code
stringlengths
31
1.05M
apis
list
extract_api
stringlengths
97
1.91M
import os import shutil import numpy as np import pandas as pd import pytest from sklearn.datasets import load_boston from vivid.cacheable import cacheable, CacheFunctionFactory from vivid.env import Settings from vivid.setup import setup_project class CountLoader: def __init__(self, loader): self.loader = loader self.counter = 0 def __call__(self, *args, **kwargs): self.counter += 1 return self.loader(return_X_y=True) @pytest.fixture(autouse=True) def cache_dir(tmpdir): root = tmpdir Settings.PROJECT_ROOT = tmpdir if os.path.exists(root): shutil.rmtree(root) CacheFunctionFactory.wrappers = {} return setup_project(root).cache @pytest.fixture(scope='function') def boston_count_loader(): return CountLoader(load_boston) def test_fixture_cache(boston_count_loader, cache_dir): @cacheable def boston(x=1): return boston_count_loader() X1, y1 = boston() assert isinstance(X1, np.ndarray) assert isinstance(y1, np.ndarray) assert boston_count_loader.counter == 1 # by default, save to env.Settings.CACHE_DIR assert os.path.exists(os.path.join(cache_dir, 'boston')) X2, y2 = boston() assert isinstance(X2, np.ndarray) assert isinstance(y2, np.ndarray) # create method is call at once assert boston_count_loader.counter == 1 np.testing.assert_array_almost_equal(X1, X2) assert 'boston' in CacheFunctionFactory.list_keys() shutil.rmtree(cache_dir) boston() assert boston_count_loader.counter == 2 boston() assert boston_count_loader.counter == 2 CacheFunctionFactory.clear_cache('boston') boston() assert boston_count_loader.counter == 3 # change argument boston(x=10) assert boston_count_loader.counter == 4 # もう一回呼び出した時は cache を使う (callされない) boston(x=10) assert boston_count_loader.counter == 4 def test_register_as_custom_name(boston_count_loader, cache_dir): @cacheable(callable_or_scope='custom_dir') def boston(): return boston_count_loader() boston() assert os.path.exists(os.path.join(cache_dir, 'custom_dir')) @pytest.mark.usefixtures('cache_dir') @pytest.mark.parametrize('output', [ pd.DataFrame([1, 2, 3, 2]), np.random.uniform(size=(100, 100)), {'hoge': [1, 2, 3]} ]) def test_generated_object_type(output): @cacheable def test(): return output test() def test_list_key(): @cacheable def hoge(): return pd.DataFrame() @cacheable def foo(): return pd.DataFrame() keys = CacheFunctionFactory.list_keys() assert 'foo' in keys assert 'hoge' in keys def test_register_function(): def create(): return pd.DataFrame([1, 2, 3]) wrapper = cacheable('hoge')(create) wrapper() assert 'hoge' in CacheFunctionFactory.list_keys() def test_cant_register_not_callable(): x = pd.DataFrame([1, 2, 3]) with pytest.raises(ValueError): cacheable(x) cacheable(lambda: x.copy()) def test_register_same_name(): def create_1(): return pd.DataFrame([1, 2, 3]) def create_2(): return None cacheable('create')(create_1) with pytest.warns(UserWarning): cacheable('create')(create_2) assert len(CacheFunctionFactory.list_keys()) == 2, CacheFunctionFactory.list_keys()
[ "pandas.DataFrame", "numpy.random.uniform", "vivid.cacheable.CacheFunctionFactory.list_keys", "pytest.warns", "os.path.exists", "pytest.fixture", "vivid.cacheable.cacheable", "pytest.raises", "vivid.setup.setup_project", "shutil.rmtree", "numpy.testing.assert_array_almost_equal", "os.path.join...
[((471, 499), 'pytest.fixture', 'pytest.fixture', ([], {'autouse': '(True)'}), '(autouse=True)\n', (485, 499), False, 'import pytest\n'), ((712, 744), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""function"""'}), "(scope='function')\n", (726, 744), False, 'import pytest\n'), ((2165, 2201), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""cache_dir"""'], {}), "('cache_dir')\n", (2188, 2201), False, 'import pytest\n'), ((583, 603), 'os.path.exists', 'os.path.exists', (['root'], {}), '(root)\n', (597, 603), False, 'import os\n'), ((1376, 1420), 'numpy.testing.assert_array_almost_equal', 'np.testing.assert_array_almost_equal', (['X1', 'X2'], {}), '(X1, X2)\n', (1412, 1420), True, 'import numpy as np\n'), ((1483, 1507), 'shutil.rmtree', 'shutil.rmtree', (['cache_dir'], {}), '(cache_dir)\n', (1496, 1507), False, 'import shutil\n'), ((1628, 1670), 'vivid.cacheable.CacheFunctionFactory.clear_cache', 'CacheFunctionFactory.clear_cache', (['"""boston"""'], {}), "('boston')\n", (1660, 1670), False, 'from vivid.cacheable import cacheable, CacheFunctionFactory\n'), ((1986, 2027), 'vivid.cacheable.cacheable', 'cacheable', ([], {'callable_or_scope': '"""custom_dir"""'}), "(callable_or_scope='custom_dir')\n", (1995, 2027), False, 'from vivid.cacheable import cacheable, CacheFunctionFactory\n'), ((2600, 2632), 'vivid.cacheable.CacheFunctionFactory.list_keys', 'CacheFunctionFactory.list_keys', ([], {}), '()\n', (2630, 2632), False, 'from vivid.cacheable import cacheable, CacheFunctionFactory\n'), ((2931, 2954), 'pandas.DataFrame', 'pd.DataFrame', (['[1, 2, 3]'], {}), '([1, 2, 3])\n', (2943, 2954), True, 'import pandas as pd\n'), ((3344, 3376), 'vivid.cacheable.CacheFunctionFactory.list_keys', 'CacheFunctionFactory.list_keys', ([], {}), '()\n', (3374, 3376), False, 'from vivid.cacheable import cacheable, CacheFunctionFactory\n'), ((613, 632), 'shutil.rmtree', 'shutil.rmtree', (['root'], {}), '(root)\n', (626, 632), False, 'import shutil\n'), ((683, 702), 'vivid.setup.setup_project', 'setup_project', (['root'], {}), '(root)\n', (696, 702), False, 'from vivid.setup import setup_project\n'), ((1158, 1191), 'os.path.join', 'os.path.join', (['cache_dir', '"""boston"""'], {}), "(cache_dir, 'boston')\n", (1170, 1191), False, 'import os\n'), ((1445, 1477), 'vivid.cacheable.CacheFunctionFactory.list_keys', 'CacheFunctionFactory.list_keys', ([], {}), '()\n', (1475, 1477), False, 'from vivid.cacheable import cacheable, CacheFunctionFactory\n'), ((2123, 2160), 'os.path.join', 'os.path.join', (['cache_dir', '"""custom_dir"""'], {}), "(cache_dir, 'custom_dir')\n", (2135, 2160), False, 'import os\n'), ((2243, 2269), 'pandas.DataFrame', 'pd.DataFrame', (['[1, 2, 3, 2]'], {}), '([1, 2, 3, 2])\n', (2255, 2269), True, 'import pandas as pd\n'), ((2275, 2309), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': '(100, 100)'}), '(size=(100, 100))\n', (2292, 2309), True, 'import numpy as np\n'), ((2512, 2526), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (2524, 2526), True, 'import pandas as pd\n'), ((2573, 2587), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (2585, 2587), True, 'import pandas as pd\n'), ((2749, 2772), 'pandas.DataFrame', 'pd.DataFrame', (['[1, 2, 3]'], {}), '([1, 2, 3])\n', (2761, 2772), True, 'import pandas as pd\n'), ((2788, 2805), 'vivid.cacheable.cacheable', 'cacheable', (['"""hoge"""'], {}), "('hoge')\n", (2797, 2805), False, 'from vivid.cacheable import cacheable, CacheFunctionFactory\n'), ((2849, 2881), 'vivid.cacheable.CacheFunctionFactory.list_keys', 'CacheFunctionFactory.list_keys', ([], {}), '()\n', (2879, 2881), False, 'from vivid.cacheable import cacheable, CacheFunctionFactory\n'), ((2964, 2989), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (2977, 2989), False, 'import pytest\n'), ((2999, 3011), 'vivid.cacheable.cacheable', 'cacheable', (['x'], {}), '(x)\n', (3008, 3011), False, 'from vivid.cacheable import cacheable, CacheFunctionFactory\n'), ((3113, 3136), 'pandas.DataFrame', 'pd.DataFrame', (['[1, 2, 3]'], {}), '([1, 2, 3])\n', (3125, 3136), True, 'import pandas as pd\n'), ((3183, 3202), 'vivid.cacheable.cacheable', 'cacheable', (['"""create"""'], {}), "('create')\n", (3192, 3202), False, 'from vivid.cacheable import cacheable, CacheFunctionFactory\n'), ((3223, 3248), 'pytest.warns', 'pytest.warns', (['UserWarning'], {}), '(UserWarning)\n', (3235, 3248), False, 'import pytest\n'), ((3258, 3277), 'vivid.cacheable.cacheable', 'cacheable', (['"""create"""'], {}), "('create')\n", (3267, 3277), False, 'from vivid.cacheable import cacheable, CacheFunctionFactory\n'), ((3304, 3336), 'vivid.cacheable.CacheFunctionFactory.list_keys', 'CacheFunctionFactory.list_keys', ([], {}), '()\n', (3334, 3336), False, 'from vivid.cacheable import cacheable, CacheFunctionFactory\n')]
import unittest import numpy as np from bltest import attr from lace.serialization import bsf, ply from lace.cache import vc class TestBSF(unittest.TestCase): @attr('missing_assets') def test_load_bsf(self): expected_mesh = ply.load(vc('/unittest/bsf/bsf_example.ply')) bsf_mesh = bsf.load(vc('/unittest/bsf/bsf_example.bsf')) np.testing.assert_array_almost_equal(bsf_mesh.v, expected_mesh.v) np.testing.assert_equal(bsf_mesh.f, expected_mesh.f)
[ "numpy.testing.assert_array_almost_equal", "bltest.attr", "lace.cache.vc", "numpy.testing.assert_equal" ]
[((166, 188), 'bltest.attr', 'attr', (['"""missing_assets"""'], {}), "('missing_assets')\n", (170, 188), False, 'from bltest import attr\n'), ((361, 426), 'numpy.testing.assert_array_almost_equal', 'np.testing.assert_array_almost_equal', (['bsf_mesh.v', 'expected_mesh.v'], {}), '(bsf_mesh.v, expected_mesh.v)\n', (397, 426), True, 'import numpy as np\n'), ((435, 487), 'numpy.testing.assert_equal', 'np.testing.assert_equal', (['bsf_mesh.f', 'expected_mesh.f'], {}), '(bsf_mesh.f, expected_mesh.f)\n', (458, 487), True, 'import numpy as np\n'), ((251, 286), 'lace.cache.vc', 'vc', (['"""/unittest/bsf/bsf_example.ply"""'], {}), "('/unittest/bsf/bsf_example.ply')\n", (253, 286), False, 'from lace.cache import vc\n'), ((316, 351), 'lace.cache.vc', 'vc', (['"""/unittest/bsf/bsf_example.bsf"""'], {}), "('/unittest/bsf/bsf_example.bsf')\n", (318, 351), False, 'from lace.cache import vc\n')]
import io, os, time from flask import Flask, jsonify, request from sklearn.externals import joblib import numpy as np import constants as const app = Flask(__name__) transformations = {} def __initialize_model(): os.environ["CUDA_VISIBLE_DEVICES"] = "-1" files = [os.path.join(const.transformer_path, f) for f in os.listdir(const.transformer_path) if os.path.isfile(os.path.join(const.transformer_path, f))] global model model = None global transformations for f in files: name = os.path.splitext(os.path.basename(f))[0] t = joblib.load(f) transformations[name] = t __initialize_model() @app.route("/predict", methods=['POST']) def predict(): from keras.models import load_model p = request.get_json() # assume dictionary on input # pressure,humidity,wind_speed,wind_deg,sensor_id # P1_minus_1,P2_minus_1,humidity_minus_1,pressure_minus_1,wind_deg_minus_1,wind_speed_minus_1, # P1_minus_2,P2_minus_2,humidity_minus_2,pressure_minus_2,wind_deg_minus_2,wind_speed_minus_2, # P1_minus_3,P2_minus_3,humidity_minus_3,pressure_minus_3,wind_deg_minus_3,wind_speed_minus_3, # P1_minus_4,P2_minus_4,humidity_minus_4,pressure_minus_4,wind_deg_minus_4,wind_speed_minus_4, # weekday, hour # bin wind directions for k_new, k_old in [(k.replace('wind_deg', 'wind_deg_bin'), k) for k in p if k.startswith('wind_deg') ]: p[k_new] = p[k_old] // 10 del p[k_old] for k in [k for k in p if k not in const.categorical_column_names]: p[k] = transformations[k].transform(np.array([p[k]]).reshape((1,-1)))[0, 0] # categoricals will be one hot encoded categories = None for k in const.categorical_column_names: dummies = transformations[k].transform(np.array([p[k]]).reshape((1,-1))).toarray() if categories is None: categories = dummies else: categories = np.concatenate((categories, dummies), axis=1) X = np.array([p['pressure'], p['humidity'], p['wind_speed'], \ p['P1_minus_1'], p['P2_minus_1'], p['humidity_minus_1'], p['pressure_minus_1'], p['wind_speed_minus_1'], \ p['P1_minus_2'], p['P2_minus_2'], p['humidity_minus_2'], p['pressure_minus_2'], p['wind_speed_minus_2'], \ p['P1_minus_3'], p['P2_minus_3'], p['humidity_minus_3'], p['pressure_minus_3'], p['wind_speed_minus_3'], \ p['P1_minus_4'], p['P2_minus_4'], p['humidity_minus_4'], p['pressure_minus_4'], p['wind_speed_minus_4']]) X = np.concatenate((X.reshape((1, 23)), categories), axis=1) # this is a bad workaround for the fact that TensorFlow and Keras don't place nice with multithreading # every worker thread will initialize its own 'model' object global model if model is None: model = load_model(const.model_path) start = time.time() p1, p2 = model.predict(X).T end = time.time() resp = jsonify(p1 = np.float64(p1[0]), p2 = np.float64(p2[0])) resp.headers[const.model_version_header_name] = const.model_version resp.headers[const.prediction_time_header_name] = '{:0.3f} ms'.format((end - start) * 1000) return resp if __name__ == "__main__": app.run(host='0.0.0.0', threaded=False, debug=False, port=80)
[ "keras.models.load_model", "os.listdir", "os.path.basename", "flask.Flask", "time.time", "numpy.array", "sklearn.externals.joblib.load", "numpy.float64", "os.path.join", "flask.request.get_json", "numpy.concatenate" ]
[((151, 166), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (156, 166), False, 'from flask import Flask, jsonify, request\n'), ((749, 767), 'flask.request.get_json', 'request.get_json', ([], {}), '()\n', (765, 767), False, 'from flask import Flask, jsonify, request\n'), ((1981, 2493), 'numpy.array', 'np.array', (["[p['pressure'], p['humidity'], p['wind_speed'], p['P1_minus_1'], p[\n 'P2_minus_1'], p['humidity_minus_1'], p['pressure_minus_1'], p[\n 'wind_speed_minus_1'], p['P1_minus_2'], p['P2_minus_2'], p[\n 'humidity_minus_2'], p['pressure_minus_2'], p['wind_speed_minus_2'], p[\n 'P1_minus_3'], p['P2_minus_3'], p['humidity_minus_3'], p[\n 'pressure_minus_3'], p['wind_speed_minus_3'], p['P1_minus_4'], p[\n 'P2_minus_4'], p['humidity_minus_4'], p['pressure_minus_4'], p[\n 'wind_speed_minus_4']]"], {}), "([p['pressure'], p['humidity'], p['wind_speed'], p['P1_minus_1'], p\n ['P2_minus_1'], p['humidity_minus_1'], p['pressure_minus_1'], p[\n 'wind_speed_minus_1'], p['P1_minus_2'], p['P2_minus_2'], p[\n 'humidity_minus_2'], p['pressure_minus_2'], p['wind_speed_minus_2'], p[\n 'P1_minus_3'], p['P2_minus_3'], p['humidity_minus_3'], p[\n 'pressure_minus_3'], p['wind_speed_minus_3'], p['P1_minus_4'], p[\n 'P2_minus_4'], p['humidity_minus_4'], p['pressure_minus_4'], p[\n 'wind_speed_minus_4']])\n", (1989, 2493), True, 'import numpy as np\n'), ((2840, 2851), 'time.time', 'time.time', ([], {}), '()\n', (2849, 2851), False, 'import io, os, time\n'), ((2895, 2906), 'time.time', 'time.time', ([], {}), '()\n', (2904, 2906), False, 'import io, os, time\n'), ((278, 317), 'os.path.join', 'os.path.join', (['const.transformer_path', 'f'], {}), '(const.transformer_path, f)\n', (290, 317), False, 'import io, os, time\n'), ((573, 587), 'sklearn.externals.joblib.load', 'joblib.load', (['f'], {}), '(f)\n', (584, 587), False, 'from sklearn.externals import joblib\n'), ((2798, 2826), 'keras.models.load_model', 'load_model', (['const.model_path'], {}), '(const.model_path)\n', (2808, 2826), False, 'from keras.models import load_model\n'), ((327, 361), 'os.listdir', 'os.listdir', (['const.transformer_path'], {}), '(const.transformer_path)\n', (337, 361), False, 'import io, os, time\n'), ((1926, 1971), 'numpy.concatenate', 'np.concatenate', (['(categories, dummies)'], {'axis': '(1)'}), '((categories, dummies), axis=1)\n', (1940, 1971), True, 'import numpy as np\n'), ((2932, 2949), 'numpy.float64', 'np.float64', (['p1[0]'], {}), '(p1[0])\n', (2942, 2949), True, 'import numpy as np\n'), ((2956, 2973), 'numpy.float64', 'np.float64', (['p2[0]'], {}), '(p2[0])\n', (2966, 2973), True, 'import numpy as np\n'), ((380, 419), 'os.path.join', 'os.path.join', (['const.transformer_path', 'f'], {}), '(const.transformer_path, f)\n', (392, 419), False, 'import io, os, time\n'), ((537, 556), 'os.path.basename', 'os.path.basename', (['f'], {}), '(f)\n', (553, 556), False, 'import io, os, time\n'), ((1581, 1597), 'numpy.array', 'np.array', (['[p[k]]'], {}), '([p[k]])\n', (1589, 1597), True, 'import numpy as np\n'), ((1779, 1795), 'numpy.array', 'np.array', (['[p[k]]'], {}), '([p[k]])\n', (1787, 1795), True, 'import numpy as np\n')]
############################################################## ### Copyright (c) 2018-present, <NAME> ### ### Style Aggregated Network for Facial Landmark Detection ### ### Computer Vision and Pattern Recognition, 2018 ### ############################################################## import numpy as np from sklearn.preprocessing import normalize import pdb def cos_dis(x, y): x = normalize(x[:,np.newaxis], axis=0).ravel() y = normalize(y[:,np.newaxis], axis=0).ravel() return np.linalg.norm(x-y) def filter_cluster(indexes, cluster_features, ratio): num_feature = cluster_features.shape[0] mean_feature = np.mean(cluster_features, axis=0) all_L1, all_L2, all_LC = [], [], [] for i in range(num_feature): x = cluster_features[i] L1 = np.sum(np.abs((x-mean_feature))) L2 = np.linalg.norm(x-mean_feature) LC = cos_dis(x, mean_feature) all_L1.append( L1 ) all_L2.append( L2 ) all_LC.append( LC ) all_L1 = np.array(all_L1) all_L2 = np.array(all_L2) all_LC = np.array(all_LC) threshold = (all_L2.max()-all_L2.min())*ratio+all_L2.min() selected = indexes[ all_L2 < threshold ] return selected.copy()
[ "numpy.abs", "numpy.mean", "numpy.array", "numpy.linalg.norm", "sklearn.preprocessing.normalize" ]
[((511, 532), 'numpy.linalg.norm', 'np.linalg.norm', (['(x - y)'], {}), '(x - y)\n', (525, 532), True, 'import numpy as np\n'), ((645, 678), 'numpy.mean', 'np.mean', (['cluster_features'], {'axis': '(0)'}), '(cluster_features, axis=0)\n', (652, 678), True, 'import numpy as np\n'), ((976, 992), 'numpy.array', 'np.array', (['all_L1'], {}), '(all_L1)\n', (984, 992), True, 'import numpy as np\n'), ((1004, 1020), 'numpy.array', 'np.array', (['all_L2'], {}), '(all_L2)\n', (1012, 1020), True, 'import numpy as np\n'), ((1032, 1048), 'numpy.array', 'np.array', (['all_LC'], {}), '(all_LC)\n', (1040, 1048), True, 'import numpy as np\n'), ((828, 860), 'numpy.linalg.norm', 'np.linalg.norm', (['(x - mean_feature)'], {}), '(x - mean_feature)\n', (842, 860), True, 'import numpy as np\n'), ((410, 445), 'sklearn.preprocessing.normalize', 'normalize', (['x[:, np.newaxis]'], {'axis': '(0)'}), '(x[:, np.newaxis], axis=0)\n', (419, 445), False, 'from sklearn.preprocessing import normalize\n'), ((459, 494), 'sklearn.preprocessing.normalize', 'normalize', (['y[:, np.newaxis]'], {'axis': '(0)'}), '(y[:, np.newaxis], axis=0)\n', (468, 494), False, 'from sklearn.preprocessing import normalize\n'), ((793, 817), 'numpy.abs', 'np.abs', (['(x - mean_feature)'], {}), '(x - mean_feature)\n', (799, 817), True, 'import numpy as np\n')]
# -------------------------------------------------------- # Focal loss # Licensed under The Apache-2.0 License [see LICENSE for details] # Written by unsky https://github.com/unsky/ # -------------------------------------------------------- """ Focal loss """ import mxnet as mx import numpy as np class FocalLossOperator(mx.operator.CustomOp): def __init__(self, gamma, alpha): super(FocalLossOperator, self).__init__() self._gamma = gamma self._alpha = alpha def forward(self, is_train, req, in_data, out_data, aux): cls_score = in_data[0].asnumpy() labels = in_data[1].asnumpy() self._labels = labels pro_ = np.exp(cls_score - cls_score.max(axis=1).reshape((cls_score.shape[0], 1))) pro_ /= pro_.sum(axis=1).reshape((cls_score.shape[0], 1)) # pro_ = mx.nd.SoftmaxActivation(cls_score) + 1e-14 # pro_ = pro_.asnumpy() self.pro_ = pro_ # restore pt for backward self._pt = pro_[np.arange(pro_.shape[0],dtype = 'int'), labels.astype('int')] ### note!!!!!!!!!!!!!!!! # focal loss value is not used in this place we should forward the cls_pro in this layer, the focal vale should be calculated in metric.py # the method is in readme # focal loss (batch_size,num_class) loss_ = -1 * np.power(1 - pro_, self._gamma) * np.log(pro_) #print "---------------" #print 'pro:',pro_[1],labels[1] self.assign(out_data[0],req[0],mx.nd.array(pro_)) def backward(self, req, out_grad, in_data, out_data, in_grad, aux): labels = self._labels pro_ = self.pro_+1e-14 #print pro_[1] #i!=j pt = self._pt + 1e-14 pt = pt.reshape(len(pt),1) dx = self._alpha*np.power(1 - pt, self._gamma - 1) * (self._gamma * (-1 * pt * pro_) * np.log(pt) + pro_ * (1 - pt)) * 1.0 #print pt[1] # print dx [1] ####i==j #reload pt pt = self._pt + 1e-14 dx[np.arange(pro_.shape[0],dtype = 'int'), labels.astype('int')] = self._alpha* np.power(1 - pt, self._gamma) * (self._gamma * pt * np.log(pt) + pt -1) * (1.0) dx /= labels.shape[0] ##batch # print "grad:", dx[1],labels[1] # print "*********************" self.assign(in_grad[0], req[0], mx.nd.array(dx)) self.assign(in_grad[1],req[1],0) @mx.operator.register('FocalLoss') class FocalLossProp(mx.operator.CustomOpProp): def __init__(self, gamma,alpha): super(FocalLossProp, self).__init__(need_top_grad=False) self._gamma = float(gamma) self._alpha = float(alpha) #print 'aa' def list_arguments(self): return ['data', 'labels'] def list_outputs(self): return ['focal_loss'] def infer_shape(self, in_shape): data_shape = in_shape[0] labels_shape = in_shape[1] out_shape = data_shape return [data_shape, labels_shape],[out_shape] def create_operator(self, ctx, shapes, dtypes): return FocalLossOperator(self._gamma,self._alpha) def declare_backward_dependency(self, out_grad, in_data, out_data): return []
[ "numpy.log", "numpy.power", "mxnet.operator.register", "numpy.arange", "mxnet.nd.array" ]
[((2443, 2476), 'mxnet.operator.register', 'mx.operator.register', (['"""FocalLoss"""'], {}), "('FocalLoss')\n", (2463, 2476), True, 'import mxnet as mx\n'), ((1392, 1404), 'numpy.log', 'np.log', (['pro_'], {}), '(pro_)\n', (1398, 1404), True, 'import numpy as np\n'), ((1518, 1535), 'mxnet.nd.array', 'mx.nd.array', (['pro_'], {}), '(pro_)\n', (1529, 1535), True, 'import mxnet as mx\n'), ((2371, 2386), 'mxnet.nd.array', 'mx.nd.array', (['dx'], {}), '(dx)\n', (2382, 2386), True, 'import mxnet as mx\n'), ((1014, 1051), 'numpy.arange', 'np.arange', (['pro_.shape[0]'], {'dtype': '"""int"""'}), "(pro_.shape[0], dtype='int')\n", (1023, 1051), True, 'import numpy as np\n'), ((1358, 1389), 'numpy.power', 'np.power', (['(1 - pro_)', 'self._gamma'], {}), '(1 - pro_, self._gamma)\n', (1366, 1389), True, 'import numpy as np\n'), ((2054, 2091), 'numpy.arange', 'np.arange', (['pro_.shape[0]'], {'dtype': '"""int"""'}), "(pro_.shape[0], dtype='int')\n", (2063, 2091), True, 'import numpy as np\n'), ((1819, 1852), 'numpy.power', 'np.power', (['(1 - pt)', '(self._gamma - 1)'], {}), '(1 - pt, self._gamma - 1)\n', (1827, 1852), True, 'import numpy as np\n'), ((2132, 2161), 'numpy.power', 'np.power', (['(1 - pt)', 'self._gamma'], {}), '(1 - pt, self._gamma)\n', (2140, 2161), True, 'import numpy as np\n'), ((1889, 1899), 'numpy.log', 'np.log', (['pt'], {}), '(pt)\n', (1895, 1899), True, 'import numpy as np\n'), ((2184, 2194), 'numpy.log', 'np.log', (['pt'], {}), '(pt)\n', (2190, 2194), True, 'import numpy as np\n')]
import os import numpy as np from smartsim import Experiment, constants from smartsim.database import PBSOrchestrator from smartredis import Client """ Launch a distributed, in memory database cluster and use the SmartRedis python client to send and recieve some numpy arrays. This example runs in an interactive allocation with at least three nodes and 1 processor per node. i.e. qsub -l select=3:ncpus=1 -l walltime=00:10:00 -A <account> -q premium -I """ def collect_db_hosts(num_hosts): """A simple method to collect hostnames because we are using openmpi. (not needed for aprun(ALPS), Slurm, etc. """ hosts = [] if "PBS_NODEFILE" in os.environ: node_file = os.environ["PBS_NODEFILE"] with open(node_file, "r") as f: for line in f.readlines(): host = line.split(".")[0] hosts.append(host) else: raise Exception("could not parse interactive allocation nodes from PBS_NODEFILE") # account for mpiprocs causing repeats in PBS_NODEFILE hosts = list(set(hosts)) if len(hosts) >= num_hosts: return hosts[:num_hosts] else: raise Exception(f"PBS_NODEFILE had {len(hosts)} hosts, not {num_hosts}") def launch_cluster_orc(exp, db_hosts, port): """Just spin up a database cluster, check the status and tear it down""" print(f"Starting Orchestrator on hosts: {db_hosts}") # batch = False to launch on existing allocation db = PBSOrchestrator(port=port, db_nodes=3, batch=False, run_command="mpirun", hosts=db_hosts) # generate directories for output files # pass in objects to make dirs for exp.generate(db, overwrite=True) # start the database on interactive allocation exp.start(db, block=True) # get the status of the database statuses = exp.get_status(db) print(f"Status of all database nodes: {statuses}") return db # create the experiment and specify PBS because cheyenne is a PBS system exp = Experiment("launch_cluster_db", launcher="pbs") db_port = 6780 db_hosts = collect_db_hosts(3) # start the database db = launch_cluster_orc(exp, db_hosts, db_port) # test sending some arrays to the database cluster # the following functions are largely the same across all the # client languages: C++, C, Fortran, Python # only need one address of one shard of DB to connect client db_address = ":".join((db_hosts[0], str(db_port))) client = Client(address=db_address, cluster=True) # put into database test_array = np.array([1,2,3,4]) print(f"Array put in database: {test_array}") client.put_tensor("test", test_array) # get from database returned_array = client.get_tensor("test") print(f"Array retrieved from database: {returned_array}") # shutdown the database because we don't need it anymore exp.stop(db)
[ "smartsim.database.PBSOrchestrator", "smartredis.Client", "numpy.array", "smartsim.Experiment" ]
[((2022, 2069), 'smartsim.Experiment', 'Experiment', (['"""launch_cluster_db"""'], {'launcher': '"""pbs"""'}), "('launch_cluster_db', launcher='pbs')\n", (2032, 2069), False, 'from smartsim import Experiment, constants\n'), ((2467, 2507), 'smartredis.Client', 'Client', ([], {'address': 'db_address', 'cluster': '(True)'}), '(address=db_address, cluster=True)\n', (2473, 2507), False, 'from smartredis import Client\n'), ((2542, 2564), 'numpy.array', 'np.array', (['[1, 2, 3, 4]'], {}), '([1, 2, 3, 4])\n', (2550, 2564), True, 'import numpy as np\n'), ((1481, 1574), 'smartsim.database.PBSOrchestrator', 'PBSOrchestrator', ([], {'port': 'port', 'db_nodes': '(3)', 'batch': '(False)', 'run_command': '"""mpirun"""', 'hosts': 'db_hosts'}), "(port=port, db_nodes=3, batch=False, run_command='mpirun',\n hosts=db_hosts)\n", (1496, 1574), False, 'from smartsim.database import PBSOrchestrator\n')]
import noise from .Math import fit_11_to_01 from noise import pnoise1, pnoise2, pnoise3 import numpy as np ''' for i in range(octaves): result = amplitude * noise(pos * frequency) frequency *= lacunarity amplitude *= gain octaves: level of detail persistence(gain): steo of amplitude lacunarity: step of frequency repeat: frequency base ''' def perlin_noise1(x, octaves=1, gain=0.5, lacunarity=2, amp=1, repeat=1024, base=0): if type(x) not in [np.ndarray, list]: return amp * fit_11_to_01(pnoise1(x, octaves, gain, lacunarity, repeat, base)) else: r = np.empty((len(x),), dtype=np.float64) for i, d in enumerate(x): r[i] = amp * fit_11_to_01(pnoise1(d, octaves, gain, lacunarity, repeat, base)) return r def perlin_noise2(x, y=None, octaves=1, gain=0.5, lacunarity=2, amp=1, repeat=1024, base=0): if y is not None: return amp * fit_11_to_01(pnoise2(x, y, octaves, gain, lacunarity, repeat, base)) else: r = np.empty((len(x),), dtype=np.float64) for i, d in enumerate(x): r[i] = amp * fit_11_to_01(pnoise2(d[0], d[1], octaves, gain, lacunarity, repeat, base)) return r def perlin_noise3(x, y=None, z=None, octaves=1, gain=0.5, lacunarity=2, amp=1, repeat=1024, base=0): if y is not None: return amp * fit_11_to_01(pnoise3(x, y, z, octaves, gain, lacunarity, repeat, base)) else: r = np.empty((len(x),), dtype=np.float64) for i, d in enumerate(x): r[i] = amp * fit_11_to_01(pnoise3(d[0], d[1], d[2], octaves, gain, lacunarity, repeat, base)) return r def snoise2(x, y=None, octaves=1, gain=0.5, lacunarity=2, amp=1, repeat=1): if y is not None: return amp * fit_11_to_01(noise.snoise2(x * repeat, y * repeat, octaves, gain, lacunarity)) else: r = np.empty((len(x),), dtype=np.float64) for i, d in enumerate(x): r[i] = amp * fit_11_to_01(noise.snoise2(d[0] * repeat, d[1] * repeat, octaves, gain, lacunarity)) return r def snoise3(x, y=None, z=None, octaves=1, gain=0.5, lacunarity=2, amp=1, repeat=1): if y is not None: return amp * fit_11_to_01(noise.snoise3(x * repeat, y * repeat, z * repeat, octaves, gain, lacunarity)) else: r = np.empty((len(x),), dtype=np.float64) for i, d in enumerate(x): r[i] = amp * fit_11_to_01(noise.snoise3(d[0] * repeat, d[1] * repeat, d[2] * repeat, octaves, gain, lacunarity)) return r def snoise4(x, y=None, z=None, w=None, octaves=1, gain=0.5, lacunarity=2, amp=1, repeat=1): if y is not None: return amp * fit_11_to_01(noise.snoise4(x * repeat, y * repeat, z * repeat, w * repeat, octaves, gain, lacunarity)) else: r = np.empty((len(x),), dtype=np.float64) for i, d in enumerate(x): r[i] = amp * fit_11_to_01(noise.snoise4(d[0] * repeat, d[1] * repeat, d[2] * repeat, d[3] * repeat, octaves, gain, lacunarity)) return r if __name__ == '__main__': d = np.random.random((10, 2)) print(snoise2(d))
[ "noise.pnoise1", "noise.pnoise3", "noise.snoise3", "noise.snoise2", "numpy.random.random", "noise.snoise4", "noise.pnoise2" ]
[((3037, 3062), 'numpy.random.random', 'np.random.random', (['(10, 2)'], {}), '((10, 2))\n', (3053, 3062), True, 'import numpy as np\n'), ((524, 575), 'noise.pnoise1', 'pnoise1', (['x', 'octaves', 'gain', 'lacunarity', 'repeat', 'base'], {}), '(x, octaves, gain, lacunarity, repeat, base)\n', (531, 575), False, 'from noise import pnoise1, pnoise2, pnoise3\n'), ((930, 984), 'noise.pnoise2', 'pnoise2', (['x', 'y', 'octaves', 'gain', 'lacunarity', 'repeat', 'base'], {}), '(x, y, octaves, gain, lacunarity, repeat, base)\n', (937, 984), False, 'from noise import pnoise1, pnoise2, pnoise3\n'), ((1356, 1413), 'noise.pnoise3', 'pnoise3', (['x', 'y', 'z', 'octaves', 'gain', 'lacunarity', 'repeat', 'base'], {}), '(x, y, z, octaves, gain, lacunarity, repeat, base)\n', (1363, 1413), False, 'from noise import pnoise1, pnoise2, pnoise3\n'), ((1766, 1830), 'noise.snoise2', 'noise.snoise2', (['(x * repeat)', '(y * repeat)', 'octaves', 'gain', 'lacunarity'], {}), '(x * repeat, y * repeat, octaves, gain, lacunarity)\n', (1779, 1830), False, 'import noise\n'), ((2195, 2271), 'noise.snoise3', 'noise.snoise3', (['(x * repeat)', '(y * repeat)', '(z * repeat)', 'octaves', 'gain', 'lacunarity'], {}), '(x * repeat, y * repeat, z * repeat, octaves, gain, lacunarity)\n', (2208, 2271), False, 'import noise\n'), ((2659, 2751), 'noise.snoise4', 'noise.snoise4', (['(x * repeat)', '(y * repeat)', '(z * repeat)', '(w * repeat)', 'octaves', 'gain', 'lacunarity'], {}), '(x * repeat, y * repeat, z * repeat, w * repeat, octaves, gain,\n lacunarity)\n', (2672, 2751), False, 'import noise\n'), ((709, 760), 'noise.pnoise1', 'pnoise1', (['d', 'octaves', 'gain', 'lacunarity', 'repeat', 'base'], {}), '(d, octaves, gain, lacunarity, repeat, base)\n', (716, 760), False, 'from noise import pnoise1, pnoise2, pnoise3\n'), ((1118, 1178), 'noise.pnoise2', 'pnoise2', (['d[0]', 'd[1]', 'octaves', 'gain', 'lacunarity', 'repeat', 'base'], {}), '(d[0], d[1], octaves, gain, lacunarity, repeat, base)\n', (1125, 1178), False, 'from noise import pnoise1, pnoise2, pnoise3\n'), ((1547, 1613), 'noise.pnoise3', 'pnoise3', (['d[0]', 'd[1]', 'd[2]', 'octaves', 'gain', 'lacunarity', 'repeat', 'base'], {}), '(d[0], d[1], d[2], octaves, gain, lacunarity, repeat, base)\n', (1554, 1613), False, 'from noise import pnoise1, pnoise2, pnoise3\n'), ((1964, 2034), 'noise.snoise2', 'noise.snoise2', (['(d[0] * repeat)', '(d[1] * repeat)', 'octaves', 'gain', 'lacunarity'], {}), '(d[0] * repeat, d[1] * repeat, octaves, gain, lacunarity)\n', (1977, 2034), False, 'import noise\n'), ((2405, 2494), 'noise.snoise3', 'noise.snoise3', (['(d[0] * repeat)', '(d[1] * repeat)', '(d[2] * repeat)', 'octaves', 'gain', 'lacunarity'], {}), '(d[0] * repeat, d[1] * repeat, d[2] * repeat, octaves, gain,\n lacunarity)\n', (2418, 2494), False, 'import noise\n'), ((2881, 2985), 'noise.snoise4', 'noise.snoise4', (['(d[0] * repeat)', '(d[1] * repeat)', '(d[2] * repeat)', '(d[3] * repeat)', 'octaves', 'gain', 'lacunarity'], {}), '(d[0] * repeat, d[1] * repeat, d[2] * repeat, d[3] * repeat,\n octaves, gain, lacunarity)\n', (2894, 2985), False, 'import noise\n')]
import numpy as np import pandas as pd from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D N_features = 2 # Number of features N_train = 1000 # Number of train samples N_test = 10000 # Number of test samples N_labels = 2 # Number of classes # Class Priors and assigning labels priors = [0.5, 0.5] train_label = np.zeros((1, N_train)) train_label = (np.random.rand(N_train) >= priors[1]).astype(int) train_label = np.array([int(-1) if (t == 0) else int(1) for t in train_label]) test_label = np.zeros((1, N_test)) test_label = (np.random.rand(N_test) >= priors[1]).astype(int) test_label = np.array([int(-1) if (t == 0) else int(1) for t in test_label]) # Assign values to data samples based on labels X_train = np.zeros(shape = [N_train, N_features]) X_test = np.zeros(shape = [N_test, N_features]) for i in range(N_train): if train_label[i] == 1: X_train[i, 0] = 4 * np.cos(np.random.uniform(-np.pi, np.pi)) X_train[i, 1] = 4 * np.sin(np.random.uniform(-np.pi, np.pi)) elif train_label[i] == -1: X_train[i, 0] = 2 * np.cos(np.random.uniform(-np.pi, np.pi)) X_train[i, 1] = 2 * np.sin(np.random.uniform(-np.pi, np.pi)) X_train[i, :] += np.random.multivariate_normal([0, 0], np.eye(2)) for i in range(N_test): if test_label[i] == 1: X_test[i, 0] = 4 * np.cos(np.random.uniform(-np.pi, np.pi)) X_test[i, 1] = 4 * np.sin(np.random.uniform(-np.pi, np.pi)) elif test_label[i] == -1: X_test[i, 0] = 2 * np.cos(np.random.uniform(-np.pi, np.pi)) X_test[i, 1] = 2 * np.sin(np.random.uniform(-np.pi, np.pi)) X_test[i, :] += np.random.multivariate_normal([0, 0], np.eye(2)) # Plot training dataset plt.scatter(X_test[(test_label == -1), 0], X_test[(test_label == -1), 1], color = "b") plt.scatter(X_test[(test_label == 1), 0], X_test[(test_label == 1), 1], color = "r") plt.xlabel("x1") plt.ylabel("x2") plt.title('Test Dataset') plt.show() # Save both datasets in a CSV file train_label = np.reshape(train_label, (1000,1)) dataset = pd.DataFrame(np.hstack((X_train, train_label))) filename = 'SVM_Dtrain_.csv' dataset.to_csv(filename, index = False) test_label = np.reshape(test_label, (10000,1)) dataset = pd.DataFrame(np.hstack((X_test, test_label))) filename = 'SVM_Dtest_.csv' dataset.to_csv(filename, index = False)
[ "matplotlib.pyplot.title", "numpy.random.uniform", "matplotlib.pyplot.show", "numpy.eye", "matplotlib.pyplot.scatter", "numpy.zeros", "numpy.hstack", "numpy.reshape", "numpy.random.rand", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel" ]
[((385, 407), 'numpy.zeros', 'np.zeros', (['(1, N_train)'], {}), '((1, N_train))\n', (393, 407), True, 'import numpy as np\n'), ((566, 587), 'numpy.zeros', 'np.zeros', (['(1, N_test)'], {}), '((1, N_test))\n', (574, 587), True, 'import numpy as np\n'), ((787, 824), 'numpy.zeros', 'np.zeros', ([], {'shape': '[N_train, N_features]'}), '(shape=[N_train, N_features])\n', (795, 824), True, 'import numpy as np\n'), ((836, 872), 'numpy.zeros', 'np.zeros', ([], {'shape': '[N_test, N_features]'}), '(shape=[N_test, N_features])\n', (844, 872), True, 'import numpy as np\n'), ((1782, 1867), 'matplotlib.pyplot.scatter', 'plt.scatter', (['X_test[test_label == -1, 0]', 'X_test[test_label == -1, 1]'], {'color': '"""b"""'}), "(X_test[test_label == -1, 0], X_test[test_label == -1, 1], color='b'\n )\n", (1793, 1867), True, 'from matplotlib import pyplot as plt\n'), ((1869, 1947), 'matplotlib.pyplot.scatter', 'plt.scatter', (['X_test[test_label == 1, 0]', 'X_test[test_label == 1, 1]'], {'color': '"""r"""'}), "(X_test[test_label == 1, 0], X_test[test_label == 1, 1], color='r')\n", (1880, 1947), True, 'from matplotlib import pyplot as plt\n'), ((1954, 1970), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""x1"""'], {}), "('x1')\n", (1964, 1970), True, 'from matplotlib import pyplot as plt\n'), ((1971, 1987), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""x2"""'], {}), "('x2')\n", (1981, 1987), True, 'from matplotlib import pyplot as plt\n'), ((1988, 2013), 'matplotlib.pyplot.title', 'plt.title', (['"""Test Dataset"""'], {}), "('Test Dataset')\n", (1997, 2013), True, 'from matplotlib import pyplot as plt\n'), ((2014, 2024), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2022, 2024), True, 'from matplotlib import pyplot as plt\n'), ((2075, 2109), 'numpy.reshape', 'np.reshape', (['train_label', '(1000, 1)'], {}), '(train_label, (1000, 1))\n', (2085, 2109), True, 'import numpy as np\n'), ((2250, 2284), 'numpy.reshape', 'np.reshape', (['test_label', '(10000, 1)'], {}), '(test_label, (10000, 1))\n', (2260, 2284), True, 'import numpy as np\n'), ((2132, 2165), 'numpy.hstack', 'np.hstack', (['(X_train, train_label)'], {}), '((X_train, train_label))\n', (2141, 2165), True, 'import numpy as np\n'), ((2307, 2338), 'numpy.hstack', 'np.hstack', (['(X_test, test_label)'], {}), '((X_test, test_label))\n', (2316, 2338), True, 'import numpy as np\n'), ((1305, 1314), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (1311, 1314), True, 'import numpy as np\n'), ((1746, 1755), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (1752, 1755), True, 'import numpy as np\n'), ((423, 446), 'numpy.random.rand', 'np.random.rand', (['N_train'], {}), '(N_train)\n', (437, 446), True, 'import numpy as np\n'), ((602, 624), 'numpy.random.rand', 'np.random.rand', (['N_test'], {}), '(N_test)\n', (616, 624), True, 'import numpy as np\n'), ((965, 997), 'numpy.random.uniform', 'np.random.uniform', (['(-np.pi)', 'np.pi'], {}), '(-np.pi, np.pi)\n', (982, 997), True, 'import numpy as np\n'), ((1034, 1066), 'numpy.random.uniform', 'np.random.uniform', (['(-np.pi)', 'np.pi'], {}), '(-np.pi, np.pi)\n', (1051, 1066), True, 'import numpy as np\n'), ((1403, 1435), 'numpy.random.uniform', 'np.random.uniform', (['(-np.pi)', 'np.pi'], {}), '(-np.pi, np.pi)\n', (1420, 1435), True, 'import numpy as np\n'), ((1471, 1503), 'numpy.random.uniform', 'np.random.uniform', (['(-np.pi)', 'np.pi'], {}), '(-np.pi, np.pi)\n', (1488, 1503), True, 'import numpy as np\n'), ((1141, 1173), 'numpy.random.uniform', 'np.random.uniform', (['(-np.pi)', 'np.pi'], {}), '(-np.pi, np.pi)\n', (1158, 1173), True, 'import numpy as np\n'), ((1210, 1242), 'numpy.random.uniform', 'np.random.uniform', (['(-np.pi)', 'np.pi'], {}), '(-np.pi, np.pi)\n', (1227, 1242), True, 'import numpy as np\n'), ((1576, 1608), 'numpy.random.uniform', 'np.random.uniform', (['(-np.pi)', 'np.pi'], {}), '(-np.pi, np.pi)\n', (1593, 1608), True, 'import numpy as np\n'), ((1644, 1676), 'numpy.random.uniform', 'np.random.uniform', (['(-np.pi)', 'np.pi'], {}), '(-np.pi, np.pi)\n', (1661, 1676), True, 'import numpy as np\n')]
import sys import torch from torchvision import transforms import cv2 import yaml import numpy as np from PIL import Image import json import uuid import time import humanfriendly import cougarvision_utils.cropping as crop_util # Adds CameraTraps to Sys path, import specific utilities with open("config/cameratraps.yml", 'r') as stream: camera_traps_config = yaml.safe_load(stream) sys.path.append(camera_traps_config['camera_traps_path']) from detection.run_tf_detector import TFDetector import visualization.visualization_utils as viz_utils # Load Configuration Settings from YML file with open("config/annotate_video.yml", 'r') as stream: config = yaml.safe_load(stream) # Load in classes, labels and color mapping classes = open('labels/megadetector.names').read().strip().split('\n') np.random.seed(42) colors = np.random.randint(0, 255, size=(len(classes), 3), dtype='uint8') image_net_labels = json.load(open("labels/labels_map.txt")) image_net_labels = [image_net_labels[str(i)] for i in range(1000)] # Loads in Label Category Mappings with open("labels/label_categories.txt") as label_category: labels = json.load(label_category) # Model Setup # Detector Model start_time = time.time() tf_detector = TFDetector(config['detector_model']) print(f'Loaded detector model in {humanfriendly.format_timespan(time.time() - start_time)}') # Classifier Model start_time = time.time() model = torch.jit.load(config['classifier_model']) model.eval() print(f'Loaded classifier model in {humanfriendly.format_timespan(time.time() - start_time)}') # Set confidence threshold conf = config['confidence'] # Input Video input_video = config['input_video'] cap = cv2.VideoCapture(input_video) # Rendered Video Setup frameSize = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))) fourcc = cv2.VideoWriter_fourcc(*'XVID') fps = 25.0 # or 30.0 for a better quality stream video = cv2.VideoWriter( 'annotated_{0}.avi'.format(input_video), fourcc, 20.0, frameSize ) while(cap.isOpened()): ret, frame = cap.read() if ret == True: # Run Megadetector t0 = time.time() result = tf_detector.generate_detections_one_image( Image.fromarray(frame), '0', conf ) print(f'forward propagation time={(time.time())-t0}') # Take crop for detection in result['detections']: img = Image.fromarray(frame) bbox = detection['bbox'] crop = crop_util.crop(img,bbox) # Run Classifier tfms = transforms.Compose([transforms.Resize(224), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),]) crop = tfms(crop).unsqueeze(0) # Perform Inference t0 = time.time() with torch.no_grad(): logits = model(crop) preds = torch.topk(logits, k=5).indices.squeeze(0).tolist() print(f'time to perform classification={(time.time())-t0}') print('-----') print(preds) label = image_net_labels[preds[0]].split(",")[0] prob = torch.softmax(logits, dim=1)[0, preds[0]].item() image = Image.fromarray(frame) if str(preds[0]) in labels['lizard']: label = 'lizard' viz_utils.draw_bounding_box_on_image(image, bbox[1], bbox[0], bbox[1] + bbox[3], bbox[0] + bbox[2], clss=preds[0], thickness=4, expansion=0, display_str_list=['{:<75} ({:.2f}%)'.format(label, prob*100)], use_normalized_coordinates=True, label_font_size=16) frame = np.asarray(image) video.write(frame) else: break video.release() cap.release()
[ "numpy.random.seed", "cv2.VideoWriter_fourcc", "yaml.safe_load", "torchvision.transforms.Normalize", "torch.no_grad", "sys.path.append", "detection.run_tf_detector.TFDetector", "torch.softmax", "torchvision.transforms.CenterCrop", "cougarvision_utils.cropping.crop", "torch.topk", "numpy.asarra...
[((811, 829), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (825, 829), True, 'import numpy as np\n'), ((1210, 1221), 'time.time', 'time.time', ([], {}), '()\n', (1219, 1221), False, 'import time\n'), ((1236, 1272), 'detection.run_tf_detector.TFDetector', 'TFDetector', (["config['detector_model']"], {}), "(config['detector_model'])\n", (1246, 1272), False, 'from detection.run_tf_detector import TFDetector\n'), ((1399, 1410), 'time.time', 'time.time', ([], {}), '()\n', (1408, 1410), False, 'import time\n'), ((1419, 1461), 'torch.jit.load', 'torch.jit.load', (["config['classifier_model']"], {}), "(config['classifier_model'])\n", (1433, 1461), False, 'import torch\n'), ((1692, 1721), 'cv2.VideoCapture', 'cv2.VideoCapture', (['input_video'], {}), '(input_video)\n', (1708, 1721), False, 'import cv2\n'), ((1848, 1879), 'cv2.VideoWriter_fourcc', 'cv2.VideoWriter_fourcc', (["*'XVID'"], {}), "(*'XVID')\n", (1870, 1879), False, 'import cv2\n'), ((371, 393), 'yaml.safe_load', 'yaml.safe_load', (['stream'], {}), '(stream)\n', (385, 393), False, 'import yaml\n'), ((398, 455), 'sys.path.append', 'sys.path.append', (["camera_traps_config['camera_traps_path']"], {}), "(camera_traps_config['camera_traps_path'])\n", (413, 455), False, 'import sys\n'), ((672, 694), 'yaml.safe_load', 'yaml.safe_load', (['stream'], {}), '(stream)\n', (686, 694), False, 'import yaml\n'), ((1139, 1164), 'json.load', 'json.load', (['label_category'], {}), '(label_category)\n', (1148, 1164), False, 'import json\n'), ((2168, 2179), 'time.time', 'time.time', ([], {}), '()\n', (2177, 2179), False, 'import time\n'), ((2252, 2274), 'PIL.Image.fromarray', 'Image.fromarray', (['frame'], {}), '(frame)\n', (2267, 2274), False, 'from PIL import Image\n'), ((2467, 2489), 'PIL.Image.fromarray', 'Image.fromarray', (['frame'], {}), '(frame)\n', (2482, 2489), False, 'from PIL import Image\n'), ((2546, 2571), 'cougarvision_utils.cropping.crop', 'crop_util.crop', (['img', 'bbox'], {}), '(img, bbox)\n', (2560, 2571), True, 'import cougarvision_utils.cropping as crop_util\n'), ((2943, 2954), 'time.time', 'time.time', ([], {}), '()\n', (2952, 2954), False, 'import time\n'), ((3385, 3407), 'PIL.Image.fromarray', 'Image.fromarray', (['frame'], {}), '(frame)\n', (3400, 3407), False, 'from PIL import Image\n'), ((3997, 4014), 'numpy.asarray', 'np.asarray', (['image'], {}), '(image)\n', (4007, 4014), True, 'import numpy as np\n'), ((2972, 2987), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (2985, 2987), False, 'import torch\n'), ((1337, 1348), 'time.time', 'time.time', ([], {}), '()\n', (1346, 1348), False, 'import time\n'), ((1541, 1552), 'time.time', 'time.time', ([], {}), '()\n', (1550, 1552), False, 'import time\n'), ((2640, 2662), 'torchvision.transforms.Resize', 'transforms.Resize', (['(224)'], {}), '(224)\n', (2657, 2662), False, 'from torchvision import transforms\n'), ((2664, 2690), 'torchvision.transforms.CenterCrop', 'transforms.CenterCrop', (['(224)'], {}), '(224)\n', (2685, 2690), False, 'from torchvision import transforms\n'), ((2725, 2746), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (2744, 2746), False, 'from torchvision import transforms\n'), ((2780, 2846), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['[0.485, 0.456, 0.406]', '[0.229, 0.224, 0.225]'], {}), '([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n', (2800, 2846), False, 'from torchvision import transforms\n'), ((2363, 2374), 'time.time', 'time.time', ([], {}), '()\n', (2372, 2374), False, 'import time\n'), ((3316, 3344), 'torch.softmax', 'torch.softmax', (['logits'], {'dim': '(1)'}), '(logits, dim=1)\n', (3329, 3344), False, 'import torch\n'), ((3151, 3162), 'time.time', 'time.time', ([], {}), '()\n', (3160, 3162), False, 'import time\n'), ((3046, 3069), 'torch.topk', 'torch.topk', (['logits'], {'k': '(5)'}), '(logits, k=5)\n', (3056, 3069), False, 'import torch\n')]
import numpy as np from scipy.stats import lomax from survival.distributions.basemodel import * from survival.optimization.optimizn import bisection class Lomax(Base): ''' We can instantiate a Lomax distribution (https://en.wikipedia.org/wiki/Lomax_distribution) with this class. ''' def __init__(self, ti=None, xi=None, k=None, lmb=None): ''' Instantiate a Lomax distribution. args: k: The shape parameter of the Lomax distribution. lmb: The scale parameter of the lomax distribution. ti: The uncensored samples for fitting the distribution. xi: The censored samples for fitting the distribution. ''' if ti is not None: self.train_org = ti self.train_inorg = xi # Initialize k and lmb to some reasonable guess self.k = 0.85 self.lmb = 1e-3 #self.newtonRh() self.gradient_descent() else: self.train = [] self.test = [] self.train_org = [] self.train_inorg = [] self.k = k self.lmb = lmb self.params = [self.k, self.lmb] def determine_params(self, k, lmb, params): ''' Determines the parameters. Defined in basemodel.py ''' return super(Lomax, self).determine_params(k, lmb, params) def pdf(self, t, k=None, lmb=None, params=None): ''' The probability distribution function (PDF) of the Lomax distribution. args: t: The value at which the PDF is to be calculated. k: The shape parameter of the Lomax distribution. lmb: The scale parameter of the lomax distribution. ''' [k, lmb] = self.determine_params(k, lmb, params) return lmb * k / (1 + lmb * t)**(k + 1) def cdf(self, t, k=None, lmb=None, params=None): ''' The cumulative density functino of the Lomax distribution. Probability that the distribution is lower than a certain value. args: t: The value at which CDF is to be calculated. k: The shape parameter of the Lomax. lmb: The sclae parameter of the Lomax. params: A 2d array with the shape and scale parameters. ''' [k, lmb] = self.determine_params(k, lmb, params) return 1 - (1 + lmb * t)**-k def survival(self, t, k=None, lmb=None, params=None): ''' The survival function for the Lomax distribution. ''' [k, lmb] = self.determine_params(k, lmb, params) return (1 + lmb * t)**-k def logpdf(self, t, k=None, lmb=None, params=None): ''' The logarithm of the PDF function. Handy for calculating log likelihood. args: t: The value at which function is to be calculated. l: The shape parameter. lmb: The scale parameter. ''' [k, lmb] = self.determine_params(k, lmb, params) return np.log(k) + np.log(lmb) - (k + 1) * np.log(1 + lmb * t) def logsurvival(self, t, k=None, lmb=None, params=None): ''' The logarithm of the survival function. Handy for calculating log likelihood. args: t: The value at which function is to be calculated. l: The shape parameter. lmb: The scale parameter. ''' [k, lmb] = self.determine_params(k, lmb, params) return -k * np.log(1 + lmb * t) def loglik(self, t, x, k=None, lmb=None, params=None): ''' The logarithm of the likelihood function. args: t: The un-censored samples. x: The censored samples. l: The shape parameter. lmb: The scale parameter. ''' [k, lmb] = self.determine_params(k, lmb, params) return sum(self.logpdf(t, k, lmb)) + sum(self.logsurvival(x, k, lmb)) def grad(self, t, x, k=0.5, lmb=0.3): ''' The gradient of the log-likelihood function. args: t: The un-censored samples. x: The censored samples. l: The shape parameter. lmb: The scale parameter. ''' n = len(t) m = len(x) delk = n / k - sum(np.log(1 + lmb * t)) - sum(np.log(1 + lmb * x)) dellmb = n / lmb - (k + 1) * sum(t / (1 + lmb * t) ) - k * sum(x / (1 + lmb * x)) return np.array([delk, dellmb]) def numerical_grad(self, t, x, k=None, lmb=None): ''' Calculates the gradient of the log-likelihood function numerically. args: t: The survival data. x: The censored data. k: The shape parameter. lmb: The scale parameter. ''' if k is None or lmb is None: k = self.k lmb = self.lmb eps = 1e-5 delk = (self.loglik(t, x, k + eps, lmb) - self.loglik(t, x, k - eps, lmb)) / 2 / eps dellmb = (self.loglik(t, x, k, lmb + eps) - self.loglik(t, x, k, lmb - eps)) / 2 / eps return np.array([delk, dellmb]) def hessian(self, t, x, k=0.5, lmb=0.3): ''' The hessian of the Loglikelihood function for Lomax. args: t: The un-censored samples. x: The censored samples. l: The shape parameter. lmb: The scale parameter. ''' n = len(t) delksq = -n / k**2 dellmbsq = -n / lmb**2 + \ (k + 1) * sum((t / (1 + lmb * t))**2) + \ k * sum((x / (1 + lmb * x))**2) delklmb = -sum(t / (1 + lmb * t)) - sum(x / (1 + lmb * x)) hess = np.zeros([2, 2]) hess[0, 0] = delksq hess[1, 1] = dellmbsq hess[0, 1] = hess[1, 0] = delklmb return hess def numerical_hessian(self, t, x, k=0.5, lmb=0.3): ''' Calculates the hessian of the log-likelihood function numerically. args: t: The survival data. x: The censored data. k: The shape parameter. lmb: The scale parameter. ''' eps = 1e-4 delksq = (self.loglik(t, x, k + 2 * eps, lmb) + self.loglik(t, x, k - 2 * eps, lmb) - 2 * self.loglik(t, x, k, lmb)) / 4 / eps / eps dellmbsq = (self.loglik(t, x, k, lmb + 2 * eps) + self.loglik(t, x, k, lmb - 2 * eps) - 2 * self.loglik(t, x, k, lmb)) / 4 / eps / eps dellmbk = (self.loglik(t, x, k + eps, lmb + eps) + self.loglik(t, x, k - eps, lmb - eps) - self.loglik(t, x, k + eps, lmb - eps) - self.loglik(t, x, k - eps, lmb + eps)) / 4 / eps / eps hess = np.zeros([2, 2]) hess[0, 0] = delksq hess[1, 1] = dellmbsq hess[0, 1] = hess[1, 0] = dellmbk return hess def gradient_descent(self, numIter=2001, params=np.array([.5, .3]), verbose=False): ''' Performs gradient descent to get the best fitting parameters for this Lomax given the censored and un-censored data. args: numIter: The maximum number of iterations for the iterative method. params: The initial guess for the shape and scale parameters respectively. verbose: Set to true for debugging. Shows progress as it fits data. ''' for i in range(numIter): lik = self.loglik(self.train_org, self.train_inorg, params[0], params[1]) directn = self.grad( self.train_org, self.train_inorg, params[0], params[1]) params2 = params for alp1 in [1e-8, 1e-7, 1e-5, 1e-3, 1e-2, .1]: params1 = params + alp1 * directn if(min(params1) > 0): lik1 = self.loglik( self.train_org, self.train_inorg, params1[0], params1[1]) if(lik1 > lik and np.isfinite(lik1)): lik = lik1 params2 = params1 params = params2 if i % 100 == 0 and verbose: print("Iteration " + str(i) + " ,objective function: " + str(lik) + " \nparams = " + str(params) + " \nGradient = " + str(directn)) print("\n########\n") return params ''' def newtonRh(self, numIter=101, params = np.array([.1,.1]), verbose=False): """ Fits the parameters of a Lomax distribution to data (censored and uncensored). Uses the Newton Raphson method for explanation, see: https://www.youtube.com/watch?v=acsSIyDugP0 args: numIter: The maximum number of iterations for the iterative method. params: The initial guess for the shape and scale parameters respectively. verbose: Set to true for debugging. Shows progress as it fits data. """ for i in range(numIter): directn = self.grad(self.train_org,self.train_inorg,params[0],params[1]) if sum(abs(directn)) < 1e-5: if verbose: print("\nIt took: " + str(i) + " Iterations.\n Gradients - " + str(directn)) self.params = params [self.k, self.lmb] = params return params lik = self.loglik(self.train_org,self.train_inorg,params[0],params[1]) step = np.linalg.solve(self.hessian(self.train_org,self.train_inorg,params[0],params[1]),directn) params = params - step if min(params) < 0: print("Drastic measures") params = params + step # undo the effect of taking the step. params2 = params for alp1 in [1e-8,1e-7,1e-5,1e-3,1e-2,.1,.5,1.0]: params1 = params - alp1 * step if(max(params1) > 0): lik1 = self.loglik(self.train_org,self.train_inorg,params1[0],params1[1]) if(lik1 > lik and np.isfinite(lik1)): lik = lik1 params2 = params1 scale = alp1 params = params2 if i % 10 == 0 and verbose: print("Iteration " + str(i) + " ,objective function: " + str(lik) + " \nparams = " + str(params) + " \nGradient = " + str(directn) + "\n##\n\n") [self.k, self.lmb] = params self.params = params return params ''' def optimal_wait_threshold(self, intervention_cost, k=None, lmb=None): ''' Gets the optimal time one should wait for a Lomax recovery before intervention. args: intervention_cost: The cost of intervening. k: The shape parameter of this Lomax distribution. lmb: The scale parameter of this Lomax distribution. ''' if k is None or lmb is None: k = self.k lmb = self.lmb return (intervention_cost * k - 1 / lmb) def expectedDT(self, tau, k, lmb, intervention_cost): ''' The expected downtime incurred when the waiting threshold is set to an arbitrary value. args: tau: The value we should set for the intervention threshold. k: The shape parameter of the current Lomax. lmb: The scale parameter of the current Lomax. intervention_cost: The cost of intervening. ''' return 1 / lmb / (k - 1) - (1 / lmb / (k - 1) \ + tau * k / (k - 1)) * 1 / (1 + lmb * tau)**k \ + (tau + intervention_cost) * 1 / (1 + lmb * tau)**k def mean(self): return Lomax.mean_s(self.k,self.lmb) @staticmethod def mean_s(k,lmb): return 1/lmb/(k-1) @staticmethod def expectedDT_s(tau, k, lmb, intervention_cost): ''' The expected downtime incurred when the waiting threshold is set to an arbitrary value (static version). args: tau: The value we should set for the intervention threshold. k: The shape parameter of the current Lomax. lmb: The scale parameter of the current Lomax. intervention_cost: The cost of intervening. ''' return 1 / lmb / (k - 1) - (1 / lmb / (k - 1) \ + tau * k / (k - 1)) * 1 / (1 + lmb * tau)**k \ + (tau + intervention_cost) * 1 / (1 + lmb * tau)**k def expectedT(self, tau, k=None, lmb=None, params=None): ''' The expected value of the Lomax conditional on it being less than tau. args: tau: Censor the Lomax here. k: The shape parameter of the current Lomax. lmb: The scale parameter of the current Lomax. params: A 2-d array with shape and scale parameters. ''' [k, lmb] = self.determine_params(k, lmb, params) return (1 / lmb / (k - 1) - (1 / lmb / (k - 1) \ + tau * k / (k - 1)) * 1 / (1 + lmb * tau)**k) / (1 - 1 / (1 + lmb * tau)**k) def samples(self, k=None, lmb=None, size=1000, params=None): ''' Generates samples for the Lomax distribution. args: k: Shape of Lomax. lmb: Scale of Lomax. size: The number of simulations to be generated. params: A 2-d array with shape and scale parameters. ''' [k, lmb] = self.determine_params(k, lmb, params) return lomax.rvs(c=k, scale=(1 / lmb), size=size) @staticmethod def samples_(k, lmb, size=1000): return lomax.rvs(c=k, scale=(1 / lmb), size=size) @staticmethod def kappafn_k(t, x, wt=None, wx=None, lmb=0.1): """ See [1] """ if wt is None: wt = np.ones(len(t)) wx = np.ones(len(x)) n = sum(wt) return n / (sum(wt*np.log(1 + lmb * t)) + sum(wx*np.log(1 + lmb * x))) @staticmethod def kappafn_lmb(t, x, wt=None, wx=None, lmb=0.1): """ See [1] """ if wt is None: wt = np.ones(len(t)) wx = np.ones(len(x)) n = sum(wt) return (n / lmb - sum(t*wt / (1 + lmb * t))) /\ (sum(t*wt / (1 + lmb * t)) + sum(x*wx / (1 + lmb * x))) @staticmethod def bisection_fn(t, x=np.array([]), wt=None, wx=None, lmb=0.1): return Lomax.kappafn_k(t, x, wt, wx, lmb) \ - Lomax.kappafn_lmb(t, x, wt, wx, lmb) @staticmethod def est_params(t, x=np.array([]), wt=None, wx=None, min_lmb=0.1, max_lmb=1000.0): fn = lambda lmb: Lomax.bisection_fn(t, x, wt, wx, lmb) lmb = bisection(fn, min_lmb, max_lmb) k = Lomax.kappafn_lmb(t, x, wt, wx, lmb) return k, lmb #[1] https://onedrive.live.com/view.aspx?resid=7CAD132A61933826%216310&id=documents&wd=target%28Math%2FSurvival.one%7C33EFE553-AA82-43B5-AD47-9900633D2A1E%2FLomax%20Wts%7C0902ADB4-A003-4CFF-98E4-95870B6E7759%2F%29onenote:https://d.docs.live.net/7cad132a61933826/Documents/Topics/Math/Survival.one#Lomax%20Wts&section-id={33EFE553-AA82-43B5-AD47-9900633D2A1E}&page-id={0902ADB4-A003-4CFF-98E4-95870B6E7759}&end def lomax_exponmix(): #### Verify Lomax equivalence with exponential-mix. k=4; theta=0.1 ## In numpy's definition, the scale, theta is inverse of Ross definition. lm = np.random.gamma(k,1/theta,size=1000) lomax_mix=np.random.exponential(1/lm) mean1=np.mean(lomax_mix) lomax_direct=lomax.rvs(c=k,scale=theta,size=1000) mean2=np.mean(lomax_direct) mean3 = theta/(k-1)
[ "survival.optimization.optimizn.bisection", "numpy.log", "numpy.random.exponential", "numpy.zeros", "numpy.isfinite", "numpy.random.gamma", "numpy.mean", "numpy.array", "scipy.stats.lomax.rvs" ]
[((15490, 15530), 'numpy.random.gamma', 'np.random.gamma', (['k', '(1 / theta)'], {'size': '(1000)'}), '(k, 1 / theta, size=1000)\n', (15505, 15530), True, 'import numpy as np\n'), ((15541, 15570), 'numpy.random.exponential', 'np.random.exponential', (['(1 / lm)'], {}), '(1 / lm)\n', (15562, 15570), True, 'import numpy as np\n'), ((15579, 15597), 'numpy.mean', 'np.mean', (['lomax_mix'], {}), '(lomax_mix)\n', (15586, 15597), True, 'import numpy as np\n'), ((15615, 15653), 'scipy.stats.lomax.rvs', 'lomax.rvs', ([], {'c': 'k', 'scale': 'theta', 'size': '(1000)'}), '(c=k, scale=theta, size=1000)\n', (15624, 15653), False, 'from scipy.stats import lomax\n'), ((15662, 15683), 'numpy.mean', 'np.mean', (['lomax_direct'], {}), '(lomax_direct)\n', (15669, 15683), True, 'import numpy as np\n'), ((4496, 4520), 'numpy.array', 'np.array', (['[delk, dellmb]'], {}), '([delk, dellmb])\n', (4504, 4520), True, 'import numpy as np\n'), ((5175, 5199), 'numpy.array', 'np.array', (['[delk, dellmb]'], {}), '([delk, dellmb])\n', (5183, 5199), True, 'import numpy as np\n'), ((5757, 5773), 'numpy.zeros', 'np.zeros', (['[2, 2]'], {}), '([2, 2])\n', (5765, 5773), True, 'import numpy as np\n'), ((6874, 6890), 'numpy.zeros', 'np.zeros', (['[2, 2]'], {}), '([2, 2])\n', (6882, 6890), True, 'import numpy as np\n'), ((7064, 7084), 'numpy.array', 'np.array', (['[0.5, 0.3]'], {}), '([0.5, 0.3])\n', (7072, 7084), True, 'import numpy as np\n'), ((13616, 13656), 'scipy.stats.lomax.rvs', 'lomax.rvs', ([], {'c': 'k', 'scale': '(1 / lmb)', 'size': 'size'}), '(c=k, scale=1 / lmb, size=size)\n', (13625, 13656), False, 'from scipy.stats import lomax\n'), ((13730, 13770), 'scipy.stats.lomax.rvs', 'lomax.rvs', ([], {'c': 'k', 'scale': '(1 / lmb)', 'size': 'size'}), '(c=k, scale=1 / lmb, size=size)\n', (13739, 13770), False, 'from scipy.stats import lomax\n'), ((14464, 14476), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (14472, 14476), True, 'import numpy as np\n'), ((14652, 14664), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (14660, 14664), True, 'import numpy as np\n'), ((14791, 14822), 'survival.optimization.optimizn.bisection', 'bisection', (['fn', 'min_lmb', 'max_lmb'], {}), '(fn, min_lmb, max_lmb)\n', (14800, 14822), False, 'from survival.optimization.optimizn import bisection\n'), ((3498, 3517), 'numpy.log', 'np.log', (['(1 + lmb * t)'], {}), '(1 + lmb * t)\n', (3504, 3517), True, 'import numpy as np\n'), ((3041, 3050), 'numpy.log', 'np.log', (['k'], {}), '(k)\n', (3047, 3050), True, 'import numpy as np\n'), ((3053, 3064), 'numpy.log', 'np.log', (['lmb'], {}), '(lmb)\n', (3059, 3064), True, 'import numpy as np\n'), ((3077, 3096), 'numpy.log', 'np.log', (['(1 + lmb * t)'], {}), '(1 + lmb * t)\n', (3083, 3096), True, 'import numpy as np\n'), ((4329, 4348), 'numpy.log', 'np.log', (['(1 + lmb * x)'], {}), '(1 + lmb * x)\n', (4335, 4348), True, 'import numpy as np\n'), ((4302, 4321), 'numpy.log', 'np.log', (['(1 + lmb * t)'], {}), '(1 + lmb * t)\n', (4308, 4321), True, 'import numpy as np\n'), ((8109, 8126), 'numpy.isfinite', 'np.isfinite', (['lik1'], {}), '(lik1)\n', (8120, 8126), True, 'import numpy as np\n'), ((14020, 14039), 'numpy.log', 'np.log', (['(1 + lmb * t)'], {}), '(1 + lmb * t)\n', (14026, 14039), True, 'import numpy as np\n'), ((14050, 14069), 'numpy.log', 'np.log', (['(1 + lmb * x)'], {}), '(1 + lmb * x)\n', (14056, 14069), True, 'import numpy as np\n')]
import numpy as np import numpy.matlib as mat from scipy import signal import scipy as sci import matplotlib.pyplot as plt import random import os import shutil class edgelink(object): """ EDGELINK - Link edge points in an image into lists ******************************************************************************************************************** Usage: [edgelist edgeim, etype] = edgelink(im, minlength, location) **Warning** 'minlength' is ignored at the moment because 'cleanedgelist' has some bugs and can be memory hungry Arguments: im - Binary edge image, it is assumed that edges have been thinned (or are nearly thin). minlength - Optional minimum edge length of interest, defaults to 1 if omitted or specified as []. Ignored at the moment. location - Optional complex valued image holding subpixel locations of edge points. For any pixel the real part holds the subpixel row coordinate of that edge point and the imaginary part holds the column coordinate. See NONMAXSUP. If this argument is supplied the edgelists will be formed from the subpixel coordinates, otherwise the the integer pixel coordinates of points in 'im' are used. ******************************************************************************************************************** Returns: edgelist - a cell array of edge lists in row,column coords in the form { [r1 c1 [r1 c1 etc } r2 c2 ... ... rN cN] ....] edgeim - Image with pixels labeled with edge number. Note that junctions in the labeled edge image will be labeled with the edge number of the last edge that was tracked through it. Note that this image also includes edges that do not meet the minimum length specification. If you want to see just the edges that meet the specification you should pass the edgelist to DRAWEDGELIST. etype - Array of values, one for each edge segment indicating its type 0 - Start free, end free 1 - Start free, end junction 2 - Start junction, end free (should not happen) 3 - Start junction, end junction 4 - Loop ******************************************************************************************************************** This function links edge points together into lists of coordinate pairs. Where an edge junction is encountered the list is terminated and a separate list is generated for each of the branches. """ def __init__(self, im, minilength): if 'im' in vars().keys(): self.edgeim = im else: raise NameError('edgelink: Image is undefined variable.') # Error. Stop. if minilength != 'Ignore': self.minilength = minilength # print('edgelink: Minimum length is % d.\n' % minilength) def get_edgelist(self): self.edgeim = (self.edgeim.copy() != 0) # Make sure image is binary self.clean = bwmorph(self.edgeim.copy(), 'clean') # Remove isolated pixels self.thin = bwmorph(self.clean, 'thin') # Make sure edges are thinned thin_float = self.thin.copy() self.row = self.edgeim.shape[0] self.col = self.edgeim.shape[1] [rj, cj], [re, ce] = findendsjunctions(thin_float) self.ej = [rj, cj], [re, ce] num_junct = len(rj) num_end = len(re) # Create a sparse matrix to mark junction locations. This makes junction testing much faster. A value # of 1 indicates a junction, a value of 2 indicates we have visited the junction. data = np.asarray([1 for ind in range(num_junct)]) if len(rj) != len(data) or len(rj) != len(cj): raise ValueError('edgelink: Junction size does not match.') junct = sci.sparse.coo_matrix((data, (rj, cj)), shape=(self.row, self.col)) # print(junct) junct = junct.tolil() self.junct = junct.copy() thin_float = thin_float * 1.0 edgeNo = -1 """ # Summary of strategy: # 1) From every end point track until we encounter an end point or junction. As we track points along an # edge image pixels are labeled with the -ve of their edge No. # 2) From every junction track out on any edges that have not been labeled yet. # 3) Scan through the image looking for any unlabeled pixels. These correspond to isolated loops that have no # junctions. """ edgelist = [] etype = [] # 1) Form tracks from each unlabeled endpoint until we encounter another endpoint or junction for idx in range(num_end): if thin_float[re[idx], ce[idx]] == 1: # Endpoint is unlabeled edgeNo = edgeNo + 1 tempedge, endType = trackedge(re[idx], ce[idx], edgeNo, 'Ignore', 'Ignore', 'Ignore', thin_float, self.junct) edgelist.append(tempedge) etype.append(endType) """ 2) Handle junctions. # Junctions are awkward when they are adjacent to other junctions. We start by looking at all the neighbours # of a junction. If there is an adjacent junction we first create a 2-element edgetrack that links the two # junctions together. We then look to see if there are any non-junction edge pixels that are adjacent to both # junctions. We then test to see which of the two junctions is closest to this common pixel and initiate an # edge track from the closest of the two junctions through this pixel. When we do this we set the # 'avoidJunction' flag in the call to trackedge so that the edge track does not immediately loop back and # terminate on the other adjacent junction. Having checked all the common neighbours of both junctions we then # track out on any remaining untracked neighbours of the junction """ for j in range(num_junct): if self.junct[rj[j], cj[j]] != 2: # We have not visited this junction self.junct[rj[j], cj[j]] = 2 # Now we have :) # Call availablepixels with edgeNo = 0 so that we get a list of available neighbouring pixels that can # be linked to and a list of all neighbouring pixels that are also junctions. [all_ra, all_ca, all_rj, all_cj] = availablepixels(rj[j], cj[j], 0, thin_float, self.junct) # For all adjacent junctions. Create a 2-element edgetrack to each adjacent junction. for k in range(len(all_rj)): edgeNo = edgeNo + 1 edgelist.append(np.array([[rj[j], cj[j]], [all_rj[k], all_cj[k]]])) etype.append(3) thin_float[rj[j], cj[j]] = -edgeNo thin_float[all_rj[k], all_cj[k]] = -edgeNo # Check if the adjacent junction has some untracked pixels that are also adjacent to the initial # junction. Thus we need to get available pixels adjacent to junction (rj(k) cj(k)). [rak, cak, rbk, cbk] = availablepixels(all_rj[k], all_cj[k], 0, thin_float, self.junct) # If both junctions have untracked neighbours that need checking... if len(all_ra) != 0 and len(rak) != 0: adj = np.asarray([all_ra, all_ca]) adj = adj.transpose() # adj[:,0] is row, adj[:,1] is col akdj = np.asarray([rak, cak]) akdj = akdj.transpose() adj_ind = {tuple(row[:]): 'None' for row in adj} akdj_ind = {tuple(row[:]): 'None' for row in akdj} commonrc = adj_ind.keys() and akdj_ind.keys() commonrc = np.asarray(list(commonrc)) # commonrc[:, 0] is row, commonrc[:, 1] is col for n in range(commonrc.shape[0]): # If one of the junctions j or k is closer to this common neighbour use that as the start of # the edge track and the common neighbour as the 2nd element. When we call trackedge we set # the avoidJunction flag to prevent the track immediately connecting back to the other # junction. distj = np.linalg.norm([commonrc[n, 0], commonrc[n, 1]] - np.array([rj[j], cj[j]])) distk = np.linalg.norm([commonrc[n, 0], commonrc[n, 1]] - np.array([all_rj[k], all_cj[k]])) edgeNo = edgeNo + 1 if distj < distk: tempedge, endType = trackedge(rj[j], cj[j], edgeNo, commonrc[n, 0], commonrc[n, 1], 1, thin_float, self.junct) edgelist.append(tempedge) else: tempedge, endType = trackedge(all_rj[k], all_cj[k], edgeNo, commonrc[n, 0], commonrc[n, 1], 1, thin_float, self.junct) edgelist.append(tempedge) etype.append(3) for m in range(len(rak)): if thin_float[rak[m], cak[m]] == 1: edgeNo = edgeNo + 1 tempedge, endType = trackedge(all_rj[k], all_cj[k], edgeNo, rak[m], cak[m], 'Ignore', thin_float, self.junct) edgelist.append(tempedge) etype.append(3) self.junct[all_rj[k], all_cj[k]] = 2 for m in range(len(all_ra)): if thin_float[all_ra[m], all_ca[m]] == 1: edgeNo = edgeNo + 1 tempedge, endType = trackedge(rj[j], cj[j], edgeNo, all_ra[m], all_ca[m], 'Ignore', thin_float, self.junct) edgelist.append(tempedge) etype.append(3) # 3) Scan through the image looking for any unlabeled pixels. These should correspond to isolated loops that # have no junctions or endpoints. for ru in range(self.row): for cu in range(self.col): if thin_float[ru, cu] == 1: edgeNo = edgeNo + 1 tempedge, endType = trackedge(ru, cu, edgeNo, 'Ignore', 'Ignore', 'Ignore', thin_float, self.junct) if endType != 0: edgelist.append(tempedge) etype.append(endType) neg_image = -thin_float.copy() thin_float = neg_image # if hasattr(self, 'minilength'): # edgelist = cleanedgelist(edgelist, self.minilength) # if hasattr(self, 'minilength'): # edgelist = cleanedgelist(edgelist, self.minilength) self.edgelist = edgelist self.etype = etype return def trackedge(rstart, cstart, edgeNo, r2, c2, avdjunct, edgeim, junct): """ EDGELINK - Link edge points in an image into lists ******************************************************************************************************************** Function to track all the edge points starting from an end point or junction. As it tracks it stores the coords of the edge points in an array and labels the pixels in the edge image with the -ve of their edge number. This continues until no more connected points are found, or a junction point is encountered. ******************************************************************************************************************** Usage: edgepoints = trackedge(rstart, cstart, edgeNo, r2, c2, avdjunct, edgeim) Arguments: rstart, cstart - Row and column No of starting point. edgeNo - The current edge number. r2, c2 - Optional row and column coords of 2nd point. avoidJunction - Optional flag indicating that (r2,c2) should not be immediately connected to a junction (if possible). edgeim - Thinned edge image junct - Junctions map ******************************************************************************************************************** Returns: edgepoints - Nx2 array of row and col values for each edge point. endType - 0 for a free end 1 for a junction 5 for a loop ******************************************************************************************************************** """ if avdjunct == 'Ignore': avdjunct = 0 edgepoints = np.array([rstart, cstart]) # Start a new list for this edge. edgepoints = np.reshape(edgepoints, [1, 2]) edgeim[rstart, cstart] = -edgeNo # Edge points in the image are encoded by -ve of their edgeNo. preferredDirection = 0 # Flag indicating we have/not a preferred direction. # If the second point has been supplied add it to the track and set the path direction if r2 != 'Ignore' and c2 != 'Ignore': addpoint = np.array([r2, c2]) addpoint = np.reshape(addpoint, [1, 2]) edgepoints = np.vstack((edgepoints, addpoint)) # row = edge[:, 0], col = edge[:, 1] edgeim[r2, c2] = -edgeNo # Initialise direction vector of path and set the current point on the path dirn = unitvector(np.array([r2 - rstart, c2 - cstart])) r = r2 c = c2 preferredDirection = 1 else: dirn = np.array([0, 0]) r = rstart c = cstart # Find all the pixels we could link to [ra, ca, rj, cj] = availablepixels(r, c, edgeNo, edgeim, junct) while len(ra) != 0 or len(rj) != 0: #First see if we can link to a junction. Choose the junction that results in a move that is as close as possible # to dirn. If we have no preferred direction, and there is a choice, link to the closest junction # We enter this block: # IF there are junction points and we are not trying to avoid a junction # OR there are junction points and no non-junction points, ie we have to enter it even if we are trying to # avoid a junction if (len(rj) != 0 and not avdjunct) or (len(rj) != 0 and len(ra) == 0): # If we have a preferred direction choose the junction that results in a move that is as close as possible # to dirn. if preferredDirection: dotp = -np.inf for idx in range(len(rj)): dirna = unitvector(np.array([rj[idx] - r, cj[idx] - c])) dp = np.sum(dirn * dirna) if dp > dotp: dotp = dp rbest, cbest = rj[idx], cj[idx] dirnbest = dirna else: # Otherwise if we have no established direction, we should pick a 4-connected junction if possible as # it will be closest. This only affects tracks of length 1 (Why do I worry about this...?!). distbest = np.inf for idx in range(len(rj)): dist = np.sum(np.abs(np.array([rj[idx] -r, cj[idx] -c]))) if dist < distbest: rbest, cbest = rj[idx], cj[idx] distbest = dist dirnbest = unitvector(np.array([rj[idx] - r, cj[idx] - c])) preferredDirection = 1 else: # If there were no junctions to link to choose the available non-junction pixel that results in a move # that is as close as possible to dirn dotp = -np.inf for idx in range(len(ra)): dirna = unitvector(np.array([ra[idx] - r, ca[idx] - c])) dp = np.sum(dirn * dirna) if dp > dotp: dotp = dp rbest, cbest = ra[idx], ca[idx] dirnbest = dirna avdjunct = 0 # Clear the avoidJunction flag if it had been set # Append the best pixel to the edgelist and update the direction and EDGEIM r, c = rbest, cbest addpoint = np.array([r, c]) addpoint = np.reshape(addpoint, [1, 2]) edgepoints = np.vstack((edgepoints, addpoint)) # row = edge[:, 0], col = edge[:, 1] dirn = dirnbest edgeim[r, c] = -edgeNo # If this point is a junction exit here if junct[r, c]: endType = 1 return edgepoints, endType else: [ra, ca, rj, cj] = availablepixels(r, c, edgeNo, edgeim, junct) # If we get here we are at an endpoint or our sequence of pixels form a loop. If it is a loop the edgelist should # have start and end points matched to form a loop. If the number of points in the list is four or more (the # minimum number that could form a loop), and the endpoints are within a pixel of each other, append a copy of the # first point to the end to complete the loop endType = 0 # Mark end as being free, unless it is reset below if len(edgepoints) >= 4: if abs(edgepoints[0, 0] - edgepoints[-1, 0]) <= 1 and abs(edgepoints[0, 1] - edgepoints[-1, 1]) <= 1: edgepoints = np.vstack((edgepoints, edgepoints[0, :])) endType = 5 return edgepoints, endType def cleanedgelist(edgelist, minlength): """ CLEANEDGELIST - remove short edges from a set of edgelists ******************************************************************************************************************** Function to clean up a set of edge lists generated by EDGELINK so that isolated edges and spurs that are shorter that a minimum length are removed. This code can also be use with a set of line segments generated by LINESEG. Usage: nedgelist = cleanedgelist(edgelist, minlength) ******************************************************************************************************************** Arguments: edgelist - a cell array of edge lists in row,column coords in the form { [r1 c1 [r1 c1 etc } r2 c2 ... ... rN cN] ....] minlength - minimum edge length of interest ******************************************************************************************************************** Returns: nedgelist - the new, cleaned up set of edgelists """ Nedges = len(edgelist) Nnodes = 2 * Nedges # Each edgelist has two end nodes - the starting point and the ending point. We build up an adjacency/connection # matrix for each node so that we can determine which, if any, edgelists are connected to a node. We also maintain # an adjacency matrix for the edges themselves. # It is tricky maintaining all this information but it does allow the code to run much faster. # First extract the end nodes from each edgelist. The nodes are numbered so that the start node has number # 2*edgenumber-1 and the end node has number 2*edgenumber node = np.zeros((Nnodes, 2)) for n in range(Nedges): node[2*n, :] = edgelist[n][0, :] node[2*n+1, :] = edgelist[n][-1, :] A = np.zeros((Nnodes, Nnodes)) B = np.zeros((Nedges, Nedges)) # Now build the adjacency/connection matrices. for n in range(Nnodes - 1): for m in range(n+1, Nnodes): # If nodes m & n are connected cond1 = node[n, 0] == node[m, 0] cond2 = node[n, 1] == node[m, 1] A[n, m] = cond1 and cond2 A[m, n] = A[n, m] if A[n, m]: edgen = int(np.fix(n / 2)) edgem = int(np.fix(m / 2)) B[edgen, edgem] = 1 B[edgem, edgen] = 1 # If we sum the columns of the adjacency matrix we get the number of other edgelists that are connected to an edgelist node_connect = sum(A) # Connection count array for nodes edge_connect = sum(B) # Connection count array for edges # Check every edge to see if any of its ends are connected to just one edge. This should not happen, but # occasionally does due to a problem in EDGELINK. Here we simply merge it with the edge it is connected to. # Ultimately I want to be able to remove this block of code. I think there are also some cases that are (still) # not properly handled by CLEANEDGELIST and there may be a case for repeating this block of code at the end for # another final cleanup pass for n in range(Nedges): if B[(n, n)] == 0 and len(edgelist[n]) != 0: [spurdegree, spurnode, startnode, sconns, endnode, econns] = connectioninfo(n, node_connect, edgelist) if sconns == 1: node2merge = np.where(A[startnode, :]) [A, B, edgelist, node_connect, edge_connect] = mergenodes(node2merge[0], startnode, A, B, edgelist, node_connect, edge_connect) if len(edgelist[n]) != 0: if econns == 1: node2merge = np.where(A[endnode, :]) [A, B, edgelist, node_connect, edge_connect] = mergenodes(node2merge[0], endnode, A, B, edgelist, node_connect, edge_connect) # Now check every edgelist, if the edgelength is below the minimum length check if we should remove it. if minlength > 0: for n in range(Nedges): [spurdegree, spurnode, _, _, _, _] = connectioninfo(n, node_connect, edgelist) if len(edgelist[n]) != 0 and edgelistlength(edgelist[n]) < minlength: # Remove unconnected lists, or lists that are only connected to themselves. if not edge_connect[n] or (edge_connect[n] == 1 and B[n, n] == 1): A, B, edgelist, node_connect, edge_connect = removeedge(n, edgelist, A, B, node_connect, edge_connect) elif spurdegree == 2: linkingedges = np.where(B[n, :]) if len(linkingedges[0]) == 1: A, B, edgelist, node_connect, edge_connect = removeedge(n, edgelist, A, B, node_connect, edge_connect) else: spurs = n length = edgelistlength(edgelist[n]) for i in range(len(linkingedges[0])): [spurdegree, _, _, _, _, _] = connectioninfo(linkingedges[0][i], node_connect, edgelist) if spurdegree: spurs = np.hstack((spurs, linkingedges[0][i])) length = np.hstack((length, edgelistlength(edgelist[linkingedges[0][i]]))) linkingedges = np.hstack((linkingedges[0], n)) if isinstance(spurs, np.ndarray): i = np.argmin(length) edge2delete = spurs[i] else: i = 0 edge2delete = spurs [spurdegree, spurnode, _, _, _, _] = connectioninfo(edge2delete, node_connect, edgelist) node2merge = np.where(A[spurnode, :]) if len(node2merge[0]) != 2: raise ValueError('Attempt to merge other than two nodes.') A, B, edgelist, node_connect, edge_connect = removeedge(edge2delete, edgelist, A, B, node_connect, edge_connect) [A, B, edgelist, node_connect, edge_connect] = mergenodes(node2merge[0][0], node2merge[0][1], A, B, edgelist, node_connect, edge_connect) elif spurdegree == 3: A, B, edgelist, node_connect, edge_connect = removeedge(n, edgelist, A, B, node_connect, edge_connect) for n in range(Nedges): if len(edgelist[n]) != 0 and edgelistlength(edgelist[n]) < minlength: if not edge_connect[n] or (edge_connect[n] == 1 and B[n, n] == 1): A, B, edgelist, node_connect, edge_connect = removeedge(n, edgelist, A, B, node_connect, edge_connect) m = 0 nedgelist = [] for n in range(Nedges): if len(edgelist[n]) != 0: m = m + 1 nedgelist.append(edgelist[n]) return nedgelist def bwmorph(image, operation): """ BWMORPH - Make the extracted edges thin and clean. Refer BWMORPH function in MATLAB. ******************************************************************************************************************** """ if operation == 'clean': lut = mat.repmat(np.vstack((np.zeros((16, 1)), np.ones((16, 1)))), 16, 1) ## identity lut[16, 0] = 0 bool_lut = lut != 0 bool_image = image != 0 image2 = applylut(bool_image, bool_lut); return image2 if operation == 'thin': lut1 = np.array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,1,1,0,0,1,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,1,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,1,1,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,1,1,0,0,0,0,0,0,0,1,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1, 0,0,0,1,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,1,0,1,0,0,0,1,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,1,0,0,0,1,0,1,1,1,1,0,0,1,1,0,0]) lut1 = np.reshape(lut1, (lut1.shape[0], 1)) bool_lut1 = lut1 != 0 lut2 = np.array([1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,1,1,1,0,1,0,1,1,0,0,0,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0, 0,0,1,1,0,0,0,0,0,1,1,0,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,1,1,1,1,0,0,0,1,1,0,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,0,1,1,1,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,1,0,1,0,0,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,0,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1, 0,1,0,0,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,0,1,0,1,1,1,0,1,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,0,0,1,0,1,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,1,0,1,0,0,1,0,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,0,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,0,1,0,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]) lut2 = np.reshape(lut2, (lut2.shape[0], 1)) bool_lut2 = lut2 != 0 bool_image = image != 0 image2 = bool_image & applylut(applylut(bool_image, bool_lut1), bool_lut2) return image2 def applylut(bw, lut): """ applylut - Returns the result of a neighbour operation using the lookup table <lut> which can be created by makelut. ******************************************************************************************************************** Usage: [bw2] = applylut(bw, lut) Arguments: bw - Binary edge image, it is assumed that isolated pixel is eliminated. lut - Look Up Table. A pre-calculated look up table of neighborhoods pixels. ******************************************************************************************************************** Returns: bw2 - a binary image that returns pixel in look up table """ if (lut.shape[0], lut.shape[1]) != (512, 1): raise ValueError('applylut: LUT size is not as expected <512, 1>.') nq = np.log2(len(lut)) n = np.sqrt(nq); if np.floor(n) != n: raise ValueError("applylut: LUT length is not as expected. Use makelut to create it.") power = np.asarray(range(int(nq-1), -1, -1)) two_power = np.power(2, power) w = np.reshape(two_power, [int(n), int(n)]) w = w.transpose() idx = signal.correlate2d(bw, w, mode='same') # idx = idx.transpose() row, col = idx.shape[0], idx.shape[1] idx_re = np.reshape(idx, [1, row * col]) temp = [] for ind in range(idx_re.shape[1]): temp.append(lut[idx_re[0, ind], 0]) temp = np.asarray(temp) temp = np.reshape(temp, [row, col]) A = temp return A def findendsjunctions(edge, disp=0): """ findendsjunctions - find junctions and endings in a line/edge image ******************************************************************************************************************** Arguments: edgeim - A binary image marking lines/edges in an image. It is assumed that this is a thinned or skeleton image disp - An optional flag 0/1 to indicate whether the edge image should be plotted with the junctions and endings marked. This defaults to 0. ******************************************************************************************************************** Returns: juncs = [rj, cj] - Row and column coordinates of junction points in the image. ends = [re, ce] - Row and column coordinates of end points in the image. ******************************************************************************************************************** """ # Set up look up table to find junctions. To do this we use the function defined at the end of this file to test # that the centre pixel within a 3x3 neighbourhood is a junction. imgtile0 = get_imgtile(edge, start=0) imgtile1 = get_imgtile(edge, start=1) diff = np.sum(np.abs(imgtile0 - imgtile1), axis=2) ends = np.int32(diff == 2) * edge junctions = np.int32(diff >= 6) * edge juncs = np.where(junctions > 0) endcs = np.where(ends > 0) return juncs, endcs def get_imgtile(img, start): """ get_imgtile - reach the neighborhood pixel value of a pixel and store them in depth layer ******************************************************************************************************************** Arguments: img - a binary image with img.shape=[height, width]. start - store neighborhood pixel value from <start>. ******************************************************************************************************************** Returns: imgtile - a 3d numpy array with imgtile.shape=[height, width, 8]. imgtile[hth, wth, :] is the neighbourhood pixel value of img[hth, wth]. for instance: if start == 0: imgtile[hth, wth, :] = [t[0], t[1], ..., t[7]] t[0] t[7] t[6] t[1] o t[5] t[2] t[3] t[4] ******************************************************************************************************************** """ height, width = img.shape[0], img.shape[1] imgtile = np.zeros((height, width, 8)) template = np.zeros((height+2, width+2)) template[1:-1, 1:-1] = img ind = np.array([0, 1, 2, 3, 4, 5, 6, 7]) ind = (ind + start) % 8 imgtile[:,:,ind[0]] = template[0: height , 0: width] imgtile[:,:,ind[1]] = template[1: height+1, 0: width] imgtile[:,:,ind[2]] = template[2: height+2, 0: width] imgtile[:,:,ind[3]] = template[2: height+2, 1: width+1] imgtile[:,:,ind[4]] = template[2: height+2, 2: width+2] imgtile[:,:,ind[5]] = template[1: height+1, 2: width+2] imgtile[:,:,ind[6]] = template[0: height+0, 2: width+2] imgtile[:,:,ind[7]] = template[0: height+0, 1: width+1] return imgtile def unitvector(v): nv = v / np.sqrt(sum(np.square(v))) return nv def availablepixels(rp, cp, edgeNo, edgeim, junct): """ AVAILABLEPIXELS - Find all the pixels that could be linked to point r, c ******************************************************************************************************************** Arguments: rp, cp - Row, col coordinates of pixel of interest. edgeNo - The edge number of the edge we are seeking to track. If not supplied its value defaults to 0 resulting in all adjacent junctions being returned, (see note below) ******************************************************************************************************************** Returns: ra, ca - Row and column coordinates of available non-junction pixels. rj, cj - Row and column coordinates of available junction pixels. A pixel is available for linking if it is: 1) Adjacent, that is it is 8-connected. 2) Its value is 1 indicating it has not already been assigned to an edge 3) or it is a junction that has not been labeled -edgeNo indicating we have not already assigned it to the current edge being tracked. If edgeNo is 0 all adjacent junctions will be returned If edgeNo not supplied set to 0 to allow all adjacent junctions to be returned ******************************************************************************************************************** """ if 'edgeNo' not in vars().keys(): edgeNo = 0 row, col = edgeim.shape[0], edgeim.shape[1] # row and column offsets for the eight neighbours of a point roff = np.array([-1, 0, 1, 1, 1, 0, -1, -1]) coff = np.array([-1, -1, -1, 0, 1, 1, 1, 0]) r = rp + roff c = cp + coff # Find indices of arrays of r and c that are within the image bounds cond1 = np.where(r >= 0) cond2 = np.where(r < row) conr = set(cond1[0]) & set(cond2[0]) cond3 = np.where(c >= 0) cond4 = np.where(c < col) conc = set(cond3[0]) & set(cond4[0]) ind = list(conr & conc) ra, ca, rj, cj = [], [], [], [] # A pixel is available for linking if its value is 1 and it is not a labeled junction -edgeNo for idx in ind: if edgeim[r[idx], c[idx]] == 1 and junct[r[idx], c[idx]] != 1: ra.append(r[idx]) ca.append(c[idx]) elif edgeim[r[idx], c[idx]] != -edgeNo and junct[r[idx], c[idx]] == 1: rj.append(r[idx]) cj.append(c[idx]) ra = np.asarray(ra) ca = np.asarray(ca) rj = np.asarray(rj) cj = np.asarray(cj) return ra, ca, rj, cj def drawedgelist(edgelist, lw, col, rowscols, name): """ DRAWEDGELIST - Plot and saved the edgelist ******************************************************************************************************************** """ if lw == 'Ignore': lw = 1 if col == 'Ignore': col = np.array([0, 0, 1]) Nedge = len(edgelist) if rowscols != 'Ignore': [rows, cols] = rowscols if col == 'rand': col = hsv(Nedge) elif col == 'mono': col = hsv(1) col = col * Nedge else: raise ValueError('Color not specified properly') plt.figure(figsize=(6,8)) for idx in range(Nedge): plt.plot(edgelist[idx][:, 1], edgelist[idx][:, 0], color=col[idx]) plt.axis([-10, cols + 20, rows + 20, -20]) # plt.axis('scaled') plt.axis('off') plt.savefig('%s.jpg' % name, dpi=500, bbox_inches='tight') plt.close() # plt.show() def hsv(Nedge): # Create random color for <drawedgelist> color = [] for idx in range(Nedge): color.append(randomcolor()) return color def connectioninfo(n, node_connect, edgelist): # Function to provide information about the connections at each end of an edgelist # [spurdegree, spurnode, startnode, sconns, endnode, econns] = connectioninfo(n) # spurdegree - If this is non-zero it indicates this edgelist is a spur, the value is the number of edges this spur # is connected to. # spurnode - If this is a spur spurnode is the index of the node that is connected to other edges, 0 otherwise. # startnode - index of starting node of edgelist. # endnode - index of end node of edgelist. # sconns - number of connections to start node. # econns - number of connections to end node. if len(edgelist[n]) == 0: spurdegree, spurnode, startnode, sconns, endnode, econns = 0, 0, 0, 0, 0, 0 return spurdegree, spurnode, startnode, sconns, endnode, econns startnode = 2 * n endnode = 2 * n + 1 sconns = node_connect[startnode] econns = node_connect[endnode] if sconns == 0 and econns >= 1: spurdegree = econns spurnode = endnode elif sconns >= 1 and econns == 0: spurdegree = sconns spurnode = startnode else: spurdegree = 0 spurnode = 0 return spurdegree, spurnode, startnode, sconns, endnode, econns def mergenodes(n1, n2, A, B, edgelist, node_connect, edge_connect): # Internal function to merge 2 edgelists together at the specified nodes and perform the necessary updates to the # edge adjacency and node adjacency matrices and the connection count arrays edge1 = int(np.fix(n1 / 2)) edge2 = int(np.fix(n2 / 2)) s1 = 2 * edge1 e1 = 2 * edge1 + 1 s2 = 2 * edge2 e2 = 2 * edge2 + 1 if edge1 == edge2: raise TypeError('Try to merge an edge with itself.\n') if not A[n1, n2]: raise TypeError('Try to merge nodes that are not connected.\n') if (n1 % 2): flipedge1 = 0 else: flipedge1 = 1 if n2 % 2: flipedge2 = 1 else: flipedge2 = 0 # Join edgelists together - with appropriate reordering depending on which end is connected to which. The result # is stored in edge1 if not flipedge1 and not flipedge2: edgelist[edge1] = np.vstack((edgelist[edge1], edgelist[edge2])) A[e1, :] = A[e2, :] A[:, e1] = A[:, e2] node_connect[e1] = node_connect[e2] elif not flipedge1 and flipedge2: edgelist[edge1] = np.vstack((edgelist[edge1], np.flipud(edgelist[edge2]))) A[e1, :] = A[s2, :] A[:, e1] = A[:, s2] node_connect[e1] = node_connect[s2] elif flipedge1 and not flipedge2: edgelist[edge1] = np.vstack((np.flipud(edgelist[edge1]), edgelist[edge2])) A[s1, :] = A[e1, :] A[:, s1] = A[:, e1] A[e1, :] = A[e2, :] A[:, e1] = A[:, e2] node_connect[s1] = node_connect[e1] node_connect[e1] = node_connect[e2] elif flipedge1 and flipedge2: edgelist[edge1] = np.vstack((np.flipud(edgelist[edge1]), np.flipud(edgelist[edge2]))) A[s1, :] = A[e1, :] A[:, s1] = A[:, e1] A[e1, :] = A[s2, :] A[:, e1] = A[:, s2] node_connect[s1] = node_connect[e1] node_connect[e1] = node_connect[s2] else: raise ValueError('Edgelists cannot be merged.') B[edge1, :] = np.logical_or(B[edge1, :], B[edge2, :]) * 1 B[:, edge1] = np.logical_or(B[:, edge1], B[:, edge2]) * 1 B[edge1, edge1] = 0 edge_connect = sum(B) node_connect = sum(A) A, B, edgelist, node_connect, edge_connect = removeedge(edge2, edgelist, A, B, node_connect, edge_connect) return A, B, edgelist, node_connect, edge_connect def removeedge(n, edgelist, A, B, node_connect, edge_connect): edgelist[n] = [] edge_connect = edge_connect - B[n, :] edge_connect[n] = 0 B[n, :] = 0 B[:, n] = 0 nodes2delete = [2*n, 2*n + 1] node_connect = node_connect - A[nodes2delete[0], :] node_connect = node_connect - A[nodes2delete[1], :] A[nodes2delete, :] = 0 A[:, nodes2delete] = 0 return A, B, edgelist, node_connect, edge_connect def edgelistlength(edgelist): diff_sqr = np.square(edgelist[0:-1, :] - edgelist[1:, :]) row_sqrtsum = np.sqrt(np.sum(diff_sqr, 1)) l = np.sum(row_sqrtsum) return l def randomcolor(): colorArr = ['1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'] color = "" for i in range(6): color += colorArr[random.randint(0,14)] return "#"+color def seglist(edgelist, tol): """ LINESEG - Form straight line segements from an edge list. ******************************************************************************************************************** Usage: seglist = lineseg(edgelist, tol) ******************************************************************************************************************** Arguments: edgelist - Cell array of edgelists where each edgelist is an Nx2 array of (row col) coords. tol - Maximum deviation from straight line before a segment is broken in two (measured in pixels). Returns: seglist - A cell array of in the same format of the input edgelist but each seglist is a subsampling of its corresponding edgelist such that straight line segments between these subsampled points do not deviate from the original points by more than tol. ******************************************************************************************************************** This function takes each array of edgepoints in edgelist, finds the size and position of the maximum deviation from the line that joins the endpoints, if the maximum deviation exceeds the allowable tolerance the edge is shortened to the point of maximum deviation and the test is repeated. In this manner each edge is broken down to line segments, each of which adhere to the original data with the specified tolerance. ******************************************************************************************************************** """ Nedge = len(edgelist) seglist = [] for e in range(Nedge): temp = [] # Note that (col, row) corresponds to (x,y) y = edgelist[e][:, 0] y = np.reshape(y, (1, y.shape[0])) x = edgelist[e][:, 1] x = np.reshape(x, (1, x.shape[0])) fst = 0 # Indices of first and last points in edge lst = x.shape[1] - 1 # Segment being considered Npts = 1 temp.append(np.asarray([y[0, fst], x[0, fst]])) while fst < lst: [m, i, D, s] = maxlinedev(x[0, fst:lst+1], y[0, fst:]) # Find size and position of maximum deviation tol1 = tol * ((10 - np.exp(-s)) / (10 + np.exp(-s))) while m > tol1: # while deviation is > tol lst = i + fst # Shorten line to point of max deviation by adjusting lst [m, i, D, s] = maxlinedev(x[0, fst:lst+1], y[0, fst:lst+1]) tol1 = tol * ((10 - np.exp(-s)) / (10 + np.exp(-s))) Npts = Npts + 1 temp.append(np.asarray([y[0, lst], x[0, lst]])) fst = lst lst = x.shape[1] - 1 temp = np.asarray(temp) seglist.append(temp) return seglist def maxlinedev(x, y): """ MAXLINEDEV - Find max deviation from a line in an edge contour. ******************************************************************************************************************** Function finds the point of maximum deviation from a line joining the endpoints of an edge contour. ******************************************************************************************************************** Usage: [maxdev, index, D, totaldev] = maxlinedev(x,y) ******************************************************************************************************************** Arguments: x, y - arrays of x,y (col,row) indicies of connected pixels on the contour. ******************************************************************************************************************** Returns: maxdev - Maximum deviation of contour point from the line joining the end points of the contour (pixels). index - Index of the point having maxdev. D - Distance between end points of the contour so that one can calculate maxdev/D - the normalised error. totaldev - Sum of the distances of all the pixels from the line joining the endpoints. ******************************************************************************************************************** """ Npts = len(x) if Npts == 1: raise ValueError('Contour of length 1') maxdev, index, D, totaldev = 0, 0, 1, 0 return maxdev, index, D, totaldev elif Npts == 0: raise ValueError('Contour of length 0') x_diff_sq = np.square(x[0] - x[-1]) y_diff_sq = np.square(y[0] - y[-1]) D = np.sqrt(x_diff_sq + y_diff_sq) if D > 2.2204e-16: y1my2 = y[0] - y[-1] x2mx1 = x[-1] - x[0] C = y[-1] * x[0] - y[0] * x[-1] # Calculate distance from line segment for each contour point d = abs(x * y1my2 + y * x2mx1 + C) / D else: # End points are coincident, calculate distances from 1st point x_sq = np.square(x - x[0]) y_sq = np.square(y - y[0]) D = 1 d = np.sqrt(x_sq + y_sq) [maxdev, index] = [np.max(d), np.argmax(d)] totaldev = sum(np.square(d)) return maxdev, index, D, totaldev def clean_dir(outpath): # clean_path = os.path.join(path, dirname) if os.path.isdir(outpath): shutil.rmtree(outpath) print('Clean directory %s\n' % outpath) else: print('No directory\n') def create_dir(outpath): # cre_path = os.path.join(path, dirname) isexists = os.path.exists(outpath) if not isexists: os.makedirs(outpath) print('Created directory %s\n' % outpath) else: print('Directory existed\n')
[ "numpy.sum", "numpy.abs", "numpy.argmax", "numpy.floor", "numpy.ones", "numpy.argmin", "matplotlib.pyplot.figure", "numpy.exp", "shutil.rmtree", "random.randint", "numpy.power", "matplotlib.pyplot.close", "os.path.exists", "scipy.sparse.coo_matrix", "numpy.max", "numpy.reshape", "num...
[((13222, 13248), 'numpy.array', 'np.array', (['[rstart, cstart]'], {}), '([rstart, cstart])\n', (13230, 13248), True, 'import numpy as np\n'), ((13308, 13338), 'numpy.reshape', 'np.reshape', (['edgepoints', '[1, 2]'], {}), '(edgepoints, [1, 2])\n', (13318, 13338), True, 'import numpy as np\n'), ((19878, 19899), 'numpy.zeros', 'np.zeros', (['(Nnodes, 2)'], {}), '((Nnodes, 2))\n', (19886, 19899), True, 'import numpy as np\n'), ((20022, 20048), 'numpy.zeros', 'np.zeros', (['(Nnodes, Nnodes)'], {}), '((Nnodes, Nnodes))\n', (20030, 20048), True, 'import numpy as np\n'), ((20057, 20083), 'numpy.zeros', 'np.zeros', (['(Nedges, Nedges)'], {}), '((Nedges, Nedges))\n', (20065, 20083), True, 'import numpy as np\n'), ((29120, 29131), 'numpy.sqrt', 'np.sqrt', (['nq'], {}), '(nq)\n', (29127, 29131), True, 'import numpy as np\n'), ((29319, 29337), 'numpy.power', 'np.power', (['(2)', 'power'], {}), '(2, power)\n', (29327, 29337), True, 'import numpy as np\n'), ((29418, 29456), 'scipy.signal.correlate2d', 'signal.correlate2d', (['bw', 'w'], {'mode': '"""same"""'}), "(bw, w, mode='same')\n", (29436, 29456), False, 'from scipy import signal\n'), ((29539, 29570), 'numpy.reshape', 'np.reshape', (['idx', '[1, row * col]'], {}), '(idx, [1, row * col])\n', (29549, 29570), True, 'import numpy as np\n'), ((29684, 29700), 'numpy.asarray', 'np.asarray', (['temp'], {}), '(temp)\n', (29694, 29700), True, 'import numpy as np\n'), ((29712, 29740), 'numpy.reshape', 'np.reshape', (['temp', '[row, col]'], {}), '(temp, [row, col])\n', (29722, 29740), True, 'import numpy as np\n'), ((31180, 31203), 'numpy.where', 'np.where', (['(junctions > 0)'], {}), '(junctions > 0)\n', (31188, 31203), True, 'import numpy as np\n'), ((31216, 31234), 'numpy.where', 'np.where', (['(ends > 0)'], {}), '(ends > 0)\n', (31224, 31234), True, 'import numpy as np\n'), ((32371, 32399), 'numpy.zeros', 'np.zeros', (['(height, width, 8)'], {}), '((height, width, 8))\n', (32379, 32399), True, 'import numpy as np\n'), ((32415, 32448), 'numpy.zeros', 'np.zeros', (['(height + 2, width + 2)'], {}), '((height + 2, width + 2))\n', (32423, 32448), True, 'import numpy as np\n'), ((32487, 32521), 'numpy.array', 'np.array', (['[0, 1, 2, 3, 4, 5, 6, 7]'], {}), '([0, 1, 2, 3, 4, 5, 6, 7])\n', (32495, 32521), True, 'import numpy as np\n'), ((34795, 34832), 'numpy.array', 'np.array', (['[-1, 0, 1, 1, 1, 0, -1, -1]'], {}), '([-1, 0, 1, 1, 1, 0, -1, -1])\n', (34803, 34832), True, 'import numpy as np\n'), ((34844, 34881), 'numpy.array', 'np.array', (['[-1, -1, -1, 0, 1, 1, 1, 0]'], {}), '([-1, -1, -1, 0, 1, 1, 1, 0])\n', (34852, 34881), True, 'import numpy as np\n'), ((35004, 35020), 'numpy.where', 'np.where', (['(r >= 0)'], {}), '(r >= 0)\n', (35012, 35020), True, 'import numpy as np\n'), ((35033, 35050), 'numpy.where', 'np.where', (['(r < row)'], {}), '(r < row)\n', (35041, 35050), True, 'import numpy as np\n'), ((35104, 35120), 'numpy.where', 'np.where', (['(c >= 0)'], {}), '(c >= 0)\n', (35112, 35120), True, 'import numpy as np\n'), ((35133, 35150), 'numpy.where', 'np.where', (['(c < col)'], {}), '(c < col)\n', (35141, 35150), True, 'import numpy as np\n'), ((35655, 35669), 'numpy.asarray', 'np.asarray', (['ra'], {}), '(ra)\n', (35665, 35669), True, 'import numpy as np\n'), ((35679, 35693), 'numpy.asarray', 'np.asarray', (['ca'], {}), '(ca)\n', (35689, 35693), True, 'import numpy as np\n'), ((35703, 35717), 'numpy.asarray', 'np.asarray', (['rj'], {}), '(rj)\n', (35713, 35717), True, 'import numpy as np\n'), ((35727, 35741), 'numpy.asarray', 'np.asarray', (['cj'], {}), '(cj)\n', (35737, 35741), True, 'import numpy as np\n'), ((36389, 36415), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(6, 8)'}), '(figsize=(6, 8))\n', (36399, 36415), True, 'import matplotlib.pyplot as plt\n'), ((36530, 36572), 'matplotlib.pyplot.axis', 'plt.axis', (['[-10, cols + 20, rows + 20, -20]'], {}), '([-10, cols + 20, rows + 20, -20])\n', (36538, 36572), True, 'import matplotlib.pyplot as plt\n'), ((36601, 36616), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (36609, 36616), True, 'import matplotlib.pyplot as plt\n'), ((36621, 36679), 'matplotlib.pyplot.savefig', 'plt.savefig', (["('%s.jpg' % name)"], {'dpi': '(500)', 'bbox_inches': '"""tight"""'}), "('%s.jpg' % name, dpi=500, bbox_inches='tight')\n", (36632, 36679), True, 'import matplotlib.pyplot as plt\n'), ((36684, 36695), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (36693, 36695), True, 'import matplotlib.pyplot as plt\n'), ((41072, 41118), 'numpy.square', 'np.square', (['(edgelist[0:-1, :] - edgelist[1:, :])'], {}), '(edgelist[0:-1, :] - edgelist[1:, :])\n', (41081, 41118), True, 'import numpy as np\n'), ((41174, 41193), 'numpy.sum', 'np.sum', (['row_sqrtsum'], {}), '(row_sqrtsum)\n', (41180, 41193), True, 'import numpy as np\n'), ((45913, 45936), 'numpy.square', 'np.square', (['(x[0] - x[-1])'], {}), '(x[0] - x[-1])\n', (45922, 45936), True, 'import numpy as np\n'), ((45953, 45976), 'numpy.square', 'np.square', (['(y[0] - y[-1])'], {}), '(y[0] - y[-1])\n', (45962, 45976), True, 'import numpy as np\n'), ((45985, 46015), 'numpy.sqrt', 'np.sqrt', (['(x_diff_sq + y_diff_sq)'], {}), '(x_diff_sq + y_diff_sq)\n', (45992, 46015), True, 'import numpy as np\n'), ((46655, 46677), 'os.path.isdir', 'os.path.isdir', (['outpath'], {}), '(outpath)\n', (46668, 46677), False, 'import os\n'), ((46887, 46910), 'os.path.exists', 'os.path.exists', (['outpath'], {}), '(outpath)\n', (46901, 46910), False, 'import os\n'), ((4280, 4347), 'scipy.sparse.coo_matrix', 'sci.sparse.coo_matrix', (['(data, (rj, cj))'], {'shape': '(self.row, self.col)'}), '((data, (rj, cj)), shape=(self.row, self.col))\n', (4301, 4347), True, 'import scipy as sci\n'), ((13712, 13730), 'numpy.array', 'np.array', (['[r2, c2]'], {}), '([r2, c2])\n', (13720, 13730), True, 'import numpy as np\n'), ((13750, 13778), 'numpy.reshape', 'np.reshape', (['addpoint', '[1, 2]'], {}), '(addpoint, [1, 2])\n', (13760, 13778), True, 'import numpy as np\n'), ((13800, 13833), 'numpy.vstack', 'np.vstack', (['(edgepoints, addpoint)'], {}), '((edgepoints, addpoint))\n', (13809, 13833), True, 'import numpy as np\n'), ((14142, 14158), 'numpy.array', 'np.array', (['[0, 0]'], {}), '([0, 0])\n', (14150, 14158), True, 'import numpy as np\n'), ((16829, 16845), 'numpy.array', 'np.array', (['[r, c]'], {}), '([r, c])\n', (16837, 16845), True, 'import numpy as np\n'), ((16865, 16893), 'numpy.reshape', 'np.reshape', (['addpoint', '[1, 2]'], {}), '(addpoint, [1, 2])\n', (16875, 16893), True, 'import numpy as np\n'), ((16915, 16948), 'numpy.vstack', 'np.vstack', (['(edgepoints, addpoint)'], {}), '((edgepoints, addpoint))\n', (16924, 16948), True, 'import numpy as np\n'), ((25674, 27304), 'numpy.array', 'np.array', (['[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0,\n 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,\n 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0,\n 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,\n 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1,\n 1, 0, 0, 1, 1, 0, 0]'], {}), '([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0,\n 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0,\n 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0,\n 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0,\n 1, 1, 1, 1, 0, 0, 1, 1, 0, 0])\n', (25682, 27304), True, 'import numpy as np\n'), ((26807, 26843), 'numpy.reshape', 'np.reshape', (['lut1', '(lut1.shape[0], 1)'], {}), '(lut1, (lut1.shape[0], 1))\n', (26817, 26843), True, 'import numpy as np\n'), ((26890, 28520), 'numpy.array', 'np.array', (['[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1,\n 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0,\n 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0,\n 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0,\n 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0,\n 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0,\n 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,\n 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0,\n 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0,\n 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1]'], {}), '([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,\n 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1,\n 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,\n 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1,\n 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1,\n 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1,\n 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1,\n 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])\n', (26898, 28520), True, 'import numpy as np\n'), ((28023, 28059), 'numpy.reshape', 'np.reshape', (['lut2', '(lut2.shape[0], 1)'], {}), '(lut2, (lut2.shape[0], 1))\n', (28033, 28059), True, 'import numpy as np\n'), ((29141, 29152), 'numpy.floor', 'np.floor', (['n'], {}), '(n)\n', (29149, 29152), True, 'import numpy as np\n'), ((31050, 31077), 'numpy.abs', 'np.abs', (['(imgtile0 - imgtile1)'], {}), '(imgtile0 - imgtile1)\n', (31056, 31077), True, 'import numpy as np\n'), ((31098, 31117), 'numpy.int32', 'np.int32', (['(diff == 2)'], {}), '(diff == 2)\n', (31106, 31117), True, 'import numpy as np\n'), ((31141, 31160), 'numpy.int32', 'np.int32', (['(diff >= 6)'], {}), '(diff >= 6)\n', (31149, 31160), True, 'import numpy as np\n'), ((36084, 36103), 'numpy.array', 'np.array', (['[0, 0, 1]'], {}), '([0, 0, 1])\n', (36092, 36103), True, 'import numpy as np\n'), ((36454, 36520), 'matplotlib.pyplot.plot', 'plt.plot', (['edgelist[idx][:, 1]', 'edgelist[idx][:, 0]'], {'color': 'col[idx]'}), '(edgelist[idx][:, 1], edgelist[idx][:, 0], color=col[idx])\n', (36462, 36520), True, 'import matplotlib.pyplot as plt\n'), ((38469, 38483), 'numpy.fix', 'np.fix', (['(n1 / 2)'], {}), '(n1 / 2)\n', (38475, 38483), True, 'import numpy as np\n'), ((38501, 38515), 'numpy.fix', 'np.fix', (['(n2 / 2)'], {}), '(n2 / 2)\n', (38507, 38515), True, 'import numpy as np\n'), ((39134, 39179), 'numpy.vstack', 'np.vstack', (['(edgelist[edge1], edgelist[edge2])'], {}), '((edgelist[edge1], edgelist[edge2]))\n', (39143, 39179), True, 'import numpy as np\n'), ((40237, 40276), 'numpy.logical_or', 'np.logical_or', (['B[edge1, :]', 'B[edge2, :]'], {}), '(B[edge1, :], B[edge2, :])\n', (40250, 40276), True, 'import numpy as np\n'), ((40299, 40338), 'numpy.logical_or', 'np.logical_or', (['B[:, edge1]', 'B[:, edge2]'], {}), '(B[:, edge1], B[:, edge2])\n', (40312, 40338), True, 'import numpy as np\n'), ((41145, 41164), 'numpy.sum', 'np.sum', (['diff_sqr', '(1)'], {}), '(diff_sqr, 1)\n', (41151, 41164), True, 'import numpy as np\n'), ((43233, 43263), 'numpy.reshape', 'np.reshape', (['y', '(1, y.shape[0])'], {}), '(y, (1, y.shape[0]))\n', (43243, 43263), True, 'import numpy as np\n'), ((43306, 43336), 'numpy.reshape', 'np.reshape', (['x', '(1, x.shape[0])'], {}), '(x, (1, x.shape[0]))\n', (43316, 43336), True, 'import numpy as np\n'), ((44208, 44224), 'numpy.asarray', 'np.asarray', (['temp'], {}), '(temp)\n', (44218, 44224), True, 'import numpy as np\n'), ((46353, 46372), 'numpy.square', 'np.square', (['(x - x[0])'], {}), '(x - x[0])\n', (46362, 46372), True, 'import numpy as np\n'), ((46388, 46407), 'numpy.square', 'np.square', (['(y - y[0])'], {}), '(y - y[0])\n', (46397, 46407), True, 'import numpy as np\n'), ((46434, 46454), 'numpy.sqrt', 'np.sqrt', (['(x_sq + y_sq)'], {}), '(x_sq + y_sq)\n', (46441, 46454), True, 'import numpy as np\n'), ((46478, 46487), 'numpy.max', 'np.max', (['d'], {}), '(d)\n', (46484, 46487), True, 'import numpy as np\n'), ((46489, 46501), 'numpy.argmax', 'np.argmax', (['d'], {}), '(d)\n', (46498, 46501), True, 'import numpy as np\n'), ((46522, 46534), 'numpy.square', 'np.square', (['d'], {}), '(d)\n', (46531, 46534), True, 'import numpy as np\n'), ((46687, 46709), 'shutil.rmtree', 'shutil.rmtree', (['outpath'], {}), '(outpath)\n', (46700, 46709), False, 'import shutil\n'), ((46941, 46961), 'os.makedirs', 'os.makedirs', (['outpath'], {}), '(outpath)\n', (46952, 46961), False, 'import os\n'), ((14018, 14054), 'numpy.array', 'np.array', (['[r2 - rstart, c2 - cstart]'], {}), '([r2 - rstart, c2 - cstart])\n', (14026, 14054), True, 'import numpy as np\n'), ((17910, 17951), 'numpy.vstack', 'np.vstack', (['(edgepoints, edgepoints[0, :])'], {}), '((edgepoints, edgepoints[0, :]))\n', (17919, 17951), True, 'import numpy as np\n'), ((41369, 41390), 'random.randint', 'random.randint', (['(0)', '(14)'], {}), '(0, 14)\n', (41383, 41390), False, 'import random\n'), ((43508, 43542), 'numpy.asarray', 'np.asarray', (['[y[0, fst], x[0, fst]]'], {}), '([y[0, fst], x[0, fst]])\n', (43518, 43542), True, 'import numpy as np\n'), ((16449, 16469), 'numpy.sum', 'np.sum', (['(dirn * dirna)'], {}), '(dirn * dirna)\n', (16455, 16469), True, 'import numpy as np\n'), ((21604, 21629), 'numpy.where', 'np.where', (['A[startnode, :]'], {}), '(A[startnode, :])\n', (21612, 21629), True, 'import numpy as np\n'), ((33090, 33102), 'numpy.square', 'np.square', (['v'], {}), '(v)\n', (33099, 33102), True, 'import numpy as np\n'), ((44102, 44136), 'numpy.asarray', 'np.asarray', (['[y[0, lst], x[0, lst]]'], {}), '([y[0, lst], x[0, lst]])\n', (44112, 44136), True, 'import numpy as np\n'), ((15263, 15283), 'numpy.sum', 'np.sum', (['(dirn * dirna)'], {}), '(dirn * dirna)\n', (15269, 15283), True, 'import numpy as np\n'), ((16390, 16426), 'numpy.array', 'np.array', (['[ra[idx] - r, ca[idx] - c]'], {}), '([ra[idx] - r, ca[idx] - c])\n', (16398, 16426), True, 'import numpy as np\n'), ((20461, 20474), 'numpy.fix', 'np.fix', (['(n / 2)'], {}), '(n / 2)\n', (20467, 20474), True, 'import numpy as np\n'), ((20504, 20517), 'numpy.fix', 'np.fix', (['(m / 2)'], {}), '(m / 2)\n', (20510, 20517), True, 'import numpy as np\n'), ((21877, 21900), 'numpy.where', 'np.where', (['A[endnode, :]'], {}), '(A[endnode, :])\n', (21885, 21900), True, 'import numpy as np\n'), ((25417, 25434), 'numpy.zeros', 'np.zeros', (['(16, 1)'], {}), '((16, 1))\n', (25425, 25434), True, 'import numpy as np\n'), ((25436, 25452), 'numpy.ones', 'np.ones', (['(16, 1)'], {}), '((16, 1))\n', (25443, 25452), True, 'import numpy as np\n'), ((39373, 39399), 'numpy.flipud', 'np.flipud', (['edgelist[edge2]'], {}), '(edgelist[edge2])\n', (39382, 39399), True, 'import numpy as np\n'), ((7149, 7199), 'numpy.array', 'np.array', (['[[rj[j], cj[j]], [all_rj[k], all_cj[k]]]'], {}), '([[rj[j], cj[j]], [all_rj[k], all_cj[k]]])\n', (7157, 7199), True, 'import numpy as np\n'), ((7864, 7892), 'numpy.asarray', 'np.asarray', (['[all_ra, all_ca]'], {}), '([all_ra, all_ca])\n', (7874, 7892), True, 'import numpy as np\n'), ((8023, 8045), 'numpy.asarray', 'np.asarray', (['[rak, cak]'], {}), '([rak, cak])\n', (8033, 8045), True, 'import numpy as np\n'), ((15200, 15236), 'numpy.array', 'np.array', (['[rj[idx] - r, cj[idx] - c]'], {}), '([rj[idx] - r, cj[idx] - c])\n', (15208, 15236), True, 'import numpy as np\n'), ((22753, 22770), 'numpy.where', 'np.where', (['B[n, :]'], {}), '(B[n, :])\n', (22761, 22770), True, 'import numpy as np\n'), ((39577, 39603), 'numpy.flipud', 'np.flipud', (['edgelist[edge1]'], {}), '(edgelist[edge1])\n', (39586, 39603), True, 'import numpy as np\n'), ((43721, 43731), 'numpy.exp', 'np.exp', (['(-s)'], {}), '(-s)\n', (43727, 43731), True, 'import numpy as np\n'), ((43741, 43751), 'numpy.exp', 'np.exp', (['(-s)'], {}), '(-s)\n', (43747, 43751), True, 'import numpy as np\n'), ((15813, 15849), 'numpy.array', 'np.array', (['[rj[idx] - r, cj[idx] - c]'], {}), '([rj[idx] - r, cj[idx] - c])\n', (15821, 15849), True, 'import numpy as np\n'), ((16032, 16068), 'numpy.array', 'np.array', (['[rj[idx] - r, cj[idx] - c]'], {}), '([rj[idx] - r, cj[idx] - c])\n', (16040, 16068), True, 'import numpy as np\n'), ((23516, 23547), 'numpy.hstack', 'np.hstack', (['(linkingedges[0], n)'], {}), '((linkingedges[0], n))\n', (23525, 23547), True, 'import numpy as np\n'), ((23970, 23994), 'numpy.where', 'np.where', (['A[spurnode, :]'], {}), '(A[spurnode, :])\n', (23978, 23994), True, 'import numpy as np\n'), ((39895, 39921), 'numpy.flipud', 'np.flipud', (['edgelist[edge1]'], {}), '(edgelist[edge1])\n', (39904, 39921), True, 'import numpy as np\n'), ((39923, 39949), 'numpy.flipud', 'np.flipud', (['edgelist[edge2]'], {}), '(edgelist[edge2])\n', (39932, 39949), True, 'import numpy as np\n'), ((44017, 44027), 'numpy.exp', 'np.exp', (['(-s)'], {}), '(-s)\n', (44023, 44027), True, 'import numpy as np\n'), ((44037, 44047), 'numpy.exp', 'np.exp', (['(-s)'], {}), '(-s)\n', (44043, 44047), True, 'import numpy as np\n'), ((23639, 23656), 'numpy.argmin', 'np.argmin', (['length'], {}), '(length)\n', (23648, 23656), True, 'import numpy as np\n'), ((8968, 8992), 'numpy.array', 'np.array', (['[rj[j], cj[j]]'], {}), '([rj[j], cj[j]])\n', (8976, 8992), True, 'import numpy as np\n'), ((9080, 9112), 'numpy.array', 'np.array', (['[all_rj[k], all_cj[k]]'], {}), '([all_rj[k], all_cj[k]])\n', (9088, 9112), True, 'import numpy as np\n'), ((23331, 23369), 'numpy.hstack', 'np.hstack', (['(spurs, linkingedges[0][i])'], {}), '((spurs, linkingedges[0][i]))\n', (23340, 23369), True, 'import numpy as np\n')]
from os.path import join import numpy as np from gym import spaces from environment.base import BaseEnv class Arm2TouchEnv(BaseEnv): def __init__(self, continuous, max_steps, geofence=.08, history_len=1, neg_reward=True, action_multiplier=1): BaseEnv.__init__(self, geofence=geofence, max_steps=max_steps, xml_filepath=join('models', 'arm2touch', 'world.xml'), history_len=history_len, use_camera=False, # TODO neg_reward=neg_reward, body_name="hand_palm_link", steps_per_action=10, image_dimensions=None) left_finger_name = 'hand_l_distal_link' self._finger_names = [left_finger_name, left_finger_name.replace('_l_', '_r_')] self._set_new_goal() self._action_multiplier = action_multiplier self._continuous = continuous obs_shape = history_len * np.size(self._obs()) + np.size(self._goal()) self.observation_space = spaces.Box(-np.inf, np.inf, shape=obs_shape) if continuous: self.action_space = spaces.Box(-1, 1, shape=self.sim.nu) else: self.action_space = spaces.Discrete(self.sim.nu * 2 + 1) def generate_valid_block_position(self): low_range = np.array([-0.15, -0.25, 0.49]) high_range = np.array([0.15, 0.25, 0.49]) return np.random.uniform(low=low_range, high=high_range) def get_block_position(self, qpos, name): idx = self.sim.jnt_qposadr(name) position = qpos[idx:idx+3] return np.copy(position) def set_block_position(self, qpos, name, position): idx = self.sim.jnt_qposadr(name) qpos = np.copy(qpos) qpos[idx:idx+3] = position return qpos def are_positions_touching(self, pos1, pos2): touching_threshold = 0.05 weighting = np.array([1, 1, 0.1]) dist = np.sqrt(np.sum(weighting*np.square(pos1 - pos2))) return dist < touching_threshold def reset_qpos(self): qpos = self.init_qpos qpos = self.set_block_position(self.sim.qpos, 'block1joint', self.generate_valid_block_position()) qpos = self.set_block_position(self.sim.qpos, 'block2joint', self.generate_valid_block_position()) return qpos def _set_new_goal(self): goal_block = np.random.randint(0, 2) onehot = np.zeros([2],dtype=np.float32) onehot[goal_block] = 1 self.__goal = onehot def _obs(self): return [self.sim.qpos] def _goal(self): return [self.__goal] def goal_3d(self): return [0,0,0] def _currently_failed(self): return False def at_goal(self, qpos, goal): block1 = self.get_block_position(qpos, 'block1joint') block2 = self.get_block_position(qpos, 'block2joint') gripper = self._gripper_pos(qpos) goal_block = np.argmax(goal) + 1 if goal_block == 1: return self.are_positions_touching(block1, gripper) else: return self.are_positions_touching(block2, gripper) def _compute_terminal(self, goal, obs): goal, = goal qpos, = obs return self.at_goal(qpos, goal) def _compute_reward(self, goal, obs): qpos, = obs if self.at_goal(qpos, goal): return 1 elif self._neg_reward: return -.0001 else: return 0 def _obs_to_goal(self, obs): raise Exception('No promises here.') qpos, = obs return [self._gripper_pos(qpos)] def _gripper_pos(self, qpos=None): finger1, finger2 = [self.sim.get_body_xpos(name, qpos) for name in self._finger_names] return (finger1 + finger2) / 2. def step(self, action): if not self._continuous: ctrl = np.zeros(self.sim.nu) if action != 0: ctrl[(action - 1) // 2] = (1 if action % 2 else -1) * self._action_multiplier return BaseEnv.step(self, ctrl) else: action = np.clip(action * self._action_multiplier, -1, 1) return BaseEnv.step(self, action)
[ "numpy.random.uniform", "numpy.copy", "numpy.argmax", "numpy.square", "numpy.zeros", "gym.spaces.Discrete", "numpy.clip", "numpy.random.randint", "numpy.array", "gym.spaces.Box", "environment.base.BaseEnv.step", "os.path.join" ]
[((1134, 1178), 'gym.spaces.Box', 'spaces.Box', (['(-np.inf)', 'np.inf'], {'shape': 'obs_shape'}), '(-np.inf, np.inf, shape=obs_shape)\n', (1144, 1178), False, 'from gym import spaces\n'), ((1422, 1452), 'numpy.array', 'np.array', (['[-0.15, -0.25, 0.49]'], {}), '([-0.15, -0.25, 0.49])\n', (1430, 1452), True, 'import numpy as np\n'), ((1474, 1502), 'numpy.array', 'np.array', (['[0.15, 0.25, 0.49]'], {}), '([0.15, 0.25, 0.49])\n', (1482, 1502), True, 'import numpy as np\n'), ((1518, 1567), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': 'low_range', 'high': 'high_range'}), '(low=low_range, high=high_range)\n', (1535, 1567), True, 'import numpy as np\n'), ((1706, 1723), 'numpy.copy', 'np.copy', (['position'], {}), '(position)\n', (1713, 1723), True, 'import numpy as np\n'), ((1837, 1850), 'numpy.copy', 'np.copy', (['qpos'], {}), '(qpos)\n', (1844, 1850), True, 'import numpy as np\n'), ((2011, 2032), 'numpy.array', 'np.array', (['[1, 1, 0.1]'], {}), '([1, 1, 0.1])\n', (2019, 2032), True, 'import numpy as np\n'), ((2482, 2505), 'numpy.random.randint', 'np.random.randint', (['(0)', '(2)'], {}), '(0, 2)\n', (2499, 2505), True, 'import numpy as np\n'), ((2523, 2554), 'numpy.zeros', 'np.zeros', (['[2]'], {'dtype': 'np.float32'}), '([2], dtype=np.float32)\n', (2531, 2554), True, 'import numpy as np\n'), ((1235, 1271), 'gym.spaces.Box', 'spaces.Box', (['(-1)', '(1)'], {'shape': 'self.sim.nu'}), '(-1, 1, shape=self.sim.nu)\n', (1245, 1271), False, 'from gym import spaces\n'), ((1318, 1354), 'gym.spaces.Discrete', 'spaces.Discrete', (['(self.sim.nu * 2 + 1)'], {}), '(self.sim.nu * 2 + 1)\n', (1333, 1354), False, 'from gym import spaces\n'), ((3045, 3060), 'numpy.argmax', 'np.argmax', (['goal'], {}), '(goal)\n', (3054, 3060), True, 'import numpy as np\n'), ((3998, 4019), 'numpy.zeros', 'np.zeros', (['self.sim.nu'], {}), '(self.sim.nu)\n', (4006, 4019), True, 'import numpy as np\n'), ((4161, 4185), 'environment.base.BaseEnv.step', 'BaseEnv.step', (['self', 'ctrl'], {}), '(self, ctrl)\n', (4173, 4185), False, 'from environment.base import BaseEnv\n'), ((4221, 4269), 'numpy.clip', 'np.clip', (['(action * self._action_multiplier)', '(-1)', '(1)'], {}), '(action * self._action_multiplier, -1, 1)\n', (4228, 4269), True, 'import numpy as np\n'), ((4289, 4315), 'environment.base.BaseEnv.step', 'BaseEnv.step', (['self', 'action'], {}), '(self, action)\n', (4301, 4315), False, 'from environment.base import BaseEnv\n'), ((428, 468), 'os.path.join', 'join', (['"""models"""', '"""arm2touch"""', '"""world.xml"""'], {}), "('models', 'arm2touch', 'world.xml')\n", (432, 468), False, 'from os.path import join\n'), ((2073, 2095), 'numpy.square', 'np.square', (['(pos1 - pos2)'], {}), '(pos1 - pos2)\n', (2082, 2095), True, 'import numpy as np\n')]
from __future__ import absolute_import, division, print_function, unicode_literals import functools import tensorflow as tf import numpy as np from tensorflow import keras import csv train_data = [] train_label = [] test_data = [] test_label = [] with open('C:/Users/felix/MakeUofT/venv/src/test_data.csv','rt') as f: data = csv.reader(f) for row in data: test_label.append(int(row[0])) temp = [] for i in range (1, 9001): if (len(row) - 1 < i): temp.append(float(0)) else: temp.append(float(row[i])) test_data.append(np.array(temp)) test_data = np.array(test_data) test_label = np.array(test_label) with open('C:/Users/felix/MakeUofT/venv/src/train_data.csv','rt') as f: data = csv.reader(f) for row in data: train_label.append(int(row[0])) temp = [] for i in range(1, 9001): if (len(row) - 1 < i): temp.append(float(0)) else: temp.append(float(row[i])) train_data.append(np.array(temp)) train_data = np.array(train_data) train_label = np.array(train_label) motions = ["swipe_up", "swipe_down", "swipe_left", "swipe_right", "cw_circ", "ccw_circ", "push_out", "pull_in", "cw_semi", "ccw_semi"] model = keras.Sequential([ keras.layers.Dense(9000, activation="relu"), keras.layers.Dense(128, activation="relu"), keras.layers.Dense(64, activation="relu"), keras.layers.Dense(10, activation="softmax") #Probability ]) #model = keras.models.load_model("Motion.h5") model.compile(optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"]) model.fit(train_data, train_label, epochs = 20) model.save("Motion.h5") test_loss, test_acc = model.evaluate(test_data, test_label) print("Tested acc", test_acc) # File name needs the file extension to function # Return the string with the motion that it detects def predict(file_name): model = keras.models.load_model("Motion.h5") with open (file_name, encoding="utf-8") as f: for line in f.readlines(): data = parse if (len(data) > 90): temp = [] for str in line: temp.append(float(str)) while (len(temp) < 9000): temp.append(float(0)) predict = model.predict(data) return motions[predict] ''' if __name__ == '__main__': model = keras.models.load_model("Motion.h5") '''
[ "tensorflow.keras.layers.Dense", "csv.reader", "numpy.array", "tensorflow.keras.models.load_model" ]
[((641, 660), 'numpy.array', 'np.array', (['test_data'], {}), '(test_data)\n', (649, 660), True, 'import numpy as np\n'), ((674, 694), 'numpy.array', 'np.array', (['test_label'], {}), '(test_label)\n', (682, 694), True, 'import numpy as np\n'), ((1095, 1115), 'numpy.array', 'np.array', (['train_data'], {}), '(train_data)\n', (1103, 1115), True, 'import numpy as np\n'), ((1130, 1151), 'numpy.array', 'np.array', (['train_label'], {}), '(train_label)\n', (1138, 1151), True, 'import numpy as np\n'), ((329, 342), 'csv.reader', 'csv.reader', (['f'], {}), '(f)\n', (339, 342), False, 'import csv\n'), ((779, 792), 'csv.reader', 'csv.reader', (['f'], {}), '(f)\n', (789, 792), False, 'import csv\n'), ((1998, 2034), 'tensorflow.keras.models.load_model', 'keras.models.load_model', (['"""Motion.h5"""'], {}), "('Motion.h5')\n", (2021, 2034), False, 'from tensorflow import keras\n'), ((1335, 1378), 'tensorflow.keras.layers.Dense', 'keras.layers.Dense', (['(9000)'], {'activation': '"""relu"""'}), "(9000, activation='relu')\n", (1353, 1378), False, 'from tensorflow import keras\n'), ((1388, 1430), 'tensorflow.keras.layers.Dense', 'keras.layers.Dense', (['(128)'], {'activation': '"""relu"""'}), "(128, activation='relu')\n", (1406, 1430), False, 'from tensorflow import keras\n'), ((1440, 1481), 'tensorflow.keras.layers.Dense', 'keras.layers.Dense', (['(64)'], {'activation': '"""relu"""'}), "(64, activation='relu')\n", (1458, 1481), False, 'from tensorflow import keras\n'), ((1491, 1535), 'tensorflow.keras.layers.Dense', 'keras.layers.Dense', (['(10)'], {'activation': '"""softmax"""'}), "(10, activation='softmax')\n", (1509, 1535), False, 'from tensorflow import keras\n'), ((612, 626), 'numpy.array', 'np.array', (['temp'], {}), '(temp)\n', (620, 626), True, 'import numpy as np\n'), ((1065, 1079), 'numpy.array', 'np.array', (['temp'], {}), '(temp)\n', (1073, 1079), True, 'import numpy as np\n')]
import logging, time import numpy as np import torch try: from fedml_core.trainer.model_trainer import ModelTrainer except ImportError: from FedML.fedml_core.trainer.model_trainer import ModelTrainer from .utils import EvaluationMetricsKeeper class DModelTrainer(ModelTrainer): def __init__(self, model, id, args=None): super().__init__(model, args) self.id = id self.node_name = 'Client {}'.format(id) self.model.setup(args) def get_model_params(self): logging.info('[{}] Obtain model parameters'.format(self.node_name)) return self.model.get_weights() def set_model_params(self, model_parameters): logging.info('[{}] Updating model'.format(self.node_name)) self.model.load_weights(model_parameters) def train(self, train_data, device, args=None): pass def train_one_iter(self, label_batch, data_batch, fake_samples): # logging.info('[{0}] local data shapes {1} {2}'.format(self.node_name, label_batch.size(), data_batch.size())) input = {'A': label_batch, 'B': data_batch} self.model.set_input(input) fake_samples = torch.tensor(np.array(fake_samples, dtype='float32'), requires_grad=True) # torch.stack(fake_samples) loss_dict, grad_fake_B = self.model.optimize(fake_samples) train_metrics = EvaluationMetricsKeeper(loss_dict['loss_D'], loss_dict['loss_G'], loss_dict['loss_D_fake'], loss_dict['loss_D_real'], loss_dict['loss_G_GAN'], loss_dict['loss_G_L1'], loss_dict['loss_G_perceptual']) return train_metrics, grad_fake_B def _train(self, train_data): model = self.model args = self.args if self.args.backbone_freezed: logging.info('[{0}] Training (Backbone Freezed) for {1} Epochs'.format(self.node_name, self.args.epochs)) else: logging.info('[{0}] Training for {1} Epochs'.format(self.node_name, self.args.epochs)) epoch_loss_D = [] epoch_loss_G = [] for epoch in range(args.epochs): t = time.time() batch_loss_D = [] batch_loss_G = [] logging.info('[{0}] Train Epoch: {1}'.format(self.node_name, epoch)) for (batch_idx, batch) in enumerate(train_data): model.set_input(batch) # unpack data from dataset and apply preprocessing loss_D, loss_G = model.optimize_parameters() # calculate loss functions, get gradients, update network weights batch_loss_D.append(loss_D) batch_loss_G.append(loss_G) if (batch_idx % 100 == 0): logging.info('[{0}] Train Iteration: {1}, LossD: {2}, lossG: {3}, Time Elapsed: {4}'.format(self.node_name, batch_idx, loss_D, loss_G, (time.time()-t)/60)) if len(batch_loss_D) > 0: epoch_loss_D.append(sum(batch_loss_D) / len(batch_loss_D)) epoch_loss_G.append(sum(batch_loss_G) / len(batch_loss_G)) logging.info('[{}]. Local Training Epoch: {} \tLossD: {:.6f}\tLossG: {:.6f}'.format(self.node_name, epoch, sum(epoch_loss_D) / len(epoch_loss_D), sum(epoch_loss_G) / len(epoch_loss_G))) model.update_learning_rate() # update learning rates at the end of every epoch. def test(self, test_data, device, args=None): logging.info('[{name}] Testing on Test Dataset'.format(name=self.node_name)) test_evaluation_metrics = self._infer(test_data, device) # logging.info("Testing Complete for client {}".format(self.id)) return test_evaluation_metrics def test_train(self, train_data, device): logging.info('[{name}] Testing on Train Dataset'.format(name=self.node_name)) train_evaluation_metrics = self._infer(train_data, device) return train_evaluation_metrics def _infer(self, test_data, device): ## TODO return None t = time.time() loss_D = loss_D_fake = loss_D_real = loss_G = loss_G_GAN = loss_G_L1 = loss_G_perceptual = 0 test_total = 0. with torch.no_grad(): for (batch_idx, batch) in enumerate(test_data): loss_dict = self.model.evaluate(batch) loss_D += loss_dict['loss_D'] loss_D_fake += loss_dict['loss_D_fake'] loss_D_real += loss_dict['loss_D_real'] loss_G += loss_dict['loss_G'] loss_G_GAN += loss_dict['loss_G_GAN'] loss_G_L1 += loss_dict['loss_G_L1'] loss_G_perceptual += loss_dict['loss_G_perceptual'] test_total += 1 # batch['A'].size(0) if batch_idx % 100 == 0: logging.info('[{0}] Test Iteration: {1}, Loss_D: {2}, Loss_G: {3}, Time Elapsed: {4}'.format(self.node_name, batch_idx, loss_dict['loss_D'], loss_dict['loss_G'], (time.time() - t) / 60)) # Evaluation Metrics (Averaged over number of samples) loss_D = loss_D / test_total loss_D_fake = loss_D_fake / test_total loss_D_real = loss_D_real / test_total loss_G = loss_G / test_total loss_G_GAN = loss_G_GAN / test_total loss_G_L1 = loss_G_L1 / test_total loss_G_perceptual = loss_G_perceptual / test_total # logging.info("Client={0}, loss_D={1}, loss_D_fake={2}, loss_D_real={3}, loss_G={4}, loss_G_GAN={5}, loss_G_L1={6}, loss_G_perceptual={7}".format( # self.id, loss_D, loss_D_fake, loss_D_real, loss_G, loss_G_GAN, loss_G_L1, loss_G_perceptual)) eval_metrics = EvaluationMetricsKeeper(loss_D, loss_G, loss_D_fake, loss_D_real, loss_G_GAN, loss_G_L1, loss_G_perceptual) return eval_metrics def test_on_the_server(self, train_data_local_dict, test_data_local_dict, device, args=None) -> bool: return False
[ "torch.no_grad", "numpy.array", "time.time" ]
[((4100, 4111), 'time.time', 'time.time', ([], {}), '()\n', (4109, 4111), False, 'import logging, time\n'), ((1177, 1216), 'numpy.array', 'np.array', (['fake_samples'], {'dtype': '"""float32"""'}), "(fake_samples, dtype='float32')\n", (1185, 1216), True, 'import numpy as np\n'), ((2164, 2175), 'time.time', 'time.time', ([], {}), '()\n', (2173, 2175), False, 'import logging, time\n'), ((4251, 4266), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (4264, 4266), False, 'import torch\n'), ((2887, 2898), 'time.time', 'time.time', ([], {}), '()\n', (2896, 2898), False, 'import logging, time\n'), ((5393, 5404), 'time.time', 'time.time', ([], {}), '()\n', (5402, 5404), False, 'import logging, time\n')]
# ---------------------------------------------------------------------------- # This module includes Genetic Algorithm class for CVRP. # Chromosome representation is composed of 2 parts. First part is job part, which includes # job ids in genes and second part is vehicle part, which includes vehicles by gene order. # # Example: # chromosome -> 1324567322 # job part -> 1324567 # vehicle part -> 322 # First vehicle route -> 132 # Second vehicle route -> 45 # Third vehicle route -> 67 # # Genetic Algorithm process: # # 1. Initialize population # 2. Fitness calculation # 3. Selection # 4. Crossover # 5. Mutation # 6. Update Population # 7. Check termination criteria # Generation number is the only termination criteria. # # (C) <NAME>, 2022 # ---------------------------------------------------------------------------- import numpy as np from genetic_algorithm_helper import * from json_parser import JsonParser class GeneticAlgorithm: def __init__(self, data): """ The constructor for GeneticAlgorithm class. :param data: Input data, which is parsed by JsonParser class. """ # Input parameters from json file. self.data = data self.vehicles = {d['id']: [d['start_index'], d['capacity'][0]] for d in data['vehicles']} self.jobs = {d['id']: [d['location_index'], d['delivery'][0], d['service']] for d in data['jobs']} self.matrix = [item for item in self.data['matrix']] self.number_of_vehicles = len(self.vehicles) self.number_of_jobs = len(self.jobs) # Genetic Algorithm parameters self.generations = 100 self.chromosomes = 10 self.mating_pool_size = 6 # Must be greater than half of chromosomes self.genes = self.number_of_vehicles + self.number_of_jobs self.offspring_size = self.chromosomes - self.mating_pool_size self.population = np.empty((self.chromosomes, self.genes), dtype='int') self.fitness = 0 # Create initial population self.__initial_population() def __initial_population(self): """ Creates initial population. """ job_ids = list(self.jobs.keys()) chromosome_job_part = [random.sample(job_ids, self.number_of_jobs) for i in range(self.chromosomes)] self.population[:, :self.number_of_jobs] = np.array(chromosome_job_part) chromosome_vehicle_part = [] for _ in self.population: random_vehicle_part = list(create_random_vehicle_part(self.number_of_vehicles, self.number_of_jobs)) chromosome_vehicle_part.append(random_vehicle_part) self.population[:, self.number_of_jobs:] = chromosome_vehicle_part def __fitness(self, chromosomes): """ Calculates fitness of given chromosomes. :param chromosomes: Individuals or solutions of algorithm. :return: Total cost value. """ self.total_cost = [] for chromosome in chromosomes: routes = map_chromosome_to_routes(chromosome, self.number_of_jobs) chromosome_cost = 0 for i in range(self.number_of_vehicles): route_cost = 0 if chromosome[len(self.jobs) + i] > 0: vehicle_id = list(self.vehicles)[i] # Vehicle ids are mapped to chromosome vehicle part in order vehicle_location = self.vehicles[vehicle_id][0] route_locations = map_route_to_route_locations(vehicle_location, routes[i], self.jobs) route_cost = calculate_route_cost(route_locations, routes[i], self.jobs, self.matrix) penalty = self.__penalty(vehicle_id, routes[i]) route_cost += penalty * route_cost chromosome_cost = chromosome_cost + route_cost self.total_cost.append(chromosome_cost) return self.total_cost def __penalty(self, vehicle_id, route): """ Calculates penalty of given route. If route violates capacity constraint, penalty score added to cost. :param vehicle_id: Vehicle ID :param route: Locations, which will be visited by the vehicle. :return: Penalty score. """ penalty = 0 vehicle_capacity = self.vehicles[vehicle_id][1] route_total_delivery = 0 for job in route: job_delivery = self.jobs[job][1] route_total_delivery += job_delivery if route_total_delivery > vehicle_capacity: penalty += 1000 return penalty def __print(self): """ Prints a report for each iteration. """ print("Generation: ", self.generation + 1, "\nPopulation\n", self.population, "\nFitness\n", self.fitness, '\n') def __selection(self): """ Selects best parents for next generation. """ self.parents = [chromosome for _, chromosome in sorted(zip(self.fitness, self.population), key=lambda x: x[0])] self.parents = self.parents[:self.mating_pool_size] def __crossover(self): """ Creates offspring from parents in mating pool. Ordered Crossover procedure is applied. """ self.offspring = np.empty((self.offspring_size, self.genes), dtype='int') for i in range(0, self.offspring_size): # offspring1 vehicle part parent1 = list(self.parents[i]) parent2 = list(self.parents[i + 1]) parent1_vehicle_part = parent1[self.number_of_jobs:] parent2_vehicle_part = parent2[self.number_of_jobs:] random_vehicle = random.randint(0, self.number_of_vehicles - 1) self.offspring[i, :] = construct_offspring(parent1, parent1_vehicle_part, parent2, parent2_vehicle_part, random_vehicle, self.number_of_jobs) def __mutation(self): """ Mutates offspring. An adaptive mutation procedure is applied. If the fitness of the offspring is greater than the average fitness of the population, it is called low-quality solution and the mutation probability will be high and vice versa. """ average_fitness = np.average(self.fitness) for i in range(self.offspring_size): fitness = self.__fitness([self.offspring[i]]) if fitness >= average_fitness: # Low-quality solution mutation_rate = 0.9 else: # High-quality solution mutation_rate = 0.1 if random.random() > mutation_rate: random_vehicle = random.randint(0, self.number_of_vehicles - 1) random_vehicle_index = self.number_of_jobs + random_vehicle # If the route has more than 1 location for service, swap 2 service locations randomly inside the route, # otherwise swap 2 random service locations in offspring regardless of routes of vehicles. # This condition prioritize the mutation in route to sustain the parent gene transfer stability. if self.offspring[i][random_vehicle_index] > 1: start_gene = int(sum(self.offspring[i][self.number_of_jobs:random_vehicle_index])) end_gene = int(start_gene + self.offspring[i][random_vehicle_index]) else: start_gene = 0 end_gene = self.number_of_jobs mutation_points = random.sample(range(start_gene, end_gene), 2) for point in range(len(mutation_points) - 1): self.offspring[i][mutation_points[point]], self.offspring[i][mutation_points[point + 1]] = \ self.offspring[i][mutation_points[point + 1]], self.offspring[i][mutation_points[point]] def run(self): """ Runs Genetic Algorithm loop: 1. Selection 2. Crossover 3. Mutation """ for self.generation in range(self.generations): self.fitness = self.__fitness(self.population) self.__print() self.__selection() self.__crossover() self.__mutation() self.population[:len(self.parents), :] = self.parents self.population[len(self.parents):, :] = self.offspring best_solution = [self.population[0]] json_data = map_chromosome_to_json_dictionary(best_solution, self.number_of_jobs, self.vehicles, self.matrix, self.jobs) JsonParser.write_json_data(json_data)
[ "numpy.empty", "numpy.average", "numpy.array", "json_parser.JsonParser.write_json_data" ]
[((1911, 1964), 'numpy.empty', 'np.empty', (['(self.chromosomes, self.genes)'], {'dtype': '"""int"""'}), "((self.chromosomes, self.genes), dtype='int')\n", (1919, 1964), True, 'import numpy as np\n'), ((2392, 2421), 'numpy.array', 'np.array', (['chromosome_job_part'], {}), '(chromosome_job_part)\n', (2400, 2421), True, 'import numpy as np\n'), ((5296, 5352), 'numpy.empty', 'np.empty', (['(self.offspring_size, self.genes)'], {'dtype': '"""int"""'}), "((self.offspring_size, self.genes), dtype='int')\n", (5304, 5352), True, 'import numpy as np\n'), ((6352, 6376), 'numpy.average', 'np.average', (['self.fitness'], {}), '(self.fitness)\n', (6362, 6376), True, 'import numpy as np\n'), ((8717, 8754), 'json_parser.JsonParser.write_json_data', 'JsonParser.write_json_data', (['json_data'], {}), '(json_data)\n', (8743, 8754), False, 'from json_parser import JsonParser\n')]
import numpy as np from sklearn.neighbors import KernelDensity from scipy.spatial.distance import euclidean from sklearn.metrics.pairwise import rbf_kernel from cvxopt import matrix, solvers from sklearn.model_selection import GridSearchCV, LeaveOneOut, KFold def gaussian_kernel(X, h, d): """ Apply gaussian kernel to the input distance X """ K = np.exp(-X / (2 * (h**2))) / ((2 * np.pi * (h**2))**(d / 2)) return K def rho(x, typ='hampel', a=0, b=0, c=0): if typ == 'huber': in1 = (x <= a) in2 = (x > a) in1_t = x[in1]**2 / 2 in2_t = x[in2] * a - a**2 / 2 L = np.sum(in1_t) + np.sum(in2_t) if typ == 'hampel': in1 = (x < a) in2 = np.logical_and(a <= x, x < b) in3 = np.logical_and(b <= x, x < c) in4 = (c <= x) in1_t = (x[in1]**2) / 2 in2_t = a * x[in2] - a**2 / 2 in3_t = (a * (x[in3] - c)**2 / (2 * (b - c))) + a * (b + c - a) / 2 in4_t = np.ones(x[in4].shape) * a * (b + c - a) / 2 L = np.sum(in1_t) + np.sum(in2_t) + np.sum(in3_t) + np.sum(in4_t) if typ == 'square': t = x**2 if typ == 'abs': t = np.abs(x) L = np.sum(t) return L / x.shape[0] def loss(x, typ='hampel', a=0, b=0, c=0): return rho(x, typ=typ, a=a, b=b, c=c) / x.shape[0] def psi(x, typ='hampel', a=0, b=0, c=0): if typ == 'huber': return np.minimum(x, a) if typ == 'hampel': in1 = (x < a) in2 = np.logical_and(a <= x, x < b) in3 = np.logical_and(b <= x, x < c) in4 = (c <= x) in1_t = x[in1] in2_t = np.ones(x[in2].shape) * a in3_t = a * (c - x[in3]) / (c - b) in4_t = np.zeros(x[in4].shape) return np.concatenate((in1_t, in2_t, in3_t, in4_t)).reshape((-1, x.shape[1])) if typ == 'square': return 2 * x if typ == 'abs': return 1 def phi(x, typ='hampel', a=0, b=0, c=0): x[x == 0] = 10e-6 return psi(x, typ=typ, a=a, b=b, c=c) / x def irls(Km, type_rho, n, a, b, c, alpha=10e-8, max_it=100): """ Iterative reweighted least-square """ # init weights w = np.ones((n, 1)) / n # first pass t1 = np.diag(Km).reshape((-1, 1)) #  (-1, dimension) t2 = - 2 * np.dot(Km, w) t3 = np.dot(np.dot(w.T, Km), w) t = t1 + t2 + t3 norm = np.sqrt(t) J = loss(norm, typ=type_rho, a=a, b=b, c=c) stop = 0 count = 0 losses = [J] while not stop: count += 1 # print("i: {} loss: {}".format(count, J)) J_old = J # update weights w = phi(norm, typ=type_rho, a=a, b=b, c=c) w = w / np.sum(w) t1 = np.diag(Km).reshape((-1, 1)) #  (-1, dimension) t2 = - 2 * np.dot(Km, w) t3 = np.dot(np.dot(w.T, Km), w) t = t1 + t2 + t3 norm = np.sqrt(t) # update loss J = loss(norm, typ=type_rho, a=a, b=b, c=c) losses.append(J) if ((np.abs(J - J_old) < (J_old * alpha)) or (count == max_it)): print("Stop at {} iterations".format(count)) stop = 1 return w, norm, losses def kde(X_data, X_plot, h, kernel='gaussian', return_model=False): kde_fit = KernelDensity(kernel=kernel, bandwidth=h).fit(X_data) if return_model: return np.exp(kde_fit.score_samples(X_plot)), kde_fit else: return np.exp(kde_fit.score_samples(X_plot)) def area_density(z, grid): if grid is None: print('\nWARNING: no grid ==> return area = 1') return 1 shapes = [el.shape[0] for el in grid] area = np.trapz(z.reshape(shapes), grid[0], axis=0) for i_grid, ax in enumerate(grid[1:]): area = np.trapz(area, ax, axis=0) return area def area_MC_mom(X, model_momkde, n_mc=100000, distribution='kde', h=1): """ Parameters ----- distribution : 'uniform', 'kde' h : if 'kde', need to specifiy the bandwidth h Returns ----- area : the area of model_momkde over X """ cube_lows = [] cube_highs = [] dim = X.shape[1] if distribution == 'uniform': for d in range(dim): x_min, x_max = X[:, d].min(), X[:, d].max() offset = np.abs(x_max - x_min) * 0.5 cube_lows.append(x_min - offset) cube_highs.append(x_max + offset) x_mc = np.random.uniform(cube_lows, cube_highs, size=(n_mc, X.shape[1])) p_mc = 1 / np.product(np.array(cube_highs) - np.array(cube_lows)) elif distribution == 'kde': kde = KernelDensity(h) kde.fit(X) x_mc = kde.sample(n_mc) p_mc = np.exp(kde.score_samples(x_mc)) res = [] for kde_k in model_momkde: res.append(np.exp(kde_k.score_samples(x_mc))) res = np.median(res, axis=0) res = res / p_mc area = np.mean(res) # print('area MC: {}'.format(area)) return area def mom_kde(X_data, X_plot, h, outliers_fraction, grid, K='auto', kernel='gaussian', median='pointwise', norm=True, return_model=False, h_std=False): """ Returns ----- (if return_model=True) KDE_K: the list of all kdes fitted on the blocks. Warning : the KDE_K is not normed to area=1, only z is normed. """ n_samples = X_data.shape[0] if K == 'auto': K = int(2 * n_samples * outliers_fraction) + 1 # print("N blocks: ", K) # print("N samples per block: ", int(n_samples / K)) KDE_K = [] X_shuffle = np.array(X_data) np.random.shuffle(X_shuffle) z = [] for k in range(K): values = X_shuffle[k * int(n_samples / K):(k + 1) * int(n_samples / K), :] if h_std: std = np.std(values) h0 = h * std else: h0 = h kde = KernelDensity(bandwidth=h0) kde.fit(values) KDE_K.append(kde) z.append(np.exp(kde.score_samples(X_plot))) if median == 'pointwise': z = np.median(z, axis=0) elif median == 'geometric': distance = euclidean z = min(map(lambda p1: (p1, sum(map(lambda p2: distance(p1, p2), z))), z), key=lambda x: x[1])[0] else: raise ValueError('Wrong value for argument median: ' + median) if norm: if grid is None: print('no grid specified, computing area with MC') area = area_MC_mom(X_data, KDE_K) else: area = area_density(z, grid) # print("area mom (before normalization) :{}".format(area)) z = z / area if return_model: return z, KDE_K else: return z def rkde(X_data, X_plot, h, type_rho='hampel', return_model=False): # kernel matrix n_samples, d = X_data.shape gamma = 1. / (2 * (h**2)) Km = rbf_kernel(X_data, X_data, gamma=gamma) * (2 * np.pi * h**2)**(-d / 2.) # find a, b, c via iterative reweighted least square a = b = c = 0 alpha = 10e-8 max_it = 100 # first it. reweighted least ssquare with rho = absolute function w, norm, losses = irls(Km, 'abs', n_samples, a, b, c, alpha, max_it) a = np.median(norm) b = np.percentile(norm, 75) c = np.percentile(norm, 95) # find weights via second iterative reweighted least square with input rho w, norm, losses = irls(Km, type_rho, n_samples, a, b, c, alpha, max_it) # kernel evaluated on plot data gamma = 1. / (2 * (h**2)) K_plot = rbf_kernel(X_plot, X_data, gamma=gamma) * (2 * np.pi * h**2)**(-d / 2.) # final density z = np.dot(K_plot, w) if return_model: return z, w else: return z def spkde(X_data, X_plot, h, outliers_fraction, return_model=False): d = X_data.shape[1] beta = 1. / (1 - outliers_fraction) gamma = 1. / (2 * (h**2)) G = rbf_kernel(X_data, X_data, gamma=gamma) * (2 * np.pi * h**2)**(-d / 2.) P = matrix(G) q = matrix(-beta / X_data.shape[0] * np.sum(G, axis=0)) G = matrix(-np.identity(X_data.shape[0])) h_solver = matrix(np.zeros(X_data.shape[0])) A = matrix(np.ones((1, X_data.shape[0]))) b = matrix(1.0) sol = solvers.qp(P, q, G, h_solver, A, b) a = np.array(sol['x']).reshape((-1, )) # final density GG = rbf_kernel(X_data, X_plot, gamma=gamma) * (2 * np.pi * h**2)**(-d / 2.) z = np.zeros((X_plot.shape[0])) for j in range(X_plot.shape[0]): for i in range(len(a)): z[j] += a[i] * GG[i, j] if return_model: return z, a else: return z def bandwidth_cvgrid(X_data, loo=False, kfold=5): """ Compute the best bandwidth along a grid search. Parameters ----- X_data : input data Returns ----- h : the best bandwidth sigma : the search grid losses : the scores along the grid """ print("Finding best bandwidth...") sigma = np.logspace(-1.5, 0.5, 80) # grid for method 2 et 3 if loo: grid = GridSearchCV(KernelDensity(kernel='gaussian'), {'bandwidth': sigma}, cv=LeaveOneOut()) else: grid = GridSearchCV(KernelDensity(kernel='gaussian'), {'bandwidth': sigma}, cv=KFold(n_splits=kfold)) grid.fit(X_data) h = grid.best_params_['bandwidth'] losses = grid.cv_results_['mean_test_score'] # print('best h: ', h) return h, sigma, losses
[ "numpy.abs", "numpy.sum", "numpy.logspace", "numpy.ones", "numpy.mean", "numpy.exp", "numpy.diag", "numpy.std", "numpy.identity", "cvxopt.solvers.qp", "numpy.random.shuffle", "numpy.trapz", "numpy.minimum", "cvxopt.matrix", "numpy.median", "sklearn.neighbors.KernelDensity", "sklearn....
[((2347, 2357), 'numpy.sqrt', 'np.sqrt', (['t'], {}), '(t)\n', (2354, 2357), True, 'import numpy as np\n'), ((4741, 4763), 'numpy.median', 'np.median', (['res'], {'axis': '(0)'}), '(res, axis=0)\n', (4750, 4763), True, 'import numpy as np\n'), ((4796, 4808), 'numpy.mean', 'np.mean', (['res'], {}), '(res)\n', (4803, 4808), True, 'import numpy as np\n'), ((5547, 5563), 'numpy.array', 'np.array', (['X_data'], {}), '(X_data)\n', (5555, 5563), True, 'import numpy as np\n'), ((5568, 5596), 'numpy.random.shuffle', 'np.random.shuffle', (['X_shuffle'], {}), '(X_shuffle)\n', (5585, 5596), True, 'import numpy as np\n'), ((7135, 7150), 'numpy.median', 'np.median', (['norm'], {}), '(norm)\n', (7144, 7150), True, 'import numpy as np\n'), ((7159, 7182), 'numpy.percentile', 'np.percentile', (['norm', '(75)'], {}), '(norm, 75)\n', (7172, 7182), True, 'import numpy as np\n'), ((7191, 7214), 'numpy.percentile', 'np.percentile', (['norm', '(95)'], {}), '(norm, 95)\n', (7204, 7214), True, 'import numpy as np\n'), ((7549, 7566), 'numpy.dot', 'np.dot', (['K_plot', 'w'], {}), '(K_plot, w)\n', (7555, 7566), True, 'import numpy as np\n'), ((7889, 7898), 'cvxopt.matrix', 'matrix', (['G'], {}), '(G)\n', (7895, 7898), False, 'from cvxopt import matrix, solvers\n'), ((8108, 8119), 'cvxopt.matrix', 'matrix', (['(1.0)'], {}), '(1.0)\n', (8114, 8119), False, 'from cvxopt import matrix, solvers\n'), ((8130, 8165), 'cvxopt.solvers.qp', 'solvers.qp', (['P', 'q', 'G', 'h_solver', 'A', 'b'], {}), '(P, q, G, h_solver, A, b)\n', (8140, 8165), False, 'from cvxopt import matrix, solvers\n'), ((8318, 8343), 'numpy.zeros', 'np.zeros', (['X_plot.shape[0]'], {}), '(X_plot.shape[0])\n', (8326, 8343), True, 'import numpy as np\n'), ((8857, 8883), 'numpy.logspace', 'np.logspace', (['(-1.5)', '(0.5)', '(80)'], {}), '(-1.5, 0.5, 80)\n', (8868, 8883), True, 'import numpy as np\n'), ((366, 391), 'numpy.exp', 'np.exp', (['(-X / (2 * h ** 2))'], {}), '(-X / (2 * h ** 2))\n', (372, 391), True, 'import numpy as np\n'), ((720, 749), 'numpy.logical_and', 'np.logical_and', (['(a <= x)', '(x < b)'], {}), '(a <= x, x < b)\n', (734, 749), True, 'import numpy as np\n'), ((764, 793), 'numpy.logical_and', 'np.logical_and', (['(b <= x)', '(x < c)'], {}), '(b <= x, x < c)\n', (778, 793), True, 'import numpy as np\n'), ((1171, 1180), 'numpy.abs', 'np.abs', (['x'], {}), '(x)\n', (1177, 1180), True, 'import numpy as np\n'), ((1193, 1202), 'numpy.sum', 'np.sum', (['t'], {}), '(t)\n', (1199, 1202), True, 'import numpy as np\n'), ((1410, 1426), 'numpy.minimum', 'np.minimum', (['x', 'a'], {}), '(x, a)\n', (1420, 1426), True, 'import numpy as np\n'), ((1487, 1516), 'numpy.logical_and', 'np.logical_and', (['(a <= x)', '(x < b)'], {}), '(a <= x, x < b)\n', (1501, 1516), True, 'import numpy as np\n'), ((1531, 1560), 'numpy.logical_and', 'np.logical_and', (['(b <= x)', '(x < c)'], {}), '(b <= x, x < c)\n', (1545, 1560), True, 'import numpy as np\n'), ((1708, 1730), 'numpy.zeros', 'np.zeros', (['x[in4].shape'], {}), '(x[in4].shape)\n', (1716, 1730), True, 'import numpy as np\n'), ((2155, 2170), 'numpy.ones', 'np.ones', (['(n, 1)'], {}), '((n, 1))\n', (2162, 2170), True, 'import numpy as np\n'), ((2265, 2278), 'numpy.dot', 'np.dot', (['Km', 'w'], {}), '(Km, w)\n', (2271, 2278), True, 'import numpy as np\n'), ((2295, 2310), 'numpy.dot', 'np.dot', (['w.T', 'Km'], {}), '(w.T, Km)\n', (2301, 2310), True, 'import numpy as np\n'), ((2836, 2846), 'numpy.sqrt', 'np.sqrt', (['t'], {}), '(t)\n', (2843, 2846), True, 'import numpy as np\n'), ((3686, 3712), 'numpy.trapz', 'np.trapz', (['area', 'ax'], {'axis': '(0)'}), '(area, ax, axis=0)\n', (3694, 3712), True, 'import numpy as np\n'), ((4331, 4396), 'numpy.random.uniform', 'np.random.uniform', (['cube_lows', 'cube_highs'], {'size': '(n_mc, X.shape[1])'}), '(cube_lows, cube_highs, size=(n_mc, X.shape[1]))\n', (4348, 4396), True, 'import numpy as np\n'), ((5837, 5864), 'sklearn.neighbors.KernelDensity', 'KernelDensity', ([], {'bandwidth': 'h0'}), '(bandwidth=h0)\n', (5850, 5864), False, 'from sklearn.neighbors import KernelDensity\n'), ((6009, 6029), 'numpy.median', 'np.median', (['z'], {'axis': '(0)'}), '(z, axis=0)\n', (6018, 6029), True, 'import numpy as np\n'), ((6802, 6841), 'sklearn.metrics.pairwise.rbf_kernel', 'rbf_kernel', (['X_data', 'X_data'], {'gamma': 'gamma'}), '(X_data, X_data, gamma=gamma)\n', (6812, 6841), False, 'from sklearn.metrics.pairwise import rbf_kernel\n'), ((7449, 7488), 'sklearn.metrics.pairwise.rbf_kernel', 'rbf_kernel', (['X_plot', 'X_data'], {'gamma': 'gamma'}), '(X_plot, X_data, gamma=gamma)\n', (7459, 7488), False, 'from sklearn.metrics.pairwise import rbf_kernel\n'), ((7808, 7847), 'sklearn.metrics.pairwise.rbf_kernel', 'rbf_kernel', (['X_data', 'X_data'], {'gamma': 'gamma'}), '(X_data, X_data, gamma=gamma)\n', (7818, 7847), False, 'from sklearn.metrics.pairwise import rbf_kernel\n'), ((8027, 8052), 'numpy.zeros', 'np.zeros', (['X_data.shape[0]'], {}), '(X_data.shape[0])\n', (8035, 8052), True, 'import numpy as np\n'), ((8069, 8098), 'numpy.ones', 'np.ones', (['(1, X_data.shape[0])'], {}), '((1, X_data.shape[0]))\n', (8076, 8098), True, 'import numpy as np\n'), ((8238, 8277), 'sklearn.metrics.pairwise.rbf_kernel', 'rbf_kernel', (['X_data', 'X_plot'], {'gamma': 'gamma'}), '(X_data, X_plot, gamma=gamma)\n', (8248, 8277), False, 'from sklearn.metrics.pairwise import rbf_kernel\n'), ((630, 643), 'numpy.sum', 'np.sum', (['in1_t'], {}), '(in1_t)\n', (636, 643), True, 'import numpy as np\n'), ((646, 659), 'numpy.sum', 'np.sum', (['in2_t'], {}), '(in2_t)\n', (652, 659), True, 'import numpy as np\n'), ((1083, 1096), 'numpy.sum', 'np.sum', (['in4_t'], {}), '(in4_t)\n', (1089, 1096), True, 'import numpy as np\n'), ((1623, 1644), 'numpy.ones', 'np.ones', (['x[in2].shape'], {}), '(x[in2].shape)\n', (1630, 1644), True, 'import numpy as np\n'), ((2201, 2212), 'numpy.diag', 'np.diag', (['Km'], {}), '(Km)\n', (2208, 2212), True, 'import numpy as np\n'), ((2651, 2660), 'numpy.sum', 'np.sum', (['w'], {}), '(w)\n', (2657, 2660), True, 'import numpy as np\n'), ((2742, 2755), 'numpy.dot', 'np.dot', (['Km', 'w'], {}), '(Km, w)\n', (2748, 2755), True, 'import numpy as np\n'), ((2776, 2791), 'numpy.dot', 'np.dot', (['w.T', 'Km'], {}), '(w.T, Km)\n', (2782, 2791), True, 'import numpy as np\n'), ((3207, 3248), 'sklearn.neighbors.KernelDensity', 'KernelDensity', ([], {'kernel': 'kernel', 'bandwidth': 'h'}), '(kernel=kernel, bandwidth=h)\n', (3220, 3248), False, 'from sklearn.neighbors import KernelDensity\n'), ((4517, 4533), 'sklearn.neighbors.KernelDensity', 'KernelDensity', (['h'], {}), '(h)\n', (4530, 4533), False, 'from sklearn.neighbors import KernelDensity\n'), ((5750, 5764), 'numpy.std', 'np.std', (['values'], {}), '(values)\n', (5756, 5764), True, 'import numpy as np\n'), ((7940, 7957), 'numpy.sum', 'np.sum', (['G'], {'axis': '(0)'}), '(G, axis=0)\n', (7946, 7957), True, 'import numpy as np\n'), ((7975, 8003), 'numpy.identity', 'np.identity', (['X_data.shape[0]'], {}), '(X_data.shape[0])\n', (7986, 8003), True, 'import numpy as np\n'), ((8174, 8192), 'numpy.array', 'np.array', (["sol['x']"], {}), "(sol['x'])\n", (8182, 8192), True, 'import numpy as np\n'), ((8950, 8982), 'sklearn.neighbors.KernelDensity', 'KernelDensity', ([], {'kernel': '"""gaussian"""'}), "(kernel='gaussian')\n", (8963, 8982), False, 'from sklearn.neighbors import KernelDensity\n'), ((9118, 9150), 'sklearn.neighbors.KernelDensity', 'KernelDensity', ([], {'kernel': '"""gaussian"""'}), "(kernel='gaussian')\n", (9131, 9150), False, 'from sklearn.neighbors import KernelDensity\n'), ((1067, 1080), 'numpy.sum', 'np.sum', (['in3_t'], {}), '(in3_t)\n', (1073, 1080), True, 'import numpy as np\n'), ((1746, 1790), 'numpy.concatenate', 'np.concatenate', (['(in1_t, in2_t, in3_t, in4_t)'], {}), '((in1_t, in2_t, in3_t, in4_t))\n', (1760, 1790), True, 'import numpy as np\n'), ((2674, 2685), 'numpy.diag', 'np.diag', (['Km'], {}), '(Km)\n', (2681, 2685), True, 'import numpy as np\n'), ((2959, 2976), 'numpy.abs', 'np.abs', (['(J - J_old)'], {}), '(J - J_old)\n', (2965, 2976), True, 'import numpy as np\n'), ((4197, 4218), 'numpy.abs', 'np.abs', (['(x_max - x_min)'], {}), '(x_max - x_min)\n', (4203, 4218), True, 'import numpy as np\n'), ((9065, 9078), 'sklearn.model_selection.LeaveOneOut', 'LeaveOneOut', ([], {}), '()\n', (9076, 9078), False, 'from sklearn.model_selection import GridSearchCV, LeaveOneOut, KFold\n'), ((9233, 9254), 'sklearn.model_selection.KFold', 'KFold', ([], {'n_splits': 'kfold'}), '(n_splits=kfold)\n', (9238, 9254), False, 'from sklearn.model_selection import GridSearchCV, LeaveOneOut, KFold\n'), ((979, 1000), 'numpy.ones', 'np.ones', (['x[in4].shape'], {}), '(x[in4].shape)\n', (986, 1000), True, 'import numpy as np\n'), ((1035, 1048), 'numpy.sum', 'np.sum', (['in1_t'], {}), '(in1_t)\n', (1041, 1048), True, 'import numpy as np\n'), ((1051, 1064), 'numpy.sum', 'np.sum', (['in2_t'], {}), '(in2_t)\n', (1057, 1064), True, 'import numpy as np\n'), ((4427, 4447), 'numpy.array', 'np.array', (['cube_highs'], {}), '(cube_highs)\n', (4435, 4447), True, 'import numpy as np\n'), ((4450, 4469), 'numpy.array', 'np.array', (['cube_lows'], {}), '(cube_lows)\n', (4458, 4469), True, 'import numpy as np\n')]
import tensorflow as tf import numpy as np import math from lib.Layer import Layer class ConvToFullyConnected(Layer): def __init__(self, input_shape): self.shape = input_shape ################################################################### def get_weights(self): return [] def output_shape(self): return np.prod(self.shape) def num_params(self): return 0 def forward(self, X): A = tf.reshape(X, [tf.shape(X)[0], -1]) return {'aout':A, 'cache':{}} ################################################################### def bp(self, AI, AO, DO, cache): DI = tf.reshape(DO, [tf.shape(AI)[0]] + self.shape) return {'dout':DI, 'cache':{}}, [] def dfa(self, AI, AO, E, DO, cache): return self.bp(AI, AO, DO, cache) def lel(self, AI, AO, DO, Y, cache): return self.bp(AI, AO, DO, cache) ###################################################################
[ "tensorflow.shape", "numpy.prod" ]
[((372, 391), 'numpy.prod', 'np.prod', (['self.shape'], {}), '(self.shape)\n', (379, 391), True, 'import numpy as np\n'), ((498, 509), 'tensorflow.shape', 'tf.shape', (['X'], {}), '(X)\n', (506, 509), True, 'import tensorflow as tf\n'), ((709, 721), 'tensorflow.shape', 'tf.shape', (['AI'], {}), '(AI)\n', (717, 721), True, 'import tensorflow as tf\n')]
import csv import cv2 import numpy as np import sklearn from keras.models import Sequential from keras.layers import Dense, Activation, Flatten, Dropout, Lambda, Conv2D, Convolution2D, MaxPooling2D, Cropping2D from sklearn.model_selection import train_test_split from sklearn.utils import shuffle BATCH_SIZE = 32 def import_driving_log(): lines = [] images = [] steering_angles = [] # Import images from left/center/right cameras and their respective steering angle with open('MyData/driving_log.csv') as csvfile: reader = csv.reader(csvfile) iterate_reader = iter(reader) next(iterate_reader) for index, line in enumerate(iterate_reader): img_center = cv2.imread('MyData/IMG/' + line[0].split('/')[-1]) img_left = cv2.imread('MyData/IMG/' + line[1].split('/')[-1]) img_right = cv2.imread('MyData/IMG/' + line[2].split('/')[-1]) #img_center_resized = cv2.resize(img_center, dsize=(int(img_center.shape[1]/4), int(img_center.shape[0]/4)), interpolation=cv2.INTER_CUBIC) #img_left_resized = cv2.resize(img_left, dsize=(int(img_left.shape[1]/4), int(img_left.shape[0]/4)), interpolation=cv2.INTER_CUBIC) #img_right_resized = cv2.resize(img_right, dsize=(int(img_right.shape[1]/4), int(img_right.shape[0]/4)), interpolation=cv2.INTER_CUBIC) images.append(img_center) images.append(img_left) images.append(img_right) steering_center = float(line[3]) steering_left = steering_center + 0.2 steering_right = steering_center - 0.2 steering_angles.append(steering_center) steering_angles.append(steering_left) steering_angles.append(steering_right) X_train = np.array(images) y_train = np.array(steering_angles) return X_train, y_train def flip_images(X_train, y_train): # Flip images to get more data for the opposite steering augmented_images, augmented_measurements = [], [] for image, steering_angles in zip(X_train, y_train): augmented_images.append(image) augmented_measurements.append(steering_angles) augmented_images.append(cv2.flip(image,1)) augmented_measurements.append(steering_angles*-1.0) X_train = np.array(augmented_images) y_train = np.array(augmented_measurements) return X_train, y_train def create_cnn_model(): # Create Sequential model (linear stack of layers) for CNN model = Sequential() # Normalize input images model.add(Lambda(lambda x: x/255.0 - 0.5, input_shape=(160,320,3), output_shape=(160,320,3))) # Crop images (70 pixels on top, 25 pixels on bottom) to get rid of part of the images bringing no relevant information (sky, hood of the car) model.add(Cropping2D(cropping=((70,25), (0,0)))) # Add layers to the neural network (based on the architecture of NVIDIA's CNN) model.add(Conv2D(18,5,5, activation="relu")) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(24,3,3, activation="relu")) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(48,3,3, activation="relu")) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(96,3,3, activation="relu")) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Flatten()) model.add(Dense(120)) model.add(Dropout(0.4)) model.add(Dense(84)) model.add(Dropout(0.4)) model.add(Dense(1)) model.summary() return model # Use a generator to process part of the dataset (shuffled) on the fly only when needed, which is more memory-efficient. def generator(X, y, batch_size = BATCH_SIZE): assert len(X) == len(y) num_samples = len(X) while 1: X_shuffled, y_shuffled = shuffle(X, y, random_state=0) for offset in range(0, num_samples, batch_size): images_samples = X_shuffled[offset:offset+batch_size] angles_samples = y_shuffled[offset:offset+batch_size] X_generated = np.array(images_samples) y_generated = np.array(angles_samples) yield shuffle(X_generated, y_generated) # import the information from the dataset (images as input and steering angles as output) X_train, y_train = import_driving_log() # create more data by adding flipped images of the same dataset X_train, y_train = flip_images(X_train, y_train) print(X_train.shape) # Split the dataset between training samples (80%) and validation samples (20%) X_train_samples, X_validation_samples, y_train_samples, y_validation_samples = train_test_split(X_train, y_train, test_size=0.2) print(X_train_samples.shape) print(X_validation_samples.shape) # compile and train the model using the generator function train_generator = generator(X_train_samples, y_train_samples, batch_size=BATCH_SIZE) validation_generator = generator(X_validation_samples, y_validation_samples, batch_size=BATCH_SIZE) # create neural network based on our model architecture model = create_cnn_model() # Configure the learning process (using adam optimization algorithm) model.compile(loss='mse', optimizer='adam') # Trains the model on data generated batch-by-batch by the generator model.fit_generator(train_generator, steps_per_epoch= len(X_train_samples)/BATCH_SIZE, validation_data=validation_generator, validation_steps=len(X_validation_samples)/BATCH_SIZE, epochs=5, verbose = 1) model.save('model.h5')
[ "csv.reader", "keras.layers.Cropping2D", "sklearn.model_selection.train_test_split", "keras.layers.Dropout", "keras.layers.Flatten", "cv2.flip", "keras.layers.Dense", "keras.layers.Lambda", "numpy.array", "keras.layers.Conv2D", "keras.models.Sequential", "sklearn.utils.shuffle", "keras.layer...
[((4236, 4285), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X_train', 'y_train'], {'test_size': '(0.2)'}), '(X_train, y_train, test_size=0.2)\n', (4252, 4285), False, 'from sklearn.model_selection import train_test_split\n'), ((1627, 1643), 'numpy.array', 'np.array', (['images'], {}), '(images)\n', (1635, 1643), True, 'import numpy as np\n'), ((1655, 1680), 'numpy.array', 'np.array', (['steering_angles'], {}), '(steering_angles)\n', (1663, 1680), True, 'import numpy as np\n'), ((2100, 2126), 'numpy.array', 'np.array', (['augmented_images'], {}), '(augmented_images)\n', (2108, 2126), True, 'import numpy as np\n'), ((2138, 2170), 'numpy.array', 'np.array', (['augmented_measurements'], {}), '(augmented_measurements)\n', (2146, 2170), True, 'import numpy as np\n'), ((2292, 2304), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (2302, 2304), False, 'from keras.models import Sequential\n'), ((535, 554), 'csv.reader', 'csv.reader', (['csvfile'], {}), '(csvfile)\n', (545, 554), False, 'import csv\n'), ((2343, 2436), 'keras.layers.Lambda', 'Lambda', (['(lambda x: x / 255.0 - 0.5)'], {'input_shape': '(160, 320, 3)', 'output_shape': '(160, 320, 3)'}), '(lambda x: x / 255.0 - 0.5, input_shape=(160, 320, 3), output_shape=(\n 160, 320, 3))\n', (2349, 2436), False, 'from keras.layers import Dense, Activation, Flatten, Dropout, Lambda, Conv2D, Convolution2D, MaxPooling2D, Cropping2D\n'), ((2583, 2622), 'keras.layers.Cropping2D', 'Cropping2D', ([], {'cropping': '((70, 25), (0, 0))'}), '(cropping=((70, 25), (0, 0)))\n', (2593, 2622), False, 'from keras.layers import Dense, Activation, Flatten, Dropout, Lambda, Conv2D, Convolution2D, MaxPooling2D, Cropping2D\n'), ((2715, 2750), 'keras.layers.Conv2D', 'Conv2D', (['(18)', '(5)', '(5)'], {'activation': '"""relu"""'}), "(18, 5, 5, activation='relu')\n", (2721, 2750), False, 'from keras.layers import Dense, Activation, Flatten, Dropout, Lambda, Conv2D, Convolution2D, MaxPooling2D, Cropping2D\n'), ((2761, 2791), 'keras.layers.MaxPooling2D', 'MaxPooling2D', ([], {'pool_size': '(2, 2)'}), '(pool_size=(2, 2))\n', (2773, 2791), False, 'from keras.layers import Dense, Activation, Flatten, Dropout, Lambda, Conv2D, Convolution2D, MaxPooling2D, Cropping2D\n'), ((2804, 2839), 'keras.layers.Conv2D', 'Conv2D', (['(24)', '(3)', '(3)'], {'activation': '"""relu"""'}), "(24, 3, 3, activation='relu')\n", (2810, 2839), False, 'from keras.layers import Dense, Activation, Flatten, Dropout, Lambda, Conv2D, Convolution2D, MaxPooling2D, Cropping2D\n'), ((2850, 2880), 'keras.layers.MaxPooling2D', 'MaxPooling2D', ([], {'pool_size': '(2, 2)'}), '(pool_size=(2, 2))\n', (2862, 2880), False, 'from keras.layers import Dense, Activation, Flatten, Dropout, Lambda, Conv2D, Convolution2D, MaxPooling2D, Cropping2D\n'), ((2893, 2928), 'keras.layers.Conv2D', 'Conv2D', (['(48)', '(3)', '(3)'], {'activation': '"""relu"""'}), "(48, 3, 3, activation='relu')\n", (2899, 2928), False, 'from keras.layers import Dense, Activation, Flatten, Dropout, Lambda, Conv2D, Convolution2D, MaxPooling2D, Cropping2D\n'), ((2939, 2969), 'keras.layers.MaxPooling2D', 'MaxPooling2D', ([], {'pool_size': '(2, 2)'}), '(pool_size=(2, 2))\n', (2951, 2969), False, 'from keras.layers import Dense, Activation, Flatten, Dropout, Lambda, Conv2D, Convolution2D, MaxPooling2D, Cropping2D\n'), ((2982, 3017), 'keras.layers.Conv2D', 'Conv2D', (['(96)', '(3)', '(3)'], {'activation': '"""relu"""'}), "(96, 3, 3, activation='relu')\n", (2988, 3017), False, 'from keras.layers import Dense, Activation, Flatten, Dropout, Lambda, Conv2D, Convolution2D, MaxPooling2D, Cropping2D\n'), ((3028, 3058), 'keras.layers.MaxPooling2D', 'MaxPooling2D', ([], {'pool_size': '(2, 2)'}), '(pool_size=(2, 2))\n', (3040, 3058), False, 'from keras.layers import Dense, Activation, Flatten, Dropout, Lambda, Conv2D, Convolution2D, MaxPooling2D, Cropping2D\n'), ((3071, 3080), 'keras.layers.Flatten', 'Flatten', ([], {}), '()\n', (3078, 3080), False, 'from keras.layers import Dense, Activation, Flatten, Dropout, Lambda, Conv2D, Convolution2D, MaxPooling2D, Cropping2D\n'), ((3093, 3103), 'keras.layers.Dense', 'Dense', (['(120)'], {}), '(120)\n', (3098, 3103), False, 'from keras.layers import Dense, Activation, Flatten, Dropout, Lambda, Conv2D, Convolution2D, MaxPooling2D, Cropping2D\n'), ((3116, 3128), 'keras.layers.Dropout', 'Dropout', (['(0.4)'], {}), '(0.4)\n', (3123, 3128), False, 'from keras.layers import Dense, Activation, Flatten, Dropout, Lambda, Conv2D, Convolution2D, MaxPooling2D, Cropping2D\n'), ((3141, 3150), 'keras.layers.Dense', 'Dense', (['(84)'], {}), '(84)\n', (3146, 3150), False, 'from keras.layers import Dense, Activation, Flatten, Dropout, Lambda, Conv2D, Convolution2D, MaxPooling2D, Cropping2D\n'), ((3163, 3175), 'keras.layers.Dropout', 'Dropout', (['(0.4)'], {}), '(0.4)\n', (3170, 3175), False, 'from keras.layers import Dense, Activation, Flatten, Dropout, Lambda, Conv2D, Convolution2D, MaxPooling2D, Cropping2D\n'), ((3188, 3196), 'keras.layers.Dense', 'Dense', (['(1)'], {}), '(1)\n', (3193, 3196), False, 'from keras.layers import Dense, Activation, Flatten, Dropout, Lambda, Conv2D, Convolution2D, MaxPooling2D, Cropping2D\n'), ((3485, 3514), 'sklearn.utils.shuffle', 'shuffle', (['X', 'y'], {'random_state': '(0)'}), '(X, y, random_state=0)\n', (3492, 3514), False, 'from sklearn.utils import shuffle\n'), ((2015, 2033), 'cv2.flip', 'cv2.flip', (['image', '(1)'], {}), '(image, 1)\n', (2023, 2033), False, 'import cv2\n'), ((3697, 3721), 'numpy.array', 'np.array', (['images_samples'], {}), '(images_samples)\n', (3705, 3721), True, 'import numpy as np\n'), ((3739, 3763), 'numpy.array', 'np.array', (['angles_samples'], {}), '(angles_samples)\n', (3747, 3763), True, 'import numpy as np\n'), ((3773, 3806), 'sklearn.utils.shuffle', 'shuffle', (['X_generated', 'y_generated'], {}), '(X_generated, y_generated)\n', (3780, 3806), False, 'from sklearn.utils import shuffle\n')]
from torchvision import datasets, transforms import torch import numpy as np from PIL import Image import PIL from config import options class CIFAR10: def __init__(self, mode='train'): self.mode = mode if mode == 'train': train_dataset = datasets.CIFAR10(root='./dataset', train=True, download=True) self.images = train_dataset.data self.labels = np.array(train_dataset.targets) elif mode == 'test': test_dataset = datasets.CIFAR10(root='./dataset', train=False, download=True) self.images = test_dataset.data self.labels = np.array(test_dataset.targets) def __getitem__(self, index): img = self.images[index] target = torch.tensor(self.labels[index]).long() # augmentation and normalization if self.mode == 'train': img = Image.fromarray(img, mode='RGB') img = transforms.RandomResizedCrop(options.img_w, scale=(0.8, 1.))(img) img = transforms.RandomHorizontalFlip()(img) img = transforms.RandomRotation(degrees=90, resample=PIL.Image.BICUBIC)(img) img = transforms.ToTensor()(img).float() return img, target def __len__(self): return len(self.labels)
[ "torchvision.transforms.RandomHorizontalFlip", "torchvision.transforms.RandomRotation", "torchvision.datasets.CIFAR10", "numpy.array", "PIL.Image.fromarray", "torchvision.transforms.RandomResizedCrop", "torch.tensor", "torchvision.transforms.ToTensor" ]
[((273, 334), 'torchvision.datasets.CIFAR10', 'datasets.CIFAR10', ([], {'root': '"""./dataset"""', 'train': '(True)', 'download': '(True)'}), "(root='./dataset', train=True, download=True)\n", (289, 334), False, 'from torchvision import datasets, transforms\n'), ((406, 437), 'numpy.array', 'np.array', (['train_dataset.targets'], {}), '(train_dataset.targets)\n', (414, 437), True, 'import numpy as np\n'), ((876, 908), 'PIL.Image.fromarray', 'Image.fromarray', (['img'], {'mode': '"""RGB"""'}), "(img, mode='RGB')\n", (891, 908), False, 'from PIL import Image\n'), ((494, 556), 'torchvision.datasets.CIFAR10', 'datasets.CIFAR10', ([], {'root': '"""./dataset"""', 'train': '(False)', 'download': '(True)'}), "(root='./dataset', train=False, download=True)\n", (510, 556), False, 'from torchvision import datasets, transforms\n'), ((627, 657), 'numpy.array', 'np.array', (['test_dataset.targets'], {}), '(test_dataset.targets)\n', (635, 657), True, 'import numpy as np\n'), ((743, 775), 'torch.tensor', 'torch.tensor', (['self.labels[index]'], {}), '(self.labels[index])\n', (755, 775), False, 'import torch\n'), ((927, 988), 'torchvision.transforms.RandomResizedCrop', 'transforms.RandomResizedCrop', (['options.img_w'], {'scale': '(0.8, 1.0)'}), '(options.img_w, scale=(0.8, 1.0))\n', (955, 988), False, 'from torchvision import datasets, transforms\n'), ((1011, 1044), 'torchvision.transforms.RandomHorizontalFlip', 'transforms.RandomHorizontalFlip', ([], {}), '()\n', (1042, 1044), False, 'from torchvision import datasets, transforms\n'), ((1068, 1133), 'torchvision.transforms.RandomRotation', 'transforms.RandomRotation', ([], {'degrees': '(90)', 'resample': 'PIL.Image.BICUBIC'}), '(degrees=90, resample=PIL.Image.BICUBIC)\n', (1093, 1133), False, 'from torchvision import datasets, transforms\n'), ((1154, 1175), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (1173, 1175), False, 'from torchvision import datasets, transforms\n')]
# coding: utf-8 from __future__ import division from __future__ import print_function from __future__ import unicode_literals import sys import argparse import os import numpy as np from .read_files import split_imdb_files, split_yahoo_files, split_agnews_files, split_snli_files from .word_level_process import word_process, get_tokenizer from .char_level_process import char_process from .adversarial_tools import ForwardGradWrapper, ForwardGradWrapper_pytorch, adversarial_paraphrase, ForwardGradWrapper_pytorch_snli, adversarial_paraphrase_snli import time import random from .unbuffered import Unbuffered import torch try: import cPickle as pickle except ImportError: import pickle sys.stdout = Unbuffered(sys.stdout) def write_origin_input_texts(origin_input_texts_path, test_texts, test_samples_cap=None): if test_samples_cap is None: test_samples_cap = len(test_texts) with open(origin_input_texts_path, 'a') as f: for i in range(test_samples_cap): f.write(test_texts[i] + '\n') def genetic_attack(opt, device, model, attack_surface, dataset='imdb', genetic_test_num=100, test_bert=False): if test_bert: if opt.bert_type=="bert": from modified_bert_tokenizer import ModifiedBertTokenizer tokenizer = ModifiedBertTokenizer.from_pretrained("bert-base-uncased", do_lower_case=True) elif opt.bert_type=="roberta": from modified_bert_tokenizer import ModifiedRobertaTokenizer tokenizer = ModifiedRobertaTokenizer.from_pretrained("roberta-base",add_prefix_space=True) elif opt.bert_type=="xlnet": from modified_bert_tokenizer import ModifiedXLNetTokenizer tokenizer = ModifiedXLNetTokenizer.from_pretrained("xlnet-base-cased", do_lower_case=True) else: # get tokenizer tokenizer = get_tokenizer(opt) if dataset == 'imdb': train_texts, train_labels, dev_texts, dev_labels, test_texts, test_labels = split_imdb_files(opt) #x_train, y_train, x_test, y_test = word_process(train_texts, train_labels, test_texts, test_labels, dataset) indexes = [i for i in range(len(test_texts))] random.seed(opt.rand_seed) random.shuffle(indexes) test_texts = [test_texts[i] for i in indexes] test_labels = [test_labels[i] for i in indexes] indexes = [] for i, x in enumerate(test_texts): words = x.split() if attack_surface.check_in(words): indexes.append(i) test_texts = [test_texts[i] for i in indexes] test_labels = [test_labels[i] for i in indexes] #print("all_genetic_in_lm", len(test_texts)) test_num = min(len(test_texts), genetic_test_num) test_texts = test_texts[:test_num] test_labels = test_labels[:test_num] from .attacks import GeneticAdversary, AdversarialModel adversary = GeneticAdversary(opt, attack_surface, num_iters=opt.genetic_iters, pop_size=opt.genetic_pop_size) from .config import config wrapped_model = AdversarialModel(tokenizer, config.word_max_len[dataset], test_bert=test_bert, bert_type=opt.bert_type) from multiprocessing import Process, Pipe conn_main = [] conn_p = [] for i in range(test_num): c1, c2 = Pipe() conn_main.append(c1) conn_p.append(c2) process_list = [] for i in range(test_num): p = Process(target=adversary.run, args=(conn_p[i], wrapped_model, test_texts[i], test_labels[i], 'cpu')) p.start() process_list.append(p) tested = 0 acc = 0 bs = 100 model.eval() p_state=[1 for i in range(test_num)] t_start = time.time() test_text = torch.zeros(bs, config.word_max_len[dataset],dtype=torch.long).to(device) test_mask = torch.zeros(bs, config.word_max_len[dataset],dtype=torch.long).to(device) test_token_type_ids = torch.zeros(bs, config.word_max_len[dataset],dtype=torch.long).to(device) i=0 while(1): if tested == test_num: break #for i in range(genetic_test_num): bs_j=0 res_dict = {} while(1): i=(i+1)%test_num if p_state[i] == 1: cm=conn_main[i] if cm.poll(): msg = cm.recv() if msg == 0 or msg == 1: tested+=1 acc+=msg cm.close() p_state[i]=0 process_list[i].join() else: text, mask, token_type_ids = msg test_text[bs_j] = text.to(device) test_mask[bs_j] = mask.to(device) test_token_type_ids[bs_j] = token_type_ids.to(device) res_dict[i]=bs_j bs_j +=1 if bs_j==bs or bs_j>=(test_num-tested): break with torch.no_grad(): logits = model(mode="text_to_logit", input=test_text, bert_mask=test_mask, bert_token_id=test_token_type_ids).detach().cpu() for key in res_dict.keys(): cm=conn_main[key] cm.send(logits[res_dict[key]]) bs_j = 0 #print("final genetic", acc/tested) print("genetic time:", time.time()-t_start) return acc/tested def genetic_attack_snli(opt, device, model, attack_surface, dataset='snli', genetic_test_num=100, split="test", test_bert=False): if test_bert: if opt.bert_type=="bert": from modified_bert_tokenizer import ModifiedBertTokenizer tokenizer = ModifiedBertTokenizer.from_pretrained("bert-base-uncased", do_lower_case=True) elif opt.bert_type=="roberta": from modified_bert_tokenizer import ModifiedRobertaTokenizer tokenizer = ModifiedRobertaTokenizer.from_pretrained("roberta-base",add_prefix_space=True) else: # get tokenizer tokenizer = get_tokenizer(opt) # Read data set if dataset == 'snli': train_perms, train_hypos, train_labels, dev_perms, dev_hypos, dev_labels, test_perms, test_hypos, test_labels = split_snli_files(opt) else: raise NotImplementedError indexes = [i for i in range(len(test_labels))] random.seed(opt.rand_seed) random.shuffle(indexes) test_perms = [test_perms[i] for i in indexes] test_hypos = [test_hypos[i] for i in indexes] test_labels = [test_labels[i] for i in indexes] from .attacks import GeneticAdversary_Snli, AdversarialModel_Snli adversary = GeneticAdversary_Snli(attack_surface, num_iters=opt.genetic_iters, pop_size=opt.genetic_pop_size) from .config import config wrapped_model = AdversarialModel_Snli(model, tokenizer, config.word_max_len[dataset], test_bert=test_bert, bert_type=opt.bert_type) adv_acc = adversary.run(wrapped_model, test_perms, test_hypos, test_labels, device, genetic_test_num, opt) print("genetic attack results:", adv_acc) return adv_acc def fool_text_classifier_pytorch(opt, device,model, dataset='imdb', clean_samples_cap=50, test_bert=False): print('clean_samples_cap:', clean_samples_cap) if test_bert: if opt.bert_type=="bert": from modified_bert_tokenizer import ModifiedBertTokenizer tokenizer = ModifiedBertTokenizer.from_pretrained("bert-base-uncased", do_lower_case=True) elif opt.bert_type=="roberta": from modified_bert_tokenizer import ModifiedRobertaTokenizer tokenizer = ModifiedRobertaTokenizer.from_pretrained("roberta-base",add_prefix_space=True) elif opt.bert_type=="xlnet": from modified_bert_tokenizer import ModifiedXLNetTokenizer tokenizer = ModifiedXLNetTokenizer.from_pretrained("xlnet-base-cased", do_lower_case=True) else: # get tokenizer tokenizer = get_tokenizer(opt) train_texts, train_labels, dev_texts, dev_labels, test_texts, test_labels = split_imdb_files(opt) # if opt.synonyms_from_file: # if dataset == 'imdb': # train_texts, train_labels, dev_texts, dev_labels, test_texts, test_labels = split_imdb_files(opt) # elif dataset == 'agnews': # train_texts, train_labels, test_texts, test_labels = split_agnews_files() # elif dataset == 'yahoo': # train_texts, train_labels, test_texts, test_labels = split_yahoo_files() # filename= opt.imdb_synonyms_file_path # f=open(filename,'rb') # saved=pickle.load(f) # f.close() # #syn_data = saved["syn_data"] # #opt.embeddings=saved['embeddings'] # #opt.vocab_size=saved['vocab_size'] # x_train=saved['x_train'] # x_test=saved['x_test'] # y_train=saved['y_train'] # y_test=saved['y_test'] # else: # if dataset == 'imdb': # train_texts, train_labels, dev_texts, dev_labels, test_texts, test_labels = split_imdb_files(opt) # x_train, y_train, x_test, y_test = word_process(train_texts, train_labels, test_texts, test_labels, dataset) # elif dataset == 'agnews': # train_texts, train_labels, test_texts, test_labels = split_agnews_files() # x_train, y_train, x_test, y_test = word_process(train_texts, train_labels, test_texts, test_labels, dataset) # elif dataset == 'yahoo': # train_texts, train_labels, test_texts, test_labels = split_yahoo_files() # x_train, y_train, x_test, y_test = word_process(train_texts, train_labels, test_texts, test_labels, dataset) #shuffle test_texts indexes = [i for i in range(len(test_texts))] random.seed(opt.rand_seed) random.shuffle(indexes) test_texts = [test_texts[i] for i in indexes] test_labels = [test_labels[i] for i in indexes] from .config import config grad_guide = ForwardGradWrapper_pytorch(dataset, config.word_max_len[dataset], model, device, tokenizer, test_bert, opt.bert_type) classes_prediction = [grad_guide.predict_classes(text) for text in test_texts[: clean_samples_cap]] print(sum([classes_prediction[i]==np.argmax(test_labels[i]) for i in range(clean_samples_cap)])/clean_samples_cap) print('Crafting adversarial examples...') successful_perturbations = 0 failed_perturbations = 0 all_test_num =0 sub_rate_list = [] NE_rate_list = [] fa_path = r'./fool_result/{}'.format(dataset) if not os.path.exists(fa_path): os.makedirs(fa_path) adv_text_path = r'./fool_result/{}/adv_{}.txt'.format(dataset, str(clean_samples_cap)) change_tuple_path = r'./fool_result/{}/change_tuple_{}.txt'.format(dataset, str(clean_samples_cap)) #file_1 = open(adv_text_path, "a") #file_2 = open(change_tuple_path, "a") for index, text in enumerate(test_texts[opt.h_test_start: opt.h_test_start+clean_samples_cap]): sub_rate = 0 NE_rate = 0 all_test_num+=1 print('_____{}______.'.format(index)) if np.argmax(test_labels[index]) == classes_prediction[index]: print('do') start_cpu = time.clock() # If the ground_true label is the same as the predicted label adv_doc, adv_y, sub_rate, NE_rate, change_tuple_list = adversarial_paraphrase(opt, input_text=text, true_y=np.argmax(test_labels[index]), grad_guide=grad_guide, tokenizer=tokenizer, dataset=dataset, level='word') if adv_y != np.argmax(test_labels[index]): successful_perturbations += 1 print('{}. Successful example crafted.'.format(index)) else: failed_perturbations += 1 print('{}. Failure.'.format(index)) print("r acc", 1.0*failed_perturbations/all_test_num) text = adv_doc sub_rate_list.append(sub_rate) NE_rate_list.append(NE_rate) end_cpu = time.clock() print('CPU second:', end_cpu - start_cpu) #mean_sub_rate = sum(sub_rate_list) / len(sub_rate_list) #mean_NE_rate = sum(NE_rate_list) / len(NE_rate_list) print('substitution:', sum(sub_rate_list)) print('sum substitution:', len(sub_rate_list)) print('NE rate:', sum(NE_rate_list)) print('sum NE:', len(NE_rate_list)) print("succ attack %d"%(successful_perturbations)) print("fail attack %d"%(failed_perturbations)) #file_1.close() #file_2.close() def fool_text_classifier_pytorch_snli(opt, device,model, dataset='snli', clean_samples_cap=50, test_bert=False): print('clean_samples_cap:', clean_samples_cap) if test_bert: if opt.bert_type=="bert": from modified_bert_tokenizer import ModifiedBertTokenizer tokenizer = ModifiedBertTokenizer.from_pretrained("bert-base-uncased", do_lower_case=True) elif opt.bert_type=="roberta": from modified_bert_tokenizer import ModifiedRobertaTokenizer tokenizer = ModifiedRobertaTokenizer.from_pretrained("roberta-base",add_prefix_space=True) else: # get tokenizer tokenizer = get_tokenizer(opt) if dataset == 'snli': train_perms, train_hypos, train_labels, dev_perms, dev_hypos, dev_labels, test_perms, test_hypos, test_labels = split_snli_files(opt) else: raise NotImplementedError #shuffle test_texts indexes = [i for i in range(len(test_perms))] random.seed(opt.rand_seed) random.shuffle(indexes) test_perms = [test_perms[i] for i in indexes] test_hypos = [test_hypos[i] for i in indexes] test_labels = [test_labels[i] for i in indexes] #indexes = [] #for i, x in enumerate(test_hypos): # words = x.split() # if attack_surface.check_in(words): # indexes.append(i) #test_texts = [test_texts[i] for i in indexes] #test_labels = [test_labels[i] for i in indexes] from .config import config grad_guide = ForwardGradWrapper_pytorch_snli(dataset, config.word_max_len[dataset], model, device, tokenizer, test_bert, opt.bert_type) classes_prediction = [grad_guide.predict_classes(test_perm, test_hypo) for test_perm, test_hypo in zip(test_perms[: clean_samples_cap], test_hypos[: clean_samples_cap])] print(sum([classes_prediction[i]==np.argmax(test_labels[i]) for i in range(clean_samples_cap)])/clean_samples_cap) print('Crafting adversarial examples...') successful_perturbations = 0 failed_perturbations = 0 all_test_num =0 sub_rate_list = [] NE_rate_list = [] for index in range(opt.h_test_start, opt.h_test_start+clean_samples_cap, 1): text_p=test_perms[index] text_h=test_hypos[index] sub_rate = 0 NE_rate = 0 all_test_num+=1 print('_____{}______.'.format(index)) if np.argmax(test_labels[index]) == classes_prediction[index]: print('do') start_cpu = time.clock() # If the ground_true label is the same as the predicted label adv_doc_p, adv_doc_h, adv_y, sub_rate, NE_rate, change_tuple_list = adversarial_paraphrase_snli(opt, input_text_p=text_p, input_text_h=text_h, true_y=np.argmax(test_labels[index]), grad_guide=grad_guide, tokenizer=tokenizer, dataset=dataset, level='word') if adv_y != np.argmax(test_labels[index]): successful_perturbations += 1 print('{}. Successful example crafted.'.format(index)) else: failed_perturbations += 1 print('{}. Failure.'.format(index)) print("r acc", 1.0*failed_perturbations/all_test_num) sub_rate_list.append(sub_rate) NE_rate_list.append(NE_rate) end_cpu = time.clock() print('CPU second:', end_cpu - start_cpu) print("PWWS acc:", 1.0*failed_perturbations/all_test_num) #print('substitution:', sum(sub_rate_list)) #print('sum substitution:', len(sub_rate_list)) #print('NE rate:', sum(NE_rate_list)) #print('sum NE:', len(NE_rate_list)) #print("succ attack %d"%(successful_perturbations)) #print("fail attack %d"%(failed_perturbations))
[ "os.makedirs", "numpy.argmax", "modified_bert_tokenizer.ModifiedXLNetTokenizer.from_pretrained", "random.shuffle", "os.path.exists", "time.clock", "time.time", "modified_bert_tokenizer.ModifiedBertTokenizer.from_pretrained", "modified_bert_tokenizer.ModifiedRobertaTokenizer.from_pretrained", "mult...
[((2178, 2204), 'random.seed', 'random.seed', (['opt.rand_seed'], {}), '(opt.rand_seed)\n', (2189, 2204), False, 'import random\n'), ((2209, 2232), 'random.shuffle', 'random.shuffle', (['indexes'], {}), '(indexes)\n', (2223, 2232), False, 'import random\n'), ((3626, 3637), 'time.time', 'time.time', ([], {}), '()\n', (3635, 3637), False, 'import time\n'), ((6286, 6312), 'random.seed', 'random.seed', (['opt.rand_seed'], {}), '(opt.rand_seed)\n', (6297, 6312), False, 'import random\n'), ((6317, 6340), 'random.shuffle', 'random.shuffle', (['indexes'], {}), '(indexes)\n', (6331, 6340), False, 'import random\n'), ((9693, 9719), 'random.seed', 'random.seed', (['opt.rand_seed'], {}), '(opt.rand_seed)\n', (9704, 9719), False, 'import random\n'), ((9724, 9747), 'random.shuffle', 'random.shuffle', (['indexes'], {}), '(indexes)\n', (9738, 9747), False, 'import random\n'), ((13967, 13993), 'random.seed', 'random.seed', (['opt.rand_seed'], {}), '(opt.rand_seed)\n', (13978, 13993), False, 'import random\n'), ((13998, 14021), 'random.shuffle', 'random.shuffle', (['indexes'], {}), '(indexes)\n', (14012, 14021), False, 'import random\n'), ((3236, 3242), 'multiprocessing.Pipe', 'Pipe', ([], {}), '()\n', (3240, 3242), False, 'from multiprocessing import Process, Pipe\n'), ((3363, 3467), 'multiprocessing.Process', 'Process', ([], {'target': 'adversary.run', 'args': "(conn_p[i], wrapped_model, test_texts[i], test_labels[i], 'cpu')"}), "(target=adversary.run, args=(conn_p[i], wrapped_model, test_texts[i],\n test_labels[i], 'cpu'))\n", (3370, 3467), False, 'from multiprocessing import Process, Pipe\n'), ((10479, 10502), 'os.path.exists', 'os.path.exists', (['fa_path'], {}), '(fa_path)\n', (10493, 10502), False, 'import os\n'), ((10512, 10532), 'os.makedirs', 'os.makedirs', (['fa_path'], {}), '(fa_path)\n', (10523, 10532), False, 'import os\n'), ((1292, 1370), 'modified_bert_tokenizer.ModifiedBertTokenizer.from_pretrained', 'ModifiedBertTokenizer.from_pretrained', (['"""bert-base-uncased"""'], {'do_lower_case': '(True)'}), "('bert-base-uncased', do_lower_case=True)\n", (1329, 1370), False, 'from modified_bert_tokenizer import ModifiedBertTokenizer\n'), ((3656, 3719), 'torch.zeros', 'torch.zeros', (['bs', 'config.word_max_len[dataset]'], {'dtype': 'torch.long'}), '(bs, config.word_max_len[dataset], dtype=torch.long)\n', (3667, 3719), False, 'import torch\n'), ((3746, 3809), 'torch.zeros', 'torch.zeros', (['bs', 'config.word_max_len[dataset]'], {'dtype': 'torch.long'}), '(bs, config.word_max_len[dataset], dtype=torch.long)\n', (3757, 3809), False, 'import torch\n'), ((3846, 3909), 'torch.zeros', 'torch.zeros', (['bs', 'config.word_max_len[dataset]'], {'dtype': 'torch.long'}), '(bs, config.word_max_len[dataset], dtype=torch.long)\n', (3857, 3909), False, 'import torch\n'), ((4937, 4952), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (4950, 4952), False, 'import torch\n'), ((5302, 5313), 'time.time', 'time.time', ([], {}), '()\n', (5311, 5313), False, 'import time\n'), ((5628, 5706), 'modified_bert_tokenizer.ModifiedBertTokenizer.from_pretrained', 'ModifiedBertTokenizer.from_pretrained', (['"""bert-base-uncased"""'], {'do_lower_case': '(True)'}), "('bert-base-uncased', do_lower_case=True)\n", (5665, 5706), False, 'from modified_bert_tokenizer import ModifiedBertTokenizer\n'), ((7332, 7410), 'modified_bert_tokenizer.ModifiedBertTokenizer.from_pretrained', 'ModifiedBertTokenizer.from_pretrained', (['"""bert-base-uncased"""'], {'do_lower_case': '(True)'}), "('bert-base-uncased', do_lower_case=True)\n", (7369, 7410), False, 'from modified_bert_tokenizer import ModifiedBertTokenizer\n'), ((11034, 11063), 'numpy.argmax', 'np.argmax', (['test_labels[index]'], {}), '(test_labels[index])\n', (11043, 11063), True, 'import numpy as np\n'), ((11142, 11154), 'time.clock', 'time.clock', ([], {}), '()\n', (11152, 11154), False, 'import time\n'), ((12480, 12492), 'time.clock', 'time.clock', ([], {}), '()\n', (12490, 12492), False, 'import time\n'), ((13307, 13385), 'modified_bert_tokenizer.ModifiedBertTokenizer.from_pretrained', 'ModifiedBertTokenizer.from_pretrained', (['"""bert-base-uncased"""'], {'do_lower_case': '(True)'}), "('bert-base-uncased', do_lower_case=True)\n", (13344, 13385), False, 'from modified_bert_tokenizer import ModifiedBertTokenizer\n'), ((15357, 15386), 'numpy.argmax', 'np.argmax', (['test_labels[index]'], {}), '(test_labels[index])\n', (15366, 15386), True, 'import numpy as np\n'), ((15465, 15477), 'time.clock', 'time.clock', ([], {}), '()\n', (15475, 15477), False, 'import time\n'), ((16728, 16740), 'time.clock', 'time.clock', ([], {}), '()\n', (16738, 16740), False, 'import time\n'), ((1508, 1587), 'modified_bert_tokenizer.ModifiedRobertaTokenizer.from_pretrained', 'ModifiedRobertaTokenizer.from_pretrained', (['"""roberta-base"""'], {'add_prefix_space': '(True)'}), "('roberta-base', add_prefix_space=True)\n", (1548, 1587), False, 'from modified_bert_tokenizer import ModifiedRobertaTokenizer\n'), ((5844, 5923), 'modified_bert_tokenizer.ModifiedRobertaTokenizer.from_pretrained', 'ModifiedRobertaTokenizer.from_pretrained', (['"""roberta-base"""'], {'add_prefix_space': '(True)'}), "('roberta-base', add_prefix_space=True)\n", (5884, 5923), False, 'from modified_bert_tokenizer import ModifiedRobertaTokenizer\n'), ((7548, 7627), 'modified_bert_tokenizer.ModifiedRobertaTokenizer.from_pretrained', 'ModifiedRobertaTokenizer.from_pretrained', (['"""roberta-base"""'], {'add_prefix_space': '(True)'}), "('roberta-base', add_prefix_space=True)\n", (7588, 7627), False, 'from modified_bert_tokenizer import ModifiedRobertaTokenizer\n'), ((12018, 12047), 'numpy.argmax', 'np.argmax', (['test_labels[index]'], {}), '(test_labels[index])\n', (12027, 12047), True, 'import numpy as np\n'), ((13523, 13602), 'modified_bert_tokenizer.ModifiedRobertaTokenizer.from_pretrained', 'ModifiedRobertaTokenizer.from_pretrained', (['"""roberta-base"""'], {'add_prefix_space': '(True)'}), "('roberta-base', add_prefix_space=True)\n", (13563, 13602), False, 'from modified_bert_tokenizer import ModifiedRobertaTokenizer\n'), ((16294, 16323), 'numpy.argmax', 'np.argmax', (['test_labels[index]'], {}), '(test_labels[index])\n', (16303, 16323), True, 'import numpy as np\n'), ((1720, 1798), 'modified_bert_tokenizer.ModifiedXLNetTokenizer.from_pretrained', 'ModifiedXLNetTokenizer.from_pretrained', (['"""xlnet-base-cased"""'], {'do_lower_case': '(True)'}), "('xlnet-base-cased', do_lower_case=True)\n", (1758, 1798), False, 'from modified_bert_tokenizer import ModifiedXLNetTokenizer\n'), ((7760, 7838), 'modified_bert_tokenizer.ModifiedXLNetTokenizer.from_pretrained', 'ModifiedXLNetTokenizer.from_pretrained', (['"""xlnet-base-cased"""'], {'do_lower_case': '(True)'}), "('xlnet-base-cased', do_lower_case=True)\n", (7798, 7838), False, 'from modified_bert_tokenizer import ModifiedXLNetTokenizer\n'), ((11528, 11557), 'numpy.argmax', 'np.argmax', (['test_labels[index]'], {}), '(test_labels[index])\n', (11537, 11557), True, 'import numpy as np\n'), ((15804, 15833), 'numpy.argmax', 'np.argmax', (['test_labels[index]'], {}), '(test_labels[index])\n', (15813, 15833), True, 'import numpy as np\n'), ((10161, 10186), 'numpy.argmax', 'np.argmax', (['test_labels[i]'], {}), '(test_labels[i])\n', (10170, 10186), True, 'import numpy as np\n'), ((14829, 14854), 'numpy.argmax', 'np.argmax', (['test_labels[i]'], {}), '(test_labels[i])\n', (14838, 14854), True, 'import numpy as np\n')]
import helstrom import numpy as np import sys if __name__ == "__main__": ''' Change rho_0 and rho_1 here ''' rho0 = np.array([[1, 0], [0, 0]]) rho1 = np.array([[0.5, 0], [0, 0.5]]) if len(sys.argv) == 3: rho0 = np.matrix(sys.argv[1]) rho1 = np.matrix(sys.argv[2]) rho0 = np.asarray(rho0) rho1 = np.asarray(rho1) helstrom.sdp(rho0, rho1)
[ "numpy.matrix", "numpy.asarray", "numpy.array", "helstrom.sdp" ]
[((135, 161), 'numpy.array', 'np.array', (['[[1, 0], [0, 0]]'], {}), '([[1, 0], [0, 0]])\n', (143, 161), True, 'import numpy as np\n'), ((173, 203), 'numpy.array', 'np.array', (['[[0.5, 0], [0, 0.5]]'], {}), '([[0.5, 0], [0, 0.5]])\n', (181, 203), True, 'import numpy as np\n'), ((375, 399), 'helstrom.sdp', 'helstrom.sdp', (['rho0', 'rho1'], {}), '(rho0, rho1)\n', (387, 399), False, 'import helstrom\n'), ((246, 268), 'numpy.matrix', 'np.matrix', (['sys.argv[1]'], {}), '(sys.argv[1])\n', (255, 268), True, 'import numpy as np\n'), ((284, 306), 'numpy.matrix', 'np.matrix', (['sys.argv[2]'], {}), '(sys.argv[2])\n', (293, 306), True, 'import numpy as np\n'), ((322, 338), 'numpy.asarray', 'np.asarray', (['rho0'], {}), '(rho0)\n', (332, 338), True, 'import numpy as np\n'), ((354, 370), 'numpy.asarray', 'np.asarray', (['rho1'], {}), '(rho1)\n', (364, 370), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- # @Author: <NAME> # @Email: <EMAIL> # @Date: 2020-09-24 15:30:34 # @Last Modified by: <NAME> # @Last Modified time: 2021-03-23 00:36:39 import os import pickle import numpy as np from scipy.integrate import odeint import matplotlib.pyplot as plt from PySONIC.core import EffectiveVariablesLookup from ..utils import logger, timer, isWithin, si_format, rmse from ..neurons import passiveNeuron class SonicBenchmark: ''' Interface allowing to run benchmark simulations of a two-compartment model incorporating the SONIC paradigm, with a simplified sinusoidal capacitive drive. ''' npc = 100 # number of samples per cycle min_ncycles = 10 # minimum number of cycles per simulation varunits = { 't': 'ms', 'Cm': 'uF/cm2', 'Vm': 'mV', 'Qm': 'nC/cm2' } varfactors = { 't': 1e3, 'Cm': 1e2, 'Vm': 1e0, 'Qm': 1e5 } nodelabels = ['node 1', 'node 2'] ga_bounds = [1e-10, 1e10] # S/m2 def __init__(self, pneuron, ga, Fdrive, gammas, passive=False): ''' Initialization. :param pneuron: point-neuron object :param ga: axial conductance (S/m2) :param Fdrive: US frequency (Hz) :param gammas: pair of relative capacitance oscillation ranges ''' self.pneuron = pneuron self.ga = ga self.Fdrive = Fdrive self.gammas = gammas self.passive = passive self.computeLookups() def copy(self): return self.__class__(self.pneuron, self.ga, self.Fdrive, self.gammas, passive=self.passive) @property def gammalist(self): return [f'{x:.2f}' for x in self.gammas] @property def gammastr(self): return f"({', '.join(self.gammalist)})" @property def fstr(self): return f'{si_format(self.Fdrive)}Hz' @property def gastr(self): return f'{self.ga:.2e} S/m2' @property def mechstr(self): dynamics = 'passive ' if self.passive else '' return f'{dynamics}{self.pneuron.name}' def __repr__(self): params = [ f'ga = {self.gastr}', f'f = {self.fstr}', f'gamma = {self.gammastr}' ] return f'{self.__class__.__name__}({self.mechstr} dynamics, {", ".join(params)})' @property def corecode(self): s = self.__repr__() for c in [' = ', ', ', ' ', '(', '/']: s = s.replace(c, '_') s = s.replace('))', '').replace('__', '_') return s @property def pneuron(self): return self._pneuron @pneuron.setter def pneuron(self, value): self._pneuron = value.copy() self.states = self._pneuron.statesNames() if hasattr(self, 'lkps'): self.computeLookups() def isPassive(self): return self.pneuron.name.startswith('pas_') @property def Fdrive(self): return self._Fdrive @Fdrive.setter def Fdrive(self, value): self._Fdrive = value if hasattr(self, 'lkps'): self.computeLookups() @property def gammas(self): return self._gammas @gammas.setter def gammas(self, value): self._gammas = value if hasattr(self, 'lkps'): self.computeLookups() @property def passive(self): return self._passive @passive.setter def passive(self, value): assert isinstance(value, bool), 'passive must be boolean typed' self._passive = value if hasattr(self, 'lkps'): self.computeLookups() @property def ga(self): return self._ga @ga.setter def ga(self, value): if value != 0.: assert isWithin('ga', value, self.ga_bounds) self._ga = value @property def gPas(self): ''' Passive membrane conductance (S/m2). ''' return self.pneuron.gLeak @property def Cm0(self): ''' Resting capacitance (F/m2). ''' return self.pneuron.Cm0 @property def Vm0(self): ''' Resting membrane potential (mV). ''' return self.pneuron.Vm0 @property def Qm0(self): ''' Resting membrane charge density (C/m2). ''' return self.Vm0 * self.Cm0 * 1e-3 @property def Qref(self): ''' Reference charge linear space. ''' return np.arange(*self.pneuron.Qbounds, 1e-5) # C/cm2 @property def Cmeff(self): ''' Analytical solution for effective membrane capacitance (F/m2). ''' return self.Cm0 * np.sqrt(1 - np.array(self.gammas)**2 / 4) @property def Qminf(self): ''' Analytical solution for steady-state charge density (C/m2). ''' return self.Cmeff * self.pneuron.ELeak * 1e-3 def capct(self, gamma, t): ''' Time-varying sinusoidal capacitance (in F/m2) ''' return self.Cm0 * (1 + 0.5 * gamma * np.sin(2 * np.pi * self.Fdrive * t)) def vCapct(self, t): ''' Vector of time-varying capacitance (in F/m2) ''' return np.array([self.capct(gamma, t) for gamma in self.gammas]) def getLookup(self, Cm): ''' Get a lookup object of effective variables for a given capacitance cycle vector. ''' refs = {'Q': self.Qref} # C/m2 Vmarray = np.array([Q / Cm for Q in self.Qref]) * 1e3 # mV tables = { k: np.array([np.mean(np.vectorize(v)(Vmvec)) for Vmvec in Vmarray]) for k, v in self.pneuron.effRates().items() } return EffectiveVariablesLookup(refs, tables) @property def tcycle(self): ''' Time vector over 1 acoustic cycle (s). ''' return np.linspace(0, 1 / self.Fdrive, self.npc) @property def dt_full(self): ''' Full time step (s). ''' return 1 / (self.npc * self.Fdrive) @property def dt_sparse(self): ''' Sparse time step (s). ''' return 1 / self.Fdrive def computeLookups(self): ''' Compute benchmark lookups. ''' self.lkps = [] if not self.passive: self.lkps = [self.getLookup(Cm_cycle) for Cm_cycle in self.vCapct(self.tcycle)] def getCmeff(self, Cm_cycle): ''' Compute effective capacitance from capacitance profile over 1 cycle. ''' return 1 / np.mean(1 / Cm_cycle) # F/m2 def iax(self, Vm, Vmother): ''' Compute axial current flowing in the compartment from another compartment (in mA/m2). [iax] = S/m2 * mV = 1e-3 A/m2 = 1 mA/m2 ''' return self.ga * (Vmother - Vm) def vIax(self, Vm): ''' Compute array of axial currents in each compartment based on array of potentials. ''' return np.array([self.iax(*Vm), self.iax(*Vm[::-1])]) # mA/m2 def serialize(self, y): ''' Serialize a single state vector into a state-per-node matrix. ''' return np.reshape(y.copy(), (self.npernode * 2)) def deserialize(self, y): ''' Deserialize a state per node matrix into a single state vector. ''' return np.reshape(y.copy(), (2, self.npernode)) def derivatives(self, t, y, Cm, dstates_func): ''' Generic derivatives method. ''' # Deserialize states vector and initialize derivatives array y = self.deserialize(y) dydt = np.empty(y.shape) # Extract charge density and membrane potential vectors Qm = y[:, 0] # C/m2 Vm = y[:, 0] / Cm * 1e3 # mV # Extract states array states_array = y[:, 1:] # Compute membrane dynamics for each node for i, (qm, vm, states) in enumerate(zip(Qm, Vm, states_array)): # If passive, compute only leakage current if self.passive: im = self.pneuron.iLeak(vm) # mA/m2 # Otherwise, compute states derivatives and total membrane current if not self.passive: states_dict = dict(zip(self.states, states)) dydt[i, 1:] = dstates_func(i, qm, vm, states_dict) # s-1 im = self.pneuron.iNet(vm, states_dict) # mA/m2 dydt[i, 0] = -im # mA/m2 # Add axial currents to currents column dydt[:, 0] += self.vIax(Vm) # mA/m2 # Rescale currents column into charge derivative units dydt[:, 0] *= 1e-3 # C/m2.s # Return serialized derivatives vector return self.serialize(dydt) def dstatesFull(self, i, qm, vm, states): ''' Compute detailed states derivatives. ''' return self.pneuron.getDerStates(vm, states) def dfull(self, t, y): ''' Compute detailed derivatives vector. ''' return self.derivatives(t, y, self.vCapct(t), self.dstatesFull) def dstatesEff(self, i, qm, vm, states): ''' Compute effective states derivatives. ''' lkp0d = self.lkps[i].interpolate1D(qm) return np.array([self.pneuron.derEffStates()[k](lkp0d, states) for k in self.states]) def deff(self, t, y): ''' Compute effective derivatives vector. ''' return self.derivatives(t, y, self.Cmeff, self.dstatesEff) @property def y0node(self): ''' Get initial conditions vector (common to every node). ''' if self.passive: return [self.Qm0] else: return [self.Qm0, *[self.pneuron.steadyStates()[k](self.Vm0) for k in self.states]] @property def y0(self): ''' Get full initial conditions vector (duplicated ynode vector). ''' self.npernode = len(self.y0node) return self.y0node + self.y0node def integrate(self, dfunc, t): ''' Integrate over a time vector and return charge density arrays. ''' # Integrate system tolerances = {'atol': 1e-10} y = odeint(dfunc, self.y0, t, tfirst=True, **tolerances).T # Cast each solution variable as a time-per-node matrix sol = {'Qm': y[::self.npernode]} if not self.passive: for i, k in enumerate(self.states): sol[k] = y[i + 1::self.npernode] # Return recast solution dictionary return sol def orderedKeys(self, varkeys): ''' Get ordered list of solution keys. ''' mainkeys = ['Qm', 'Vm', 'Cm'] otherkeys = list(set(varkeys) - set(mainkeys)) return mainkeys + otherkeys def orderedSol(self, sol): ''' Re-order solution according to keys list. ''' return {k: sol[k] for k in self.orderedKeys(sol.keys())} def nsamples(self, tstop): ''' Compute the number of samples required to integrate over a given time interval. ''' return self.getNCycles(tstop) * self.npc @timer def simFull(self, tstop): ''' Simulate the full system until a specific stop time. ''' t = np.linspace(0, tstop, self.nsamples(tstop)) sol = self.integrate(self.dfull, t) sol['Cm'] = self.vCapct(t) sol['Vm'] = sol['Qm'] / sol['Cm'] * 1e3 return t, self.orderedSol(sol) @timer def simEff(self, tstop): ''' Simulate the effective system until a specific stop time. ''' t = np.linspace(0, tstop, self.getNCycles(tstop)) sol = self.integrate(self.deff, t) sol['Cm'] = np.array([np.ones(t.size) * Cmeff for Cmeff in self.Cmeff]) sol['Vm'] = sol['Qm'] / sol['Cm'] * 1e3 return t, self.orderedSol(sol) @property def methods(self): ''' Dictionary of simulation methods. ''' return {'full': self.simFull, 'effective': self.simEff} def getNCycles(self, duration): ''' Compute number of cycles from a duration. ''' return int(np.ceil(duration * self.Fdrive)) def simulate(self, mtype, tstop): ''' Simulate the system with a specific method for a given duration. ''' # Cast tstop as a multiple of the acoustic period tstop = self.getNCycles(tstop) / self.Fdrive # s # Retrieve simulation method try: method = self.methods[mtype] except KeyError: raise ValueError(f'"{mtype}" is not a valid method type') # Run simulation and return output logger.debug(f'running {mtype} {si_format(tstop, 2)}s simulation') output, tcomp = method(tstop) logger.debug(f'completed in {tcomp:.2f} s') return output def cycleAvg(self, y): ''' Cycle-average a solution vector according to the number of samples per cycle. ''' ypercycle = np.reshape(y, (int(y.shape[0] / self.npc), self.npc)) return np.mean(ypercycle, axis=1) def cycleAvgSol(self, t, sol): ''' Cycle-average a time vector and a solution dictionary. ''' solavg = {} # For each per-node-matrix in the solution for k, ymat in sol.items(): # Cycle-average each node vector of the matrix solavg[k] = np.array([self.cycleAvg(yvec) for yvec in ymat]) # Re-sample time vector at system periodicity tavg = t[::self.npc] # + 0.5 / self.Fdrive # Return cycle-averaged time vector and solution dictionary return tavg, solavg def g2tau(self, g): ''' Convert conductance per unit membrane area (S/m2) to time constant (s). ''' return self.Cm0 / g # s def tau2g(self, tau): ''' Convert time constant (s) to conductance per unit membrane area (S/m2). ''' return self.Cm0 / tau # s @property def taum(self): ''' Passive membrane time constant (s). ''' return self.pneuron.tau_pas @taum.setter def taum(self, value): ''' Update point-neuron leakage conductance to match time new membrane time constant. ''' if not self.isPassive(): raise ValueError('taum can only be set for passive neurons') self.pneuron = passiveNeuron( self.pneuron.Cm0, self.tau2g(value), # S/m2 self.pneuron.ELeak) @property def tauax(self): ''' Axial time constant (s). ''' return self.g2tau(self.ga) @tauax.setter def tauax(self, value): ''' Update axial conductance per unit area to match time new axial time constant. ''' self.ga = self.tau2g(value) # S/m2 @property def taumax(self): ''' Maximal time constant of the model (s). ''' return max(self.taum, self.tauax) def setTimeConstants(self, taum, tauax): ''' Update benchmark according to pair of time constants (in s). ''' self.taum = taum # s self.tauax = tauax # s def setDrive(self, f, gammas): ''' Update benchmark drive to a new frequency and amplitude. ''' self.Fdrive = f self.gammas = gammas def getPassiveTstop(self, f): ''' Compute minimum simulation time for a passive model (s). ''' return max(5 * self.taumax, self.min_ncycles / f) @property def passive_tstop(self): return self.getPassiveTstop(self.Fdrive) def simAllMethods(self, tstop): ''' Simulate the model with both methods. ''' logger.info(f'{self}: {si_format(tstop)}s simulation') # Simulate with full and effective systems t, sol = {}, {} for method in self.methods.keys(): t[method], sol[method] = self.simulate(method, tstop) t, sol = self.postproSol(t, sol) return t, sol def simAndSave(self, *args, outdir=''): fpath = os.path.join(outdir, self.corecode) if os.path.isfile(fpath): with open(fpath, 'rb') as fh: out = pickle.load(fh) else: out = self.simAllMethods(*args) with open(fpath, 'wb') as fh: pickle.dump(out, fh) return out def computeGradient(self, sol): ''' compute the gradient of a solution array. ''' return {k: np.vstack((y, np.diff(y, axis=0))) for k, y in sol.items()} def addOnset(self, ymat, y0): return np.hstack((np.ones((2, 2)) * y0, ymat)) def getY0(self, k, y): y0dict = {'Cm': self.Cm0, 'Qm': self.Qm0, 'Vm': self.Vm0} try: return y0dict[k] except KeyError: return y[0, 0] return def postproSol(self, t, sol, gradient=False): ''' Post-process solution. ''' # Add cycle-average of full solution t['cycle-avg'], sol['cycle-avg'] = self.cycleAvgSol(t['full'], sol['full']) keys = list(sol.keys()) tonset = 0.05 * np.ptp(t['full']) # Add onset for k in keys: t[k] = np.hstack(([-tonset, 0], t[k])) sol[k] = {vk: self.addOnset(ymat, self.getY0(vk, ymat)) for vk, ymat in sol[k].items()} # Add gradient across nodes for each variable if gradient: for k in keys: t[f'{k}-grad'] = t[k] sol[f'{k}-grad'] = self.computeGradient(sol[k]) return t, sol def plot(self, t, sol, Qonly=False, gradient=False): ''' Plot results of benchmark simulations of the model. ''' colors = ['C0', 'C1', 'darkgrey'] markers = ['-', '--', '-'] alphas = [0.5, 1., 1.] # Reduce solution dictionary if only Q needs to be plotted if Qonly: sol = {key: {'Qm': value['Qm']} for key, value in sol.items()} # Extract simulation duration tstop = t[list(t.keys())[0]][-1] # s # Gather keys of methods and variables to plot mkeys = list(sol.keys()) varkeys = list(sol[mkeys[0]].keys()) naxes = len(varkeys) # Get node labels lbls = self.nodelabels # Create figure fig, axes = plt.subplots(naxes, 1, sharex=True, figsize=(10, min(3 * naxes, 10))) if naxes == 1: axes = [axes] axes[0].set_title(f'{self} - {si_format(tstop)}s simulation') axes[-1].set_xlabel(f'time ({self.varunits["t"]})') for ax, vk in zip(axes, varkeys): ax.set_ylabel(f'{vk} ({self.varunits.get(vk, "-")})') if self.passive: # Add horizontal lines for node-specific SONIC steady-states on charge density plot Qm_ax = axes[varkeys.index('Qm')] for Qm, c in zip(self.Qminf, colors): Qm_ax.axhline(Qm * self.varfactors['Qm'], c=c, linestyle=':') # For each solution type for m, alpha, (mkey, varsdict) in zip(markers, alphas, sol.items()): tplt = t[mkey] * self.varfactors['t'] # For each solution variable for ax, (vkey, v) in zip(axes, varsdict.items()): # For each node for y, c, lbl in zip(v, colors, lbls): # Plot node variable with appropriate color and marker ax.plot(tplt, y * self.varfactors.get(vkey, 1.0), m, alpha=alpha, c=c, label=f'{lbl} - {mkey}') # Add legend fig.subplots_adjust(bottom=0.2) axes[-1].legend( bbox_to_anchor=(0., -0.7, 1., .1), loc='upper center', ncol=3, mode="expand", borderaxespad=0.) # Return figure return fig def plotQnorm(self, t, sol, ax=None, notitle=False): ''' Plot normalized charge density traces from benchmark simulations of the model. ''' colors = ['C0', 'C1'] markers = ['-', '--', '-'] alphas = [0.5, 1., 1.] V = {key: value['Qm'] / self.Cm0 for key, value in sol.items()} tstop = t[list(t.keys())[0]][-1] # s if ax is None: fig, ax = plt.subplots(figsize=(10, 3)) else: fig = ax.get_figure() if not notitle: ax.set_title(f'{self} - {si_format(tstop)}s simulation') ax.set_xlabel(f'time ({self.varunits["t"]})') ax.set_ylabel(f'Qm / Cm0 (mV)') for sk in ['top', 'right']: ax.spines[sk].set_visible(False) ax.set_ylim(-85., 55.) for m, alpha, (key, varsdict) in zip(markers, alphas, sol.items()): for y, c, lbl in zip(V[key], colors, self.nodelabels): ax.plot(t[key] * self.varfactors['t'], y * 1e3, m, alpha=alpha, c=c, label=f'{lbl} - {key}') # fig.subplots_adjust(bottom=0.2) # ax.legend(bbox_to_anchor=(0., -0.7, 1., .1), loc='upper center', ncol=3, # mode="expand", borderaxespad=0.) return fig def simplot(self, *args, **kwargs): ''' Run benchmark simulation and plot results. ''' return self.plot(*self.simAllMethods(*args, **kwargs)) @property def eval_funcs(self): ''' Different functions to evaluate the divergence between two solutions. ''' return { 'rmse': lambda y1, y2: rmse(y1, y2), # RMSE 'ss': lambda y1, y2: np.abs(y1[-1] - y2[-1]), # steady-state absolute difference 'amax': lambda y1, y2: np.max(np.abs(y1 - y2)) # max absolute difference } def divergencePerNode(self, t, sol, eval_mode='RMSE'): ''' Evaluate the divergence between the effective and full, cycle-averaged solutions at a specific point in time, computing per-node differences in charge density values divided by resting capacitance. ''' if eval_mode not in self.eval_funcs.keys(): raise ValueError(f'{eval_mode} evaluation mode is not supported') # Extract charge matrices from solution dictionary Qsol = {k: sol[k]['Qm'] for k in ['effective', 'cycle-avg']} # C/m2 # Normalize matrices by resting capacitance Qnorm = {k: v / self.Cm0 * 1e3 for k, v in Qsol.items()} # mV # Keep only the first two rows (3rd one, if any, is a gradient) Qnorm = {k: v[:2, :] for k, v in Qnorm.items()} # Discard the first 3 columns (artifical onset and first cycle artefact) Qnorm = {k: v[:, 3:] for k, v in Qnorm.items()} eval_func = self.eval_funcs[eval_mode] # Compute deviation across nodes saccording to evaluation mode div_per_node = [eval_func(*[v[i] for v in Qnorm.values()]) for i in range(2)] # Cast into dictionary and return div_per_node = dict(zip(self.nodelabels, div_per_node)) logger.debug(f'divergence per node: ', {k: f'{v:.2e} mV' for k, v in div_per_node.items()}) return div_per_node def divergence(self, *args, **kwargs): div_per_node = self.divergencePerNode(*args, **kwargs) # mV return max(list(div_per_node.values())) # mV def logDivergences(self, t, sol): for eval_mode in self.eval_funcs.keys(): div_per_node = self.divergencePerNode(t, sol, eval_mode=eval_mode) div_per_node_str = {k: f'{v:.3f}' for k, v in div_per_node.items()} logger.info(f'{eval_mode}: divergence = {div_per_node_str} mV') def phaseplotQnorm(self, t, sol): ''' Phase-plot normalized charge density traces from benchmark simulations of the model. ''' colors = ['C0', 'C1'] markers = ['-', '--', '-'] alphas = [0.5, 1., 1.] # Extract normalized charge density profiles Qnorm = {key: value['Qm'] / self.Cm0 for key, value in sol.items()} # Discard the first 2 indexes of artifical onset) t = {k: v[2:] for k, v in t.items()} Qnorm = {k: v[:, 2:] for k, v in Qnorm.items()} # Get time derivatives dQnorm = {} for key, value in Qnorm.items(): dQdt = np.diff(value, axis=1) / np.diff(t[key]) dQnorm[key] = np.hstack((np.array([dQdt[:, 0]]).T, dQdt)) fig, ax = plt.subplots(figsize=(5, 5), constrained_layout=True) # tstop = t[list(t.keys())[0]][-1] # s # ax.set_title(f'{self} - {si_format(tstop)}s simulation', fontsize=10) ax.set_xlabel(f'Qm / Cm0 (mV)') ax.set_ylabel(f'd(Qm / Cm0) / dt (V/s)') xfactor, yfactor = 1e3, 1e0 x0 = self.pneuron.Qm0 / self.pneuron.Cm0 y0 = 0. for m, alpha, (key, varsdict) in zip(markers, alphas, sol.items()): if key != 'full': for y, dydt, c, lbl in zip(Qnorm[key], dQnorm[key], colors, self.nodelabels): ax.plot(np.hstack(([x0], y)) * xfactor, np.hstack(([y0], dydt)) * yfactor, m, alpha=alpha, c=c, label=f'{lbl} - {key}') ax.scatter(x0 * xfactor, y0 * yfactor, c=['k'], zorder=2.5) # fig.subplots_adjust(bottom=0.2) # ax.legend(bbox_to_anchor=(0., -0.7, 1., .1), loc='upper center', ncol=3, # mode="expand", borderaxespad=0.) return fig
[ "pickle.dump", "numpy.abs", "numpy.empty", "numpy.ones", "PySONIC.core.EffectiveVariablesLookup", "os.path.isfile", "numpy.mean", "numpy.arange", "pickle.load", "numpy.sin", "os.path.join", "scipy.integrate.odeint", "numpy.linspace", "matplotlib.pyplot.subplots", "numpy.vectorize", "nu...
[((4422, 4461), 'numpy.arange', 'np.arange', (['*self.pneuron.Qbounds', '(1e-05)'], {}), '(*self.pneuron.Qbounds, 1e-05)\n', (4431, 4461), True, 'import numpy as np\n'), ((5570, 5608), 'PySONIC.core.EffectiveVariablesLookup', 'EffectiveVariablesLookup', (['refs', 'tables'], {}), '(refs, tables)\n', (5594, 5608), False, 'from PySONIC.core import EffectiveVariablesLookup\n'), ((5716, 5757), 'numpy.linspace', 'np.linspace', (['(0)', '(1 / self.Fdrive)', 'self.npc'], {}), '(0, 1 / self.Fdrive, self.npc)\n', (5727, 5757), True, 'import numpy as np\n'), ((7345, 7362), 'numpy.empty', 'np.empty', (['y.shape'], {}), '(y.shape)\n', (7353, 7362), True, 'import numpy as np\n'), ((12580, 12606), 'numpy.mean', 'np.mean', (['ypercycle'], {'axis': '(1)'}), '(ypercycle, axis=1)\n', (12587, 12606), True, 'import numpy as np\n'), ((15464, 15499), 'os.path.join', 'os.path.join', (['outdir', 'self.corecode'], {}), '(outdir, self.corecode)\n', (15476, 15499), False, 'import os\n'), ((15511, 15532), 'os.path.isfile', 'os.path.isfile', (['fpath'], {}), '(fpath)\n', (15525, 15532), False, 'import os\n'), ((23678, 23731), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(5, 5)', 'constrained_layout': '(True)'}), '(figsize=(5, 5), constrained_layout=True)\n', (23690, 23731), True, 'import matplotlib.pyplot as plt\n'), ((5340, 5379), 'numpy.array', 'np.array', (['[(Q / Cm) for Q in self.Qref]'], {}), '([(Q / Cm) for Q in self.Qref])\n', (5348, 5379), True, 'import numpy as np\n'), ((6342, 6363), 'numpy.mean', 'np.mean', (['(1 / Cm_cycle)'], {}), '(1 / Cm_cycle)\n', (6349, 6363), True, 'import numpy as np\n'), ((9800, 9852), 'scipy.integrate.odeint', 'odeint', (['dfunc', 'self.y0', 't'], {'tfirst': '(True)'}), '(dfunc, self.y0, t, tfirst=True, **tolerances)\n', (9806, 9852), False, 'from scipy.integrate import odeint\n'), ((11682, 11713), 'numpy.ceil', 'np.ceil', (['(duration * self.Fdrive)'], {}), '(duration * self.Fdrive)\n', (11689, 11713), True, 'import numpy as np\n'), ((16513, 16530), 'numpy.ptp', 'np.ptp', (["t['full']"], {}), "(t['full'])\n", (16519, 16530), True, 'import numpy as np\n'), ((16593, 16624), 'numpy.hstack', 'np.hstack', (['([-tonset, 0], t[k])'], {}), '(([-tonset, 0], t[k]))\n', (16602, 16624), True, 'import numpy as np\n'), ((19585, 19614), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(10, 3)'}), '(figsize=(10, 3))\n', (19597, 19614), True, 'import matplotlib.pyplot as plt\n'), ((15598, 15613), 'pickle.load', 'pickle.load', (['fh'], {}), '(fh)\n', (15609, 15613), False, 'import pickle\n'), ((15730, 15750), 'pickle.dump', 'pickle.dump', (['out', 'fh'], {}), '(out, fh)\n', (15741, 15750), False, 'import pickle\n'), ((20842, 20865), 'numpy.abs', 'np.abs', (['(y1[-1] - y2[-1])'], {}), '(y1[-1] - y2[-1])\n', (20848, 20865), True, 'import numpy as np\n'), ((23548, 23570), 'numpy.diff', 'np.diff', (['value'], {'axis': '(1)'}), '(value, axis=1)\n', (23555, 23570), True, 'import numpy as np\n'), ((23573, 23588), 'numpy.diff', 'np.diff', (['t[key]'], {}), '(t[key])\n', (23580, 23588), True, 'import numpy as np\n'), ((4958, 4993), 'numpy.sin', 'np.sin', (['(2 * np.pi * self.Fdrive * t)'], {}), '(2 * np.pi * self.Fdrive * t)\n', (4964, 4993), True, 'import numpy as np\n'), ((11279, 11294), 'numpy.ones', 'np.ones', (['t.size'], {}), '(t.size)\n', (11286, 11294), True, 'import numpy as np\n'), ((15898, 15916), 'numpy.diff', 'np.diff', (['y'], {'axis': '(0)'}), '(y, axis=0)\n', (15905, 15916), True, 'import numpy as np\n'), ((16005, 16020), 'numpy.ones', 'np.ones', (['(2, 2)'], {}), '((2, 2))\n', (16012, 16020), True, 'import numpy as np\n'), ((20946, 20961), 'numpy.abs', 'np.abs', (['(y1 - y2)'], {}), '(y1 - y2)\n', (20952, 20961), True, 'import numpy as np\n'), ((23626, 23648), 'numpy.array', 'np.array', (['[dQdt[:, 0]]'], {}), '([dQdt[:, 0]])\n', (23634, 23648), True, 'import numpy as np\n'), ((4623, 4644), 'numpy.array', 'np.array', (['self.gammas'], {}), '(self.gammas)\n', (4631, 4644), True, 'import numpy as np\n'), ((5442, 5457), 'numpy.vectorize', 'np.vectorize', (['v'], {}), '(v)\n', (5454, 5457), True, 'import numpy as np\n'), ((24278, 24298), 'numpy.hstack', 'np.hstack', (['([x0], y)'], {}), '(([x0], y))\n', (24287, 24298), True, 'import numpy as np\n'), ((24310, 24333), 'numpy.hstack', 'np.hstack', (['([y0], dydt)'], {}), '(([y0], dydt))\n', (24319, 24333), True, 'import numpy as np\n')]
#!/usr/bin/env python # coding=utf-8 """ Showcasing data inspection This example script needs PIL (Pillow package) to load images from disk. """ import os import sys import numpy as np # Extend the python path sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')) from iminspect.inspector import inspect, DataType from vito import imutils from vito import flowutils if __name__ == "__main__": # If the user wants to load an image from disk: inspect(None) # Inspect a boolean mask mask = imutils.imread('space-invader.png', mode='L').astype(np.bool) inspect(mask) # Create exemplary label images cats1 = np.row_stack((np.arange(5), np.arange(5), np.arange(5), np.arange(5))).astype(np.int16) cats2 = np.row_stack((np.arange(5), np.arange(5), np.arange(5), np.arange(5))).astype(np.int16) cats2[2, :] = -42 # Category with an existing label (but non-sequential category value in contrast to the other categories) cats1[0, 1:-1] = 75 # Inject category without an existing label in both examples cats2[3, 1:-1] = 75 labels = {0: 'car', 1: 'van', 2: 'truck', 3: 'bike', 4: 'person', 5: 'tree', -42: 'road'} print('You should scale these tiny images up, press Ctrl+F !!') inspect( (cats1, cats2), data_type=DataType.CATEGORICAL, categorical_labels=labels) # Exemplary weight matrix weights = imutils.imread('peaks.png', mode='L') # Show as float data type, data range [-0.5, 0.5] weights_f32 = weights.astype(np.float32) / 255.0 - 0.5 _, display_settings = inspect(weights_f32) # Inspect an image with 11 labels. cats = (weights / 25).astype(np.int16) - 5 _, display_settings = inspect( cats, data_type=DataType.CATEGORICAL) # Inspect a depth image depth = imutils.imread('depth.png') inspect(depth) # Inspect optical flow flow = flowutils.floread('color_wheel.flo') inspect(flow) # Visualize standard RGB image rgb = imutils.imread('flamingo.jpg') inspect(rgb, label='Demo RGB [{}]'.format(rgb.dtype)) # # Inspect RGBA image # rgb = imutils.imread('flamingo-alpha.png') # inspect(rgb, label='Demo RGBA [{}]'.format(rgb.dtype))
[ "os.path.abspath", "vito.imutils.imread", "numpy.arange", "vito.flowutils.floread", "iminspect.inspector.inspect" ]
[((481, 494), 'iminspect.inspector.inspect', 'inspect', (['None'], {}), '(None)\n', (488, 494), False, 'from iminspect.inspector import inspect, DataType\n'), ((601, 614), 'iminspect.inspector.inspect', 'inspect', (['mask'], {}), '(mask)\n', (608, 614), False, 'from iminspect.inspector import inspect, DataType\n'), ((1257, 1344), 'iminspect.inspector.inspect', 'inspect', (['(cats1, cats2)'], {'data_type': 'DataType.CATEGORICAL', 'categorical_labels': 'labels'}), '((cats1, cats2), data_type=DataType.CATEGORICAL, categorical_labels=\n labels)\n', (1264, 1344), False, 'from iminspect.inspector import inspect, DataType\n'), ((1410, 1447), 'vito.imutils.imread', 'imutils.imread', (['"""peaks.png"""'], {'mode': '"""L"""'}), "('peaks.png', mode='L')\n", (1424, 1447), False, 'from vito import imutils\n'), ((1587, 1607), 'iminspect.inspector.inspect', 'inspect', (['weights_f32'], {}), '(weights_f32)\n', (1594, 1607), False, 'from iminspect.inspector import inspect, DataType\n'), ((1721, 1766), 'iminspect.inspector.inspect', 'inspect', (['cats'], {'data_type': 'DataType.CATEGORICAL'}), '(cats, data_type=DataType.CATEGORICAL)\n', (1728, 1766), False, 'from iminspect.inspector import inspect, DataType\n'), ((1825, 1852), 'vito.imutils.imread', 'imutils.imread', (['"""depth.png"""'], {}), "('depth.png')\n", (1839, 1852), False, 'from vito import imutils\n'), ((1857, 1871), 'iminspect.inspector.inspect', 'inspect', (['depth'], {}), '(depth)\n', (1864, 1871), False, 'from iminspect.inspector import inspect, DataType\n'), ((1911, 1947), 'vito.flowutils.floread', 'flowutils.floread', (['"""color_wheel.flo"""'], {}), "('color_wheel.flo')\n", (1928, 1947), False, 'from vito import flowutils\n'), ((1952, 1965), 'iminspect.inspector.inspect', 'inspect', (['flow'], {}), '(flow)\n', (1959, 1965), False, 'from iminspect.inspector import inspect, DataType\n'), ((2012, 2042), 'vito.imutils.imread', 'imutils.imread', (['"""flamingo.jpg"""'], {}), "('flamingo.jpg')\n", (2026, 2042), False, 'from vito import imutils\n'), ((259, 284), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (274, 284), False, 'import os\n'), ((535, 580), 'vito.imutils.imread', 'imutils.imread', (['"""space-invader.png"""'], {'mode': '"""L"""'}), "('space-invader.png', mode='L')\n", (549, 580), False, 'from vito import imutils\n'), ((678, 690), 'numpy.arange', 'np.arange', (['(5)'], {}), '(5)\n', (687, 690), True, 'import numpy as np\n'), ((692, 704), 'numpy.arange', 'np.arange', (['(5)'], {}), '(5)\n', (701, 704), True, 'import numpy as np\n'), ((706, 718), 'numpy.arange', 'np.arange', (['(5)'], {}), '(5)\n', (715, 718), True, 'import numpy as np\n'), ((720, 732), 'numpy.arange', 'np.arange', (['(5)'], {}), '(5)\n', (729, 732), True, 'import numpy as np\n'), ((778, 790), 'numpy.arange', 'np.arange', (['(5)'], {}), '(5)\n', (787, 790), True, 'import numpy as np\n'), ((792, 804), 'numpy.arange', 'np.arange', (['(5)'], {}), '(5)\n', (801, 804), True, 'import numpy as np\n'), ((806, 818), 'numpy.arange', 'np.arange', (['(5)'], {}), '(5)\n', (815, 818), True, 'import numpy as np\n'), ((820, 832), 'numpy.arange', 'np.arange', (['(5)'], {}), '(5)\n', (829, 832), True, 'import numpy as np\n')]
"""Functions for mapping between geo regions.""" # -*- coding: utf-8 -*- import numpy as np import pandas as pd from delphi_utils import GeoMapper from .constants import METRICS, COMBINED_METRIC gmpr = GeoMapper() def generate_transition_matrix(geo_res): """ Generate transition matrix from county to msa/hrr. Parameters ---------- geo_res: str "msa" or "hrr" Returns ------- pd.DataFrame columns "geo_id", "timestamp", and "val". The first is a data frame for HRR regions and the second are MSA regions. """ map_df = gmpr._load_crosswalk("fips", geo_res) # pylint: disable=protected-access # Add population as weights map_df = gmpr.add_population_column(map_df, "fips") if geo_res == "hrr": map_df["population"] = map_df["population"] * map_df["weight"] msa_pop = map_df.groupby(geo_res).sum().reset_index() map_df = map_df.merge( msa_pop, on=geo_res, how="inner", suffixes=["_raw", "_groupsum"] ) map_df["weight"] = map_df["population_raw"] / map_df["population_groupsum"] map_df = pd.pivot_table( map_df, values='weight', index=["fips"], columns=[geo_res] ).fillna(0).reset_index().rename({"fips": "geo_id"}, axis = 1) return map_df def geo_map(df, geo_res): """ Compute derived HRR and MSA counts as a weighted sum of the county dataset. Parameters ---------- df: pd.DataFrame a data frame with columns "geo_id", "timestamp", and columns for signal vals geo_res: str "msa" or "hrr" Returns ------- pd.DataFrame A dataframe with columns "geo_id", "timestamp", and columns for signal vals. The geo_id has been converted from fips to HRRs/MSAs """ if geo_res in set(["county", "state"]): return df map_df = generate_transition_matrix(geo_res) converted_df = pd.DataFrame(columns = df.columns) for _date in df["timestamp"].unique(): val_lists = df[df["timestamp"] == _date].merge( map_df["geo_id"], how="right" )[METRICS + [COMBINED_METRIC]].fillna(0) newdf = pd.DataFrame( np.matmul(map_df.values[:, 1:].T, val_lists.values), columns = list(val_lists.keys()) ) newdf["timestamp"] = _date newdf["geo_id"] = list(map_df.keys())[1:] mask = (newdf == 0) newdf[mask] = np.nan converted_df = converted_df.append(newdf) return converted_df
[ "pandas.DataFrame", "delphi_utils.GeoMapper", "pandas.pivot_table", "numpy.matmul" ]
[((203, 214), 'delphi_utils.GeoMapper', 'GeoMapper', ([], {}), '()\n', (212, 214), False, 'from delphi_utils import GeoMapper\n'), ((1945, 1977), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': 'df.columns'}), '(columns=df.columns)\n', (1957, 1977), True, 'import pandas as pd\n'), ((2228, 2279), 'numpy.matmul', 'np.matmul', (['map_df.values[:, 1:].T', 'val_lists.values'], {}), '(map_df.values[:, 1:].T, val_lists.values)\n', (2237, 2279), True, 'import numpy as np\n'), ((1123, 1197), 'pandas.pivot_table', 'pd.pivot_table', (['map_df'], {'values': '"""weight"""', 'index': "['fips']", 'columns': '[geo_res]'}), "(map_df, values='weight', index=['fips'], columns=[geo_res])\n", (1137, 1197), True, 'import pandas as pd\n')]
# import numpy as np import cv2 import face_recognition from PIL import Image,ImageFont,ImageDraw import face_recognition from apps.cve.model.m_face_embedding_manager import MFaceEmbeddingManager from apps.cve.view.v_face_embedding_manager import VFaceEmbeddingManager class CFaceEmbeddingManager(object): def __init__(self): self.name = '' self.model = MFaceEmbeddingManager() def prepare_data(self): yt_image = face_recognition.load_image_file('images/samples/yt1.jpg') yt_face_encodings = face_recognition.face_encodings(yt_image)[0] def startup(self): cap = cv2.VideoCapture(0) while True: ret, frame = cap.read() frame_small = cv2.resize(frame,(0,0),fx=0.25,fy=0.25) #detect all faces in the image #arguments are image,no_of_times_to_upsample, model all_face_locations = face_recognition.face_locations(frame_small,number_of_times_to_upsample=2,model='hog') for index,current_face_location in enumerate(all_face_locations): #splitting the tuple to get the four position values of current face top_pos,right_pos,bottom_pos,left_pos = current_face_location #change the position maginitude to fit the actual size video frame top_pos = top_pos*4 right_pos = right_pos*4 bottom_pos = bottom_pos*4 left_pos = left_pos*4 # enlarge the cripping box left_pos -= int((right_pos - left_pos)*0.25) if left_pos<0: left_pos = 0 top_pos -= int((bottom_pos - top_pos) * 0.6) if top_pos < 0: top_pos = 0 right_pos += int((right_pos - left_pos) * 0.3) if right_pos > frame.shape[1]: right_pos = frame.shape[1] bottom_pos += int((bottom_pos - top_pos) * 0.2) if bottom_pos > frame.shape[0]: bottom_pos = frame.shape[0] #printing the location of current face #print('Found face {} at top:{},right:{},bottom:{},left:{}'.format(index+1,top_pos,right_pos,bottom_pos,left_pos)) current_face_image = frame[top_pos:bottom_pos,left_pos:right_pos] if cv2.waitKey(1) & 0xFF == ord('a'): face_embedding = np.array(face_recognition.face_encodings(current_face_image)) self.model.face_embedding = np.reshape(face_embedding, (face_embedding.shape[1],)) self.model.face_data = current_face_image view = VFaceEmbeddingManager(self) view.show_add_face() #im = Image.fromarray(current_face_image) #im.save("yt2.jpg") #draw rectangle around the face detected cv2.rectangle(frame,(left_pos,top_pos),(right_pos,bottom_pos),(0,0,255),2) cv2.imshow("Webcam Video", frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() def save_face_embedding(self, face_name): ''' 由界面的保存按钮触发,保存当前人脸图片 ''' face_embedding = self.model.face_embedding fe_file = self.model.save_face_embedding_npy(face_embedding) face_jpg = self.model.save_face_jpg(self.model.face_data) face_embedding_num = self.model.face_embedding_num face_name_jpg = self.model.text_to_jpg(face_name, face_embedding_num) self.model.save_face_embedding(face_name, fe_file, face_jpg, face_name_jpg)
[ "cv2.waitKey", "face_recognition.face_encodings", "face_recognition.load_image_file", "cv2.imshow", "cv2.VideoCapture", "apps.cve.model.m_face_embedding_manager.MFaceEmbeddingManager", "apps.cve.view.v_face_embedding_manager.VFaceEmbeddingManager", "numpy.reshape", "cv2.rectangle", "face_recogniti...
[((376, 399), 'apps.cve.model.m_face_embedding_manager.MFaceEmbeddingManager', 'MFaceEmbeddingManager', ([], {}), '()\n', (397, 399), False, 'from apps.cve.model.m_face_embedding_manager import MFaceEmbeddingManager\n'), ((448, 506), 'face_recognition.load_image_file', 'face_recognition.load_image_file', (['"""images/samples/yt1.jpg"""'], {}), "('images/samples/yt1.jpg')\n", (480, 506), False, 'import face_recognition\n'), ((626, 645), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (642, 645), False, 'import cv2\n'), ((3165, 3188), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (3186, 3188), False, 'import cv2\n'), ((535, 576), 'face_recognition.face_encodings', 'face_recognition.face_encodings', (['yt_image'], {}), '(yt_image)\n', (566, 576), False, 'import face_recognition\n'), ((728, 771), 'cv2.resize', 'cv2.resize', (['frame', '(0, 0)'], {'fx': '(0.25)', 'fy': '(0.25)'}), '(frame, (0, 0), fx=0.25, fy=0.25)\n', (738, 771), False, 'import cv2\n'), ((908, 1000), 'face_recognition.face_locations', 'face_recognition.face_locations', (['frame_small'], {'number_of_times_to_upsample': '(2)', 'model': '"""hog"""'}), "(frame_small, number_of_times_to_upsample=2,\n model='hog')\n", (939, 1000), False, 'import face_recognition\n'), ((3029, 3062), 'cv2.imshow', 'cv2.imshow', (['"""Webcam Video"""', 'frame'], {}), "('Webcam Video', frame)\n", (3039, 3062), False, 'import cv2\n'), ((2942, 3029), 'cv2.rectangle', 'cv2.rectangle', (['frame', '(left_pos, top_pos)', '(right_pos, bottom_pos)', '(0, 0, 255)', '(2)'], {}), '(frame, (left_pos, top_pos), (right_pos, bottom_pos), (0, 0, \n 255), 2)\n', (2955, 3029), False, 'import cv2\n'), ((2554, 2608), 'numpy.reshape', 'np.reshape', (['face_embedding', '(face_embedding.shape[1],)'], {}), '(face_embedding, (face_embedding.shape[1],))\n', (2564, 2608), True, 'import numpy as np\n'), ((2698, 2725), 'apps.cve.view.v_face_embedding_manager.VFaceEmbeddingManager', 'VFaceEmbeddingManager', (['self'], {}), '(self)\n', (2719, 2725), False, 'from apps.cve.view.v_face_embedding_manager import VFaceEmbeddingManager\n'), ((3078, 3092), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (3089, 3092), False, 'import cv2\n'), ((2372, 2386), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (2383, 2386), False, 'import cv2\n'), ((2453, 2504), 'face_recognition.face_encodings', 'face_recognition.face_encodings', (['current_face_image'], {}), '(current_face_image)\n', (2484, 2504), False, 'import face_recognition\n')]
# Copyright (c) 2020-present, Assistive Robotics Lab # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # from common.data_utils import read_h5 from common.logging import logger import h5py import argparse import sys import glob import numpy as np def parse_args(): """Parse arguments for module. Returns: argparse.Namespace: contains accessible arguments passed in to module """ parser = argparse.ArgumentParser() parser.add_argument("--training", help=("participants for training, space separated; " "e.g., W1 W2")) parser.add_argument("--validation", help=("participants for validation, space separated; " "e.g., P1 P2")) parser.add_argument("--testing", help=("participants for testing, space separated; " "e.g., P4 P5")) parser.add_argument("-f", "--data-path", help="path to h5 files for reading data") parser.add_argument("-o", "--output-path", help=("path to directory to save h5 files for " "training, validation, and testing")) parser.add_argument("-x", "--task-input", help=("input type; " "e.g., orientation, relativePosition, " "or jointAngle")) parser.add_argument("--input-label-request", help=("input label requests, space separated; " "e.g., all or Pelvis RightForearm")) parser.add_argument("-y", "--task-output", help="output type; e.g., orientation or jointAngle") parser.add_argument("--output-label-request", help=("output label requests, space separated; " "e.g., all or jRightElbow")) parser.add_argument("--aux-task-output", help=("auxiliary task output in addition " "to regular task output")) parser.add_argument("--aux-output-label-request", help="aux output label requests, space separated") args = parser.parse_args() if None in [args.training, args.validation, args.testing]: logger.info(("Participant numbers for training, validation, " "or testing dataset were not provided.")) parser.print_help() sys.exit() if None in [args.data_path, args.output_path]: logger.error("Data path or output path were not provided.") parser.print_help() sys.exit() if None in [args.task_input, args.input_label_request, args.task_output]: logger.error(("Task input and label requests " "or task output were not given.")) parser.print_help() sys.exit() if args.output_label_request is None: if args.task_input == args.task_output: logger.info("Will create h5 files with input data only.") else: logger.error("Label output requests were not given for the task.") parser.print_help() sys.exit() if args.aux_task_output == args.task_output: logger.error("Auxiliary task should not be the same as the main task.") parser.print_help() sys.exit() if (args.aux_task_output is not None and args.aux_output_label_request is None): logger.error("Need auxiliary output labels if using aux output task") parser.print_help() sys.exit() if args.task_input == args.task_output: if args.output_label_request is None: logger.info(("Will create h5 files with only input " "data for self-supervision tasks...")) else: logger.info("Will create h5 files with input and output data.") return args def setup_filepaths(data_path, participant_numbers): """Set up filepaths for reading in participant .h5 files. Args: data_path (str): path to directory containing .h5 files participant_numbers (list): participant numbers for filepaths Returns: list: filepaths to all of the .h5 files """ all_filepaths = [] for participant_number in participant_numbers: filepaths = glob.glob(data_path + "/" + participant_number + "_*.h5") all_filepaths += filepaths return all_filepaths def map_requests(tasks, labels): """Generate a dict of tasks mapped to labels. Args: tasks (list): list of tasks/groups that will be mapped to labels labels (list): list of labels that will be the value for each task Returns: dict: dictionary mapping each task to the list of labels """ requests = dict(map(lambda e: (e, labels), tasks)) return requests def write_dataset(filepath_groups, variable, experiment_setup, requests): """Write data to training, validation, testing .h5 files. Args: filepath_groups (list): list of tuples associate files to data group variable (str): the machine learning variable X or Y to be written to experiment_setup (dict): map to reference task for variable requests (dict): requests to read from files to store with variable """ for filepaths, group in filepath_groups: logger.info(f"Writing {variable} to the {group} set...") h5_filename = args.output_path + "/" + group + ".h5" with h5py.File(h5_filename, "a") as h5_file: dataset = read_h5(filepaths, requests) for filename in dataset.keys(): temp_dataset = None for j, data_group in enumerate(experiment_setup[variable]): if temp_dataset is None: temp_dataset = dataset[filename][data_group] else: temp_dataset = np.append(temp_dataset, dataset[filename][data_group], axis=1) try: h5_file.create_dataset(filename + "/" + variable, data=temp_dataset) except KeyError: logger.info(f"{filename} does not contain {data_group}") if __name__ == "__main__": args = parse_args() train_filepaths = setup_filepaths(args.data_path, args.training.split(" ")) val_filepaths = setup_filepaths(args.data_path, args.validation.split(" ")) test_filepaths = setup_filepaths(args.data_path, args.testing.split(" ")) filepath_groups = [(train_filepaths, "training"), (val_filepaths, "validation"), (test_filepaths, "testing")] task_input = args.task_input.split(" ") input_label_request = args.input_label_request.split(" ") task_output = args.task_output.split(" ") if args.output_label_request is not None: output_label_request = args.output_label_request.split(" ") if (args.task_input == args.task_output and args.output_label_request is None): experiment_setup = {"X": task_input} requests = map_requests(task_input, input_label_request) write_dataset(filepath_groups, "X", experiment_setup, requests) else: experiment_setup = {"X": task_input, "Y": task_output} input_requests = map_requests(task_input, input_label_request) output_requests = map_requests(task_output, output_label_request) if args.aux_task_output is not None: aux_task_output = args.aux_task_output.split(" ") aux_output_label_request = args.aux_output_label_request.split(" ") experiment_setup["Y"] += aux_task_output aux_output_requests = map_requests(aux_task_output, aux_output_label_request) output_requests.update(aux_output_requests) write_dataset(filepath_groups, "X", experiment_setup, input_requests) write_dataset(filepath_groups, "Y", experiment_setup, output_requests)
[ "h5py.File", "argparse.ArgumentParser", "common.data_utils.read_h5", "numpy.append", "common.logging.logger.error", "common.logging.logger.info", "glob.glob", "sys.exit" ]
[((511, 536), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (534, 536), False, 'import argparse\n'), ((2450, 2558), 'common.logging.logger.info', 'logger.info', (['"""Participant numbers for training, validation, or testing dataset were not provided."""'], {}), "(\n 'Participant numbers for training, validation, or testing dataset were not provided.'\n )\n", (2461, 2558), False, 'from common.logging import logger\n'), ((2611, 2621), 'sys.exit', 'sys.exit', ([], {}), '()\n', (2619, 2621), False, 'import sys\n'), ((2682, 2741), 'common.logging.logger.error', 'logger.error', (['"""Data path or output path were not provided."""'], {}), "('Data path or output path were not provided.')\n", (2694, 2741), False, 'from common.logging import logger\n'), ((2778, 2788), 'sys.exit', 'sys.exit', ([], {}), '()\n', (2786, 2788), False, 'import sys\n'), ((2876, 2952), 'common.logging.logger.error', 'logger.error', (['"""Task input and label requests or task output were not given."""'], {}), "('Task input and label requests or task output were not given.')\n", (2888, 2952), False, 'from common.logging import logger\n'), ((3016, 3026), 'sys.exit', 'sys.exit', ([], {}), '()\n', (3024, 3026), False, 'import sys\n'), ((3394, 3465), 'common.logging.logger.error', 'logger.error', (['"""Auxiliary task should not be the same as the main task."""'], {}), "('Auxiliary task should not be the same as the main task.')\n", (3406, 3465), False, 'from common.logging import logger\n'), ((3502, 3512), 'sys.exit', 'sys.exit', ([], {}), '()\n', (3510, 3512), False, 'import sys\n'), ((3619, 3688), 'common.logging.logger.error', 'logger.error', (['"""Need auxiliary output labels if using aux output task"""'], {}), "('Need auxiliary output labels if using aux output task')\n", (3631, 3688), False, 'from common.logging import logger\n'), ((3725, 3735), 'sys.exit', 'sys.exit', ([], {}), '()\n', (3733, 3735), False, 'import sys\n'), ((4489, 4546), 'glob.glob', 'glob.glob', (["(data_path + '/' + participant_number + '_*.h5')"], {}), "(data_path + '/' + participant_number + '_*.h5')\n", (4498, 4546), False, 'import glob\n'), ((5522, 5578), 'common.logging.logger.info', 'logger.info', (['f"""Writing {variable} to the {group} set..."""'], {}), "(f'Writing {variable} to the {group} set...')\n", (5533, 5578), False, 'from common.logging import logger\n'), ((3130, 3187), 'common.logging.logger.info', 'logger.info', (['"""Will create h5 files with input data only."""'], {}), "('Will create h5 files with input data only.')\n", (3141, 3187), False, 'from common.logging import logger\n'), ((3214, 3280), 'common.logging.logger.error', 'logger.error', (['"""Label output requests were not given for the task."""'], {}), "('Label output requests were not given for the task.')\n", (3226, 3280), False, 'from common.logging import logger\n'), ((3325, 3335), 'sys.exit', 'sys.exit', ([], {}), '()\n', (3333, 3335), False, 'import sys\n'), ((3839, 3930), 'common.logging.logger.info', 'logger.info', (['"""Will create h5 files with only input data for self-supervision tasks..."""'], {}), "(\n 'Will create h5 files with only input data for self-supervision tasks...')\n", (3850, 3930), False, 'from common.logging import logger\n'), ((3982, 4045), 'common.logging.logger.info', 'logger.info', (['"""Will create h5 files with input and output data."""'], {}), "('Will create h5 files with input and output data.')\n", (3993, 4045), False, 'from common.logging import logger\n'), ((5653, 5680), 'h5py.File', 'h5py.File', (['h5_filename', '"""a"""'], {}), "(h5_filename, 'a')\n", (5662, 5680), False, 'import h5py\n'), ((5715, 5743), 'common.data_utils.read_h5', 'read_h5', (['filepaths', 'requests'], {}), '(filepaths, requests)\n', (5722, 5743), False, 'from common.data_utils import read_h5\n'), ((6079, 6141), 'numpy.append', 'np.append', (['temp_dataset', 'dataset[filename][data_group]'], {'axis': '(1)'}), '(temp_dataset, dataset[filename][data_group], axis=1)\n', (6088, 6141), True, 'import numpy as np\n'), ((6446, 6502), 'common.logging.logger.info', 'logger.info', (['f"""{filename} does not contain {data_group}"""'], {}), "(f'{filename} does not contain {data_group}')\n", (6457, 6502), False, 'from common.logging import logger\n')]
""" Visualize and save group detections """ from utils import read_cad_frames, read_cad_annotations, get_interaction_features, add_annotation, custom_interaction_features from matplotlib import pyplot as plt from keras.models import Model from keras.layers import Input, Dense from keras.layers.merge import add from keras.optimizers import adam import keras.backend as kb from keras.models import load_model import numpy as np from scipy import io from utils import get_group_instance from matplotlib import pyplot as plt from keras import losses from sklearn.cluster import AffinityPropagation, DBSCAN import os from numpy import genfromtxt, savetxt def kernel_loss(y_true, y_pred): inclusion_dist = kb.max(y_pred - 1 + y_true) exclusion_dist = kb.max(y_pred - y_true) exclusion_dist2 = kb.mean(y_pred * (1 - y_true) * kb.cast(y_pred > 0, dtype=kb.floatx())) # ex_cost = kb.log(exclusion_dist + kb.epsilon()) * (1 - kb.prod(y_true)) # in_cost = -kb.log(inclusion_dist + kb.epsilon()) * (1 - kb.prod(1 - y_true)) ex_cost = (exclusion_dist2 + kb.epsilon()) * (1 - kb.prod(y_true)) in_cost = -(inclusion_dist + kb.epsilon()) * (1 - kb.prod(1 - y_true)) # return inclusion_dist * kb.sum(y_true) # return - exclusion_dist * (1 - kb.prod(y_true)) return in_cost + ex_cost def simple_loss(y_true, y_pred): res_diff = (y_true - y_pred) * kb.cast(y_pred >= 0, dtype=kb.floatx()) return kb.sum(kb.square(res_diff)) ''' ======================CONSTANTS================================================================================== ''' losses.simple_loss = simple_loss losses.kernel_loss = kernel_loss if not os.path.exists('res'): os.makedirs('res') model_path = './models/cad-kernel-affinity-bottom-max-long-custom-20.h5' n_max = 20 cad_dir = '../ActivityDataset' annotations_dir = cad_dir + '/' + 'csvanno-long-feat' # annotations_dir = cad_dir + '/' + 'csvanno-long-feat' annotations_dir_out = cad_dir + '/' + 'csvanno-long-feat-results' colorstr = ['r', 'g', 'b', 'k', 'w', 'm', 'c', 'y'] n = 11 # specify which sequences are visualized test_seq = [1, 4, 5, 6, 8, 2, 7, 28, 35, 11, 10, 26] kernel_net = load_model(model_path) for n in range(1, 45): try: if n == 39: continue f = 1 pose_vec = genfromtxt('../common/pose/pose%2.2d.txt' % n) pose_meta = genfromtxt('../common/pose/meta%2.2d.txt' % n) action_vec = genfromtxt('../split1/atomic/actions.txt') action_meta = genfromtxt('../split1/atomic/meta.txt') if not os.path.exists('res/scene%d' % n): os.makedirs('res/scene%d' % n) # fig, ax = plt.subplots(1) anno_data = read_cad_annotations(annotations_dir, n) print(anno_data.shape) n_frames = np.max(anno_data[:, 0]) while True: f += 10 if f > n_frames: break im = read_cad_frames(cad_dir, n, f) bx, by, bp, bi = custom_interaction_features(anno_data, f, max_people=20) # print(bx[0].shape, by[0].shape, bp[0].shape) # print(len(bx)) # print(bx[0][:, 18:22]) anno_data_i = anno_data[anno_data[:, 0] == f, :] n_ped = anno_data_i.shape[0] affinity_matrix = [] for j in range(len(bx)): # uncomment this to visualize # plt.clf() # ax.clear() # ax.imshow(im) temp = np.squeeze(kernel_net.predict_on_batch(x=[bx[j], bp[j]])) affinity_matrix.append(temp[0:n_ped].tolist()) # uncomment this to visualize individual features # print() # print(np.round(temp[0:n_ped], 2)) # print(by[j][0:n_ped, 0]) # print() # add_annotation(ax, bi[j, 2:6], 'k', 2) for k in range(n_ped): l = k # uncomment this to visualize individual features # if l is not j: # if np.sum(bi[k, 10:]) > 0: # if temp[l] > 0.5: # add_annotation(ax, bi[k, 2:6], 'b', 2) # ax.arrow(bi[k, 2], bi[k, 3], 64 * bx[k][k, 0], 64 * bx[k][k, 1], fc='b', ec='b', # head_width=5, head_length=10) # else: # add_annotation(ax, bi[k, 2:6], 'r', 2) # ax.arrow(bi[k, 2], bi[k, 3], 64 * bx[k][k, 0], 64 * bx[k][k, 1], fc='r', ec='r', # head_width=5, head_length=10) # uncomment this to visualize individual features # add_annotation(ax, bi[j, 2:6], 'k', 2) # ax.arrow(bi[j, 2], bi[j, 3], 64*bx[j][0, 0], 64*bx[j][0, 1], fc='k', ec='k', # head_width=5, head_length=10) # print(bi[j, 2], bi[j, 3], 64*bx[j][0, 0], 64*bx[j][0, 1]) # plt.pause(1./2) affinity_matrix = np.array(affinity_matrix) affinity_matrix[np.isnan(affinity_matrix)] = 0 # try: # print(affinity_matrix) if n_ped == 0: continue af = DBSCAN(eps=0.55, metric='precomputed', min_samples=0, algorithm='auto', n_jobs=1) af.fit(1-affinity_matrix) # print(af.labels_) af_labels = af.labels_ n_samples = af_labels.shape[0] ipm = np.zeros(shape=(n_samples, n_samples)) for i1 in range(n_samples): for i2 in range(n_samples): ipm[i1, i2] = af_labels[i1] == af_labels[i2] # print(ipm) gt_pm = np.zeros(shape=(n_samples, n_samples)) for i1 in range(n_samples): for i2 in range(n_samples): gt_pm[i1, i2] = by[i1][i2, 0] # print(gt_pm) # ax.clear() # ax.imshow(im) # for j in range(len(bx)): # # plt.clf() # add_annotation(ax, bi[j, 2:6], colorstr[af_labels[j]], 2) # plt.pause(0.01) # plt.savefig('res/scene%d/frame%d.png' % (n, f)) ## except: # print('skipped clustering') for ped_i in range(af_labels.shape[0]): # print(np.sum(np.bitwise_and(anno_data[:, 0] == f, anno_data[:, 1] == ped_i+1))) anno_data[np.bitwise_and(anno_data[:, 0] == f, anno_data[:, 1] == ped_i+1), 8] = af_labels[ped_i] + 1 # save group labels savetxt(annotations_dir_out + '/' + 'data_%2.2d.txt' % n, anno_data, delimiter=',') print(annotations_dir_out + '/' + 'data_%2.2d.txt' % n) except: print('skipped', n)
[ "keras.models.load_model", "utils.custom_interaction_features", "keras.backend.epsilon", "utils.read_cad_frames", "numpy.isnan", "utils.read_cad_annotations", "sklearn.cluster.DBSCAN", "numpy.savetxt", "os.path.exists", "numpy.genfromtxt", "numpy.max", "keras.backend.max", "os.makedirs", "...
[((2167, 2189), 'keras.models.load_model', 'load_model', (['model_path'], {}), '(model_path)\n', (2177, 2189), False, 'from keras.models import load_model\n'), ((710, 737), 'keras.backend.max', 'kb.max', (['(y_pred - 1 + y_true)'], {}), '(y_pred - 1 + y_true)\n', (716, 737), True, 'import keras.backend as kb\n'), ((759, 782), 'keras.backend.max', 'kb.max', (['(y_pred - y_true)'], {}), '(y_pred - y_true)\n', (765, 782), True, 'import keras.backend as kb\n'), ((1660, 1681), 'os.path.exists', 'os.path.exists', (['"""res"""'], {}), "('res')\n", (1674, 1681), False, 'import os\n'), ((1687, 1705), 'os.makedirs', 'os.makedirs', (['"""res"""'], {}), "('res')\n", (1698, 1705), False, 'import os\n'), ((1441, 1460), 'keras.backend.square', 'kb.square', (['res_diff'], {}), '(res_diff)\n', (1450, 1460), True, 'import keras.backend as kb\n'), ((2297, 2343), 'numpy.genfromtxt', 'genfromtxt', (["('../common/pose/pose%2.2d.txt' % n)"], {}), "('../common/pose/pose%2.2d.txt' % n)\n", (2307, 2343), False, 'from numpy import genfromtxt, savetxt\n'), ((2364, 2410), 'numpy.genfromtxt', 'genfromtxt', (["('../common/pose/meta%2.2d.txt' % n)"], {}), "('../common/pose/meta%2.2d.txt' % n)\n", (2374, 2410), False, 'from numpy import genfromtxt, savetxt\n'), ((2433, 2475), 'numpy.genfromtxt', 'genfromtxt', (['"""../split1/atomic/actions.txt"""'], {}), "('../split1/atomic/actions.txt')\n", (2443, 2475), False, 'from numpy import genfromtxt, savetxt\n'), ((2498, 2537), 'numpy.genfromtxt', 'genfromtxt', (['"""../split1/atomic/meta.txt"""'], {}), "('../split1/atomic/meta.txt')\n", (2508, 2537), False, 'from numpy import genfromtxt, savetxt\n'), ((2690, 2730), 'utils.read_cad_annotations', 'read_cad_annotations', (['annotations_dir', 'n'], {}), '(annotations_dir, n)\n', (2710, 2730), False, 'from utils import read_cad_frames, read_cad_annotations, get_interaction_features, add_annotation, custom_interaction_features\n'), ((2781, 2804), 'numpy.max', 'np.max', (['anno_data[:, 0]'], {}), '(anno_data[:, 0])\n', (2787, 2804), True, 'import numpy as np\n'), ((6708, 6795), 'numpy.savetxt', 'savetxt', (["(annotations_dir_out + '/' + 'data_%2.2d.txt' % n)", 'anno_data'], {'delimiter': '""","""'}), "(annotations_dir_out + '/' + 'data_%2.2d.txt' % n, anno_data,\n delimiter=',')\n", (6715, 6795), False, 'from numpy import genfromtxt, savetxt\n'), ((1072, 1084), 'keras.backend.epsilon', 'kb.epsilon', ([], {}), '()\n', (1082, 1084), True, 'import keras.backend as kb\n'), ((1093, 1108), 'keras.backend.prod', 'kb.prod', (['y_true'], {}), '(y_true)\n', (1100, 1108), True, 'import keras.backend as kb\n'), ((1164, 1183), 'keras.backend.prod', 'kb.prod', (['(1 - y_true)'], {}), '(1 - y_true)\n', (1171, 1183), True, 'import keras.backend as kb\n'), ((2554, 2587), 'os.path.exists', 'os.path.exists', (["('res/scene%d' % n)"], {}), "('res/scene%d' % n)\n", (2568, 2587), False, 'import os\n'), ((2601, 2631), 'os.makedirs', 'os.makedirs', (["('res/scene%d' % n)"], {}), "('res/scene%d' % n)\n", (2612, 2631), False, 'import os\n'), ((2916, 2946), 'utils.read_cad_frames', 'read_cad_frames', (['cad_dir', 'n', 'f'], {}), '(cad_dir, n, f)\n', (2931, 2946), False, 'from utils import read_cad_frames, read_cad_annotations, get_interaction_features, add_annotation, custom_interaction_features\n'), ((2977, 3033), 'utils.custom_interaction_features', 'custom_interaction_features', (['anno_data', 'f'], {'max_people': '(20)'}), '(anno_data, f, max_people=20)\n', (3004, 3033), False, 'from utils import read_cad_frames, read_cad_annotations, get_interaction_features, add_annotation, custom_interaction_features\n'), ((5144, 5169), 'numpy.array', 'np.array', (['affinity_matrix'], {}), '(affinity_matrix)\n', (5152, 5169), True, 'import numpy as np\n'), ((5354, 5439), 'sklearn.cluster.DBSCAN', 'DBSCAN', ([], {'eps': '(0.55)', 'metric': '"""precomputed"""', 'min_samples': '(0)', 'algorithm': '"""auto"""', 'n_jobs': '(1)'}), "(eps=0.55, metric='precomputed', min_samples=0, algorithm='auto',\n n_jobs=1)\n", (5360, 5439), False, 'from sklearn.cluster import AffinityPropagation, DBSCAN\n'), ((5602, 5640), 'numpy.zeros', 'np.zeros', ([], {'shape': '(n_samples, n_samples)'}), '(shape=(n_samples, n_samples))\n', (5610, 5640), True, 'import numpy as np\n'), ((5835, 5873), 'numpy.zeros', 'np.zeros', ([], {'shape': '(n_samples, n_samples)'}), '(shape=(n_samples, n_samples))\n', (5843, 5873), True, 'import numpy as np\n'), ((1143, 1155), 'keras.backend.epsilon', 'kb.epsilon', ([], {}), '()\n', (1153, 1155), True, 'import keras.backend as kb\n'), ((1410, 1421), 'keras.backend.floatx', 'kb.floatx', ([], {}), '()\n', (1419, 1421), True, 'import keras.backend as kb\n'), ((5198, 5223), 'numpy.isnan', 'np.isnan', (['affinity_matrix'], {}), '(affinity_matrix)\n', (5206, 5223), True, 'import numpy as np\n'), ((863, 874), 'keras.backend.floatx', 'kb.floatx', ([], {}), '()\n', (872, 874), True, 'import keras.backend as kb\n'), ((6579, 6645), 'numpy.bitwise_and', 'np.bitwise_and', (['(anno_data[:, 0] == f)', '(anno_data[:, 1] == ped_i + 1)'], {}), '(anno_data[:, 0] == f, anno_data[:, 1] == ped_i + 1)\n', (6593, 6645), True, 'import numpy as np\n')]
"""Just for testing purposes. Change at will.""" import numpy as np X = np.array([[30, 0], [50, 0], [70, 1], [30, 1], [50, 1], [60, 0], [61, 0], [40, 0], [39, 0], [40, 1], [39, 1]]) y = np.array([0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0]) X = X.astype('float32') y = y.astype('float32') std = np.std(X, axis=0) mean = np.mean(X, axis=0) def normalize(X): return (X - mean) / std def denormalize(X): return X * std + mean Xn = normalize(X) def keras_nn_model(X, y): from alchemy import binary_model model = binary_model(input_shape=X[0].shape) history = model.fit(X, y, batch_size=1, epochs=500, verbose=1) return model, history def SVM(): from sklearn.svm import SVC model = SVC() model.fit(Xn, y) return model def KNN(k=3): from sklearn.neighbors import KNeighborsClassifier model = KNeighborsClassifier(k) model.fit(Xn, y) return model def RandomForest(): from sklearn.ensemble import RandomForestClassifier model = RandomForestClassifier() model.fit(Xn, y) return model print('Neural Net') nn, history = keras_nn_model(Xn, y) error_indices = nn.predict(Xn).round().ravel() != y print(X[error_indices]) print(nn.evaluate(Xn, y)) # nn.fit(Xn[error_indices], y[error_indices], batch_size=1, epochs=100) # error_indices = nn.predict(Xn).round().ravel() != y # print(X[error_indices]) # print('SVM') # svm = SVM(Xn, y) # print(X[svm.predict(Xn).round().ravel() != y]) # print('k-NN') # knn = KNN(Xn, y) # print(X[knn.predict(Xn).round().ravel() != y]) # print('Random Forest') # random_forest = RandomForest(Xn, y) # print(X[random_forest.predict(Xn).round().ravel() != y])
[ "sklearn.ensemble.RandomForestClassifier", "numpy.std", "sklearn.neighbors.KNeighborsClassifier", "numpy.mean", "numpy.array", "sklearn.svm.SVC", "alchemy.binary_model" ]
[((75, 189), 'numpy.array', 'np.array', (['[[30, 0], [50, 0], [70, 1], [30, 1], [50, 1], [60, 0], [61, 0], [40, 0], [\n 39, 0], [40, 1], [39, 1]]'], {}), '([[30, 0], [50, 0], [70, 1], [30, 1], [50, 1], [60, 0], [61, 0], [\n 40, 0], [39, 0], [40, 1], [39, 1]])\n', (83, 189), True, 'import numpy as np\n'), ((329, 372), 'numpy.array', 'np.array', (['[0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0]'], {}), '([0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0])\n', (337, 372), True, 'import numpy as np\n'), ((429, 446), 'numpy.std', 'np.std', (['X'], {'axis': '(0)'}), '(X, axis=0)\n', (435, 446), True, 'import numpy as np\n'), ((454, 472), 'numpy.mean', 'np.mean', (['X'], {'axis': '(0)'}), '(X, axis=0)\n', (461, 472), True, 'import numpy as np\n'), ((667, 703), 'alchemy.binary_model', 'binary_model', ([], {'input_shape': 'X[0].shape'}), '(input_shape=X[0].shape)\n', (679, 703), False, 'from alchemy import binary_model\n'), ((855, 860), 'sklearn.svm.SVC', 'SVC', ([], {}), '()\n', (858, 860), False, 'from sklearn.svm import SVC\n'), ((983, 1006), 'sklearn.neighbors.KNeighborsClassifier', 'KNeighborsClassifier', (['k'], {}), '(k)\n', (1003, 1006), False, 'from sklearn.neighbors import KNeighborsClassifier\n'), ((1136, 1160), 'sklearn.ensemble.RandomForestClassifier', 'RandomForestClassifier', ([], {}), '()\n', (1158, 1160), False, 'from sklearn.ensemble import RandomForestClassifier\n')]
import RPi.GPIO as GPIO import time import datetime import csv import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation trig = 13 echo = 15 print('setting up the pins') #GPIO.cleanup() GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) GPIO.setup(trig,GPIO.OUT) GPIO.setup(echo,GPIO.IN) # Create figure for plotting fig = plt.figure() ax = fig.add_subplot(1, 1, 1) xs = [] sensor_reading = [] k_estimated = [] k_uncertainity = [] file_name = 'ultrasonic_kalman_data.csv' with open(file_name, 'a') as header: csvwriter = csv.writer(header) csvwriter.writerow(['Ultrasonic sensor data','Kalman filter estimation','Uncertainity']) # initialization for kalman filters x = np.matrix([[0.]]) # initial distance estimate p = np.matrix([[1000.]]) # initial uncertainity u = np.matrix([[0.]]) w = np.matrix([[0.]]) A = np.matrix([[1.]]) B = np.matrix([[0.]]) H = np.matrix([[1.]]) Q = np.matrix([[0.00001]]) R = np.matrix([[0.10071589]]) # True distance if distance is fixed true_distance = [] def kalman(x_,p_,x_measured): # prediction x_predicted = A*x_ + B*u + w p_predicted = A*p_*np.transpose(A) + Q # measurement update y = x_measured - (H*x_predicted) # kalman estimation s = H*p_predicted*np.transpose(H) + R K = p_predicted*np.transpose(H)*np.linalg.inv(s) x_estimated = x_predicted + (K*y) p_estimated = (1 - (K*H))*p_predicted return x_estimated, p_estimated def measure(k, xs, sensor_reading, k_estimated, true_distance): global x, p GPIO.output(trig,False) #print('Waiting for the sensors to settle') time.sleep(1) GPIO.output(trig,True) time.sleep(0.00001) GPIO.output(trig,False) while(GPIO.input(echo)==0): pulse_start = time.time() while(GPIO.input(echo)==1): pulse_end = time.time() pulse = pulse_end - pulse_start distance = round(pulse * 17150,5) xs.append(k) sensor_reading.append(distance) ''' if k <= 15: true_distance.append(10) if k>15 and k<=30: true_distance.append(12) if k>30: true_distance.append(20) ''' true_distance.append(10) x, p = kalman(x,p,distance) k_estimated.append(x.item(0)) k_uncertainity.append(p) with open(file_name, 'a') as csvfile: csvwriter = csv.writer(csvfile) csvwriter.writerow([distance,x.item(0),p.item(0)]) # Limit x and y lists to 20 items xs = xs[-20:] sensor_reading = sensor_reading[-20:] true_distance = true_distance[-20:] k_estimated = k_estimated[-20:] # Draw x and y lists ax.clear() ax.plot(xs, sensor_reading, label='Sensor data') ax.plot(xs, k_estimated, 'tab:red', label='kalman estimation') ax.plot(xs, true_distance, 'tab:orange', label='True distance') #legend = ax.legend(loc='upper center', shadow=True, fontsize='x-large') ax.legend() '''if k == 14 or k == 29: print('Distance changed') ''' # Format plot #plt.xticks(rotation=45, ha='right') plt.subplots_adjust(bottom=0.30) plt.title('Kalman filter data estimation of HCSR04') plt.ylabel('Distance (cms)') print('Distance from sensor: ',distance,' cms') print('kalman estimated distance: ',x.item(0),' cms') try: ani = animation.FuncAnimation(fig, measure, fargs=(xs, sensor_reading, k_estimated, true_distance), interval=2000) plt.show() except KeyboardInterrupt: print('Cleaning up') GPIO.cleanup()
[ "matplotlib.pyplot.title", "numpy.matrix", "RPi.GPIO.setmode", "matplotlib.pyplot.show", "csv.writer", "RPi.GPIO.cleanup", "RPi.GPIO.setup", "numpy.transpose", "time.sleep", "matplotlib.animation.FuncAnimation", "time.time", "matplotlib.pyplot.figure", "numpy.linalg.inv", "RPi.GPIO.input",...
[((223, 247), 'RPi.GPIO.setmode', 'GPIO.setmode', (['GPIO.BOARD'], {}), '(GPIO.BOARD)\n', (235, 247), True, 'import RPi.GPIO as GPIO\n'), ((248, 271), 'RPi.GPIO.setwarnings', 'GPIO.setwarnings', (['(False)'], {}), '(False)\n', (264, 271), True, 'import RPi.GPIO as GPIO\n'), ((272, 298), 'RPi.GPIO.setup', 'GPIO.setup', (['trig', 'GPIO.OUT'], {}), '(trig, GPIO.OUT)\n', (282, 298), True, 'import RPi.GPIO as GPIO\n'), ((298, 323), 'RPi.GPIO.setup', 'GPIO.setup', (['echo', 'GPIO.IN'], {}), '(echo, GPIO.IN)\n', (308, 323), True, 'import RPi.GPIO as GPIO\n'), ((359, 371), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (369, 371), True, 'import matplotlib.pyplot as plt\n'), ((725, 743), 'numpy.matrix', 'np.matrix', (['[[0.0]]'], {}), '([[0.0]])\n', (734, 743), True, 'import numpy as np\n'), ((780, 801), 'numpy.matrix', 'np.matrix', (['[[1000.0]]'], {}), '([[1000.0]])\n', (789, 801), True, 'import numpy as np\n'), ((831, 849), 'numpy.matrix', 'np.matrix', (['[[0.0]]'], {}), '([[0.0]])\n', (840, 849), True, 'import numpy as np\n'), ((853, 871), 'numpy.matrix', 'np.matrix', (['[[0.0]]'], {}), '([[0.0]])\n', (862, 871), True, 'import numpy as np\n'), ((875, 893), 'numpy.matrix', 'np.matrix', (['[[1.0]]'], {}), '([[1.0]])\n', (884, 893), True, 'import numpy as np\n'), ((897, 915), 'numpy.matrix', 'np.matrix', (['[[0.0]]'], {}), '([[0.0]])\n', (906, 915), True, 'import numpy as np\n'), ((919, 937), 'numpy.matrix', 'np.matrix', (['[[1.0]]'], {}), '([[1.0]])\n', (928, 937), True, 'import numpy as np\n'), ((941, 961), 'numpy.matrix', 'np.matrix', (['[[1e-05]]'], {}), '([[1e-05]])\n', (950, 961), True, 'import numpy as np\n'), ((968, 993), 'numpy.matrix', 'np.matrix', (['[[0.10071589]]'], {}), '([[0.10071589]])\n', (977, 993), True, 'import numpy as np\n'), ((564, 582), 'csv.writer', 'csv.writer', (['header'], {}), '(header)\n', (574, 582), False, 'import csv\n'), ((1565, 1589), 'RPi.GPIO.output', 'GPIO.output', (['trig', '(False)'], {}), '(trig, False)\n', (1576, 1589), True, 'import RPi.GPIO as GPIO\n'), ((1641, 1654), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (1651, 1654), False, 'import time\n'), ((1660, 1683), 'RPi.GPIO.output', 'GPIO.output', (['trig', '(True)'], {}), '(trig, True)\n', (1671, 1683), True, 'import RPi.GPIO as GPIO\n'), ((1687, 1704), 'time.sleep', 'time.sleep', (['(1e-05)'], {}), '(1e-05)\n', (1697, 1704), False, 'import time\n'), ((1711, 1735), 'RPi.GPIO.output', 'GPIO.output', (['trig', '(False)'], {}), '(trig, False)\n', (1722, 1735), True, 'import RPi.GPIO as GPIO\n'), ((3081, 3112), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'bottom': '(0.3)'}), '(bottom=0.3)\n', (3100, 3112), True, 'import matplotlib.pyplot as plt\n'), ((3118, 3170), 'matplotlib.pyplot.title', 'plt.title', (['"""Kalman filter data estimation of HCSR04"""'], {}), "('Kalman filter data estimation of HCSR04')\n", (3127, 3170), True, 'import matplotlib.pyplot as plt\n'), ((3175, 3203), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Distance (cms)"""'], {}), "('Distance (cms)')\n", (3185, 3203), True, 'import matplotlib.pyplot as plt\n'), ((3335, 3447), 'matplotlib.animation.FuncAnimation', 'animation.FuncAnimation', (['fig', 'measure'], {'fargs': '(xs, sensor_reading, k_estimated, true_distance)', 'interval': '(2000)'}), '(fig, measure, fargs=(xs, sensor_reading,\n k_estimated, true_distance), interval=2000)\n', (3358, 3447), True, 'import matplotlib.animation as animation\n'), ((3448, 3458), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3456, 3458), True, 'import matplotlib.pyplot as plt\n'), ((1345, 1361), 'numpy.linalg.inv', 'np.linalg.inv', (['s'], {}), '(s)\n', (1358, 1361), True, 'import numpy as np\n'), ((1746, 1762), 'RPi.GPIO.input', 'GPIO.input', (['echo'], {}), '(echo)\n', (1756, 1762), True, 'import RPi.GPIO as GPIO\n'), ((1790, 1801), 'time.time', 'time.time', ([], {}), '()\n', (1799, 1801), False, 'import time\n'), ((1813, 1829), 'RPi.GPIO.input', 'GPIO.input', (['echo'], {}), '(echo)\n', (1823, 1829), True, 'import RPi.GPIO as GPIO\n'), ((1855, 1866), 'time.time', 'time.time', ([], {}), '()\n', (1864, 1866), False, 'import time\n'), ((2364, 2383), 'csv.writer', 'csv.writer', (['csvfile'], {}), '(csvfile)\n', (2374, 2383), False, 'import csv\n'), ((3519, 3533), 'RPi.GPIO.cleanup', 'GPIO.cleanup', ([], {}), '()\n', (3531, 3533), True, 'import RPi.GPIO as GPIO\n'), ((1156, 1171), 'numpy.transpose', 'np.transpose', (['A'], {}), '(A)\n', (1168, 1171), True, 'import numpy as np\n'), ((1289, 1304), 'numpy.transpose', 'np.transpose', (['H'], {}), '(H)\n', (1301, 1304), True, 'import numpy as np\n'), ((1329, 1344), 'numpy.transpose', 'np.transpose', (['H'], {}), '(H)\n', (1341, 1344), True, 'import numpy as np\n')]
######################################## # MIT License # # Copyright (c) 2020 <NAME> ######################################## ''' Basic functions and classes to do minimizations. ''' from ..base import data_types from ..base import exceptions from ..base import parameters from ..base.core import DocMeta import collections import contextlib import numdifftools import numpy as np import warnings DEFAULT_ASYM_ERROR_ATOL = 1e-8 # same as numpy.allclose DEFAULT_ASYM_ERROR_RTOL = 1e-5 # same as numpy.allclose __all__ = ['Minimizer'] MinimizationResult = collections.namedtuple( 'MinimizationResult', ['valid', 'fcn', 'cov']) def errors_and_covariance_matrix(evaluate, result, hessian_opts=None): ''' Calculate the covariance matrix given a function to evaluate the FCN and the values of the parameters at the minimum. :param evaluate: function used to evaluate the FCN. It must take all the parameters that are not constant. :param result: values at the FCN minimum. :type result: numpy.ndarray :param hessian_opts: options to be passed to :class:`numdifftools.core.Hessian`. :type hessian_opts: dict or None :returns: values with the errors and covariance matrix. :rtype: numpy.ndarray(uncertainties.core.Variable), numpy.ndarray ''' hessian_opts = hessian_opts or {} # Disable warnings, since "numdifftools" does not allow to set bounds with warnings.catch_warnings(): warnings.simplefilter('ignore') hessian = numdifftools.Hessian( lambda a: evaluate(*a), **hessian_opts) cov = 2. * np.linalg.inv(hessian(result)) errors = np.sqrt(np.diag(cov)) return errors, cov def determine_varargs_values_varids(args): ''' Check the arguments that are constant and create three collections: one containing the arguments that are constant, the values of these parameters and the position in the list. :param args: collection of arguments. :type args: Registry(Parameter) :returns: constant parameters, values and indices in the registry. :rtype: Registry(Parameter), numpy.ndarray, numpy.ndarray ''' varargs = parameters.Registry(filter(lambda v: not v.constant, args)) # We must create an array with all the values varids = [] values = data_types.empty_float(len(args)) for i, a in enumerate(args): if a.constant: values[i] = a.value else: varids.append(i) return varargs, values, varids def _process_parameters(args, wa, values): ''' Process an input set of parameters, converting it to a :class:`Registry`, if only one parameter is provided. :param args: whole set of parameters. :type args: Registry :param wa: input arguments to process. :type wa: str or list(str) :param values: values to calculate a profile. :type values: numpy.ndarray :returns: registry of parameters and values. :rtype: Registry, numpy.ndarray :raises RuntimeError: If the number of provided sets of values is differet to the number of profile parameters. ''' values = np.asarray(values) if np.asarray(wa).ndim == 0: wa = [wa] values = np.array([values]) if len(wa) != len(values): raise RuntimeError( 'Length of the profile values must coincide with profile parameters') pars = parameters.Registry(args.get(n) for n in wa) return pars, values class Minimizer(object, metaclass=DocMeta): def __init__(self, evaluator): ''' Abstract class to serve as an API between MinKit and the different minimization methods. :param evaluator: evaluator to be used in the minimization. :type evaluator: UnbinnedEvaluator, BinnedEvaluator or SimultaneousEvaluator ''' super().__init__() self.__eval = evaluator def _asym_error(self, par, bound, var=1, atol=DEFAULT_ASYM_ERROR_ATOL, rtol=DEFAULT_ASYM_ERROR_RTOL, max_call=None): ''' Calculate the asymmetric error using the variation of the FCN from *value* to *bound*. :param par: parameter to calculate the asymmetric errors. :type par: float :param bound: bound of the parameter. :type bound: float :param var: squared number of standard deviations. :type var: float :param atol: absolute tolerance for the error. :type atol: float :param rtol: relative tolerance for the error. :type rtol: float :param max_call: maximum number of calls to calculate each error bound. :type max_call: int or None :returns: Absolute value of the error. :rtype: float ''' with self.restoring_state(): initial = par.value l, r = par.value, bound # consider the minimum on the left fcn_l = ref_fcn = self.__eval.fcn() # it must have been minimized self._set_parameter_state(par, value=bound, fixed=True) fcn_r = self._minimize_check_minimum(par) if np.allclose(fcn_r - ref_fcn, var, atol=atol, rtol=rtol): return abs(par.value - bound) closest_fcn = fcn_r i = 0 while (True if max_call is None else i < max_call) and not np.allclose(abs(closest_fcn - ref_fcn), var, atol=atol, rtol=rtol): i += 1 # increase the internal counter (for max_call) self._set_parameter_state(par, value=0.5 * (l + r)) fcn = self._minimize_check_minimum(par) if abs(fcn - ref_fcn) < var: l, fcn_l = par.value, fcn else: r, fcn_r = par.value, fcn if var - (fcn_l - ref_fcn) < (fcn_r - ref_fcn) - var: bound, closest_fcn = l, fcn_l else: bound, closest_fcn = r, fcn_r if max_call is not None and i == max_call: warnings.warn( 'Reached maximum number of minimization calls', RuntimeWarning, stacklevel=1) return abs(initial - bound) def _minimize_check_minimum(self, par): ''' Check the minimum of a minimization and warn if it is not valid. :param par: parameter to work with. :type par: Parameter :returns: Value of the FCN. :rtype: float ''' m = self.minimize() if not m.valid: warnings.warn('Minimum is not valid during FCN scan', RuntimeWarning, stacklevel=2) return m.fcn def _set_parameter_state(self, par, value=None, error=None, fixed=None): ''' Set the state of the parameter. :param par: parameter to modify. :type par: Parameter :param value: new value of a parameter. :type value: float or None :param error: error of the parameter. :type error: float or None :param fixed: whether to fix the parameter. :type fixed: bool or None ''' if value is not None: par.value = value if error is not None: par.error = error if fixed is not None: par.constant = fixed @property def evaluator(self): ''' Evaluator of the minimizer. ''' return self.__eval def asymmetric_errors(self, name, sigma=1, atol=DEFAULT_ASYM_ERROR_ATOL, rtol=DEFAULT_ASYM_ERROR_RTOL, max_call=None): ''' Calculate the asymmetric errors for the given parameter. This is done by subdividing the bounds of the parameter into two till the variation of the FCN is one. Unlike MINOS, this method does not treat new minima. Remember that the PDF must have been minimized before a call to this function. :param name: name of the parameter. :type name: str :param sigma: number of standard deviations to compute. :type sigma: float :param atol: absolute tolerance for the error. :type atol: float :param rtol: relative tolerance for the error. :type rtol: float :param max_call: maximum number of calls to calculate each error bound. :type max_call: int or None ''' par = self.__eval.args.get(name) lb, ub = par.bounds var = sigma * sigma lo = self._asym_error(par, lb, var, atol, rtol, max_call) hi = self._asym_error(par, ub, var, atol, rtol, max_call) par.asym_errors = lo, hi def fcn_profile(self, wa, values): ''' Evaluate the profile of an FCN for a set of parameters and values. :param wa: single variable or set of variables. :type wa: str or list(str). :param values: values for each parameter specified in *wa*. :type values: numpy.ndarray :returns: Profile of the FCN for the given values. :rtype: numpy.ndarray ''' profile_pars, values = _process_parameters( self.__eval.args, wa, values) fcn_values = data_types.empty_float(len(values[0])) with self.restoring_state(): for p in self.__eval.args: if p in profile_pars: self._set_parameter_state(p, fixed=False) else: self._set_parameter_state(p, fixed=True) with self.__eval.using_caches(): for i, vals in enumerate(values.T): for p, v in zip(profile_pars, vals): self._set_parameter_state(p, value=v) fcn_values[i] = self.__eval.fcn() return fcn_values def minimize(self, *args, **kwargs): ''' Minimize the FCN for the stored PDF and data sample. Arguments depend on the specific minimizer to use. It returns a tuple with the information whether the minimization succeded and the covariance matrix. ''' raise exceptions.MethodNotDefinedError( self.__class__, 'minimize') def minimization_profile(self, wa, values, minimization_results=False, minimizer_config=None): ''' Minimize a PDF an calculate the FCN for each set of parameters and values. :param wa: single variable or set of variables. :type wa: str or list(str). :param values: values for each parameter specified in *wa*. :type values: numpy.ndarray :param minimization_results: if set to True, then the results for each step are returned. :type minimization_results: bool :param minimizer_config: arguments passed to :meth:`Minimizer.minimize`. :type minimizer_config: dict or None :returns: Profile of the FCN for the given values. :rtype: numpy.ndarray, (list(MinimizationResult)) ''' profile_pars, values = _process_parameters( self.__eval.args, wa, values) fcn_values = data_types.empty_float(len(values[0])) minimizer_config = minimizer_config or {} results = [] with self.restoring_state(): for p in profile_pars: self._set_parameter_state(p, fixed=True) for i, vals in enumerate(values.T): for p, v in zip(profile_pars, vals): self._set_parameter_state(p, value=v) res = self.minimize(**minimizer_config) if not res.valid: warnings.warn( 'Minimum in FCN scan is not valid', RuntimeWarning) fcn_values[i] = res.fcn results.append(res) if minimization_results: return fcn_values, res else: return fcn_values @contextlib.contextmanager def restoring_state(self): ''' Method to ensure that modifications of parameters within a minimizer context are reset properly. .. seealso:: :meth:`MinuitMinimizer.restoring_state`, :meth:`SciPyMinimizer.restoring_state` ''' with self.__eval.args.restoring_state(): yield self def set_parameter_state(self, name, value=None, error=None, fixed=None): ''' Method to ensure that a modification of a parameter within a minimizer context is treated properly. Sadly, the :class:`iminuit.Minuit` class is not stateless, so each time a parameter is modified it must be notified of the change. :param name: name of the parameter. :type name: str :param value: new value of a parameter. :type value: float or None :param error: error of the parameter. :type error: float or None :param fixed: whether to fix the parameter. :type fixed: bool or None ''' par = self.__eval.args.get(name) return self._set_parameter_state(par, value, error, fixed)
[ "warnings.simplefilter", "numpy.asarray", "numpy.allclose", "warnings.catch_warnings", "collections.namedtuple", "numpy.array", "numpy.diag", "warnings.warn" ]
[((562, 631), 'collections.namedtuple', 'collections.namedtuple', (['"""MinimizationResult"""', "['valid', 'fcn', 'cov']"], {}), "('MinimizationResult', ['valid', 'fcn', 'cov'])\n", (584, 631), False, 'import collections\n'), ((3133, 3151), 'numpy.asarray', 'np.asarray', (['values'], {}), '(values)\n', (3143, 3151), True, 'import numpy as np\n'), ((1423, 1448), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {}), '()\n', (1446, 1448), False, 'import warnings\n'), ((1458, 1489), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""'], {}), "('ignore')\n", (1479, 1489), False, 'import warnings\n'), ((1654, 1666), 'numpy.diag', 'np.diag', (['cov'], {}), '(cov)\n', (1661, 1666), True, 'import numpy as np\n'), ((3221, 3239), 'numpy.array', 'np.array', (['[values]'], {}), '([values])\n', (3229, 3239), True, 'import numpy as np\n'), ((3160, 3174), 'numpy.asarray', 'np.asarray', (['wa'], {}), '(wa)\n', (3170, 3174), True, 'import numpy as np\n'), ((5097, 5152), 'numpy.allclose', 'np.allclose', (['(fcn_r - ref_fcn)', 'var'], {'atol': 'atol', 'rtol': 'rtol'}), '(fcn_r - ref_fcn, var, atol=atol, rtol=rtol)\n', (5108, 5152), True, 'import numpy as np\n'), ((6507, 6594), 'warnings.warn', 'warnings.warn', (['"""Minimum is not valid during FCN scan"""', 'RuntimeWarning'], {'stacklevel': '(2)'}), "('Minimum is not valid during FCN scan', RuntimeWarning,\n stacklevel=2)\n", (6520, 6594), False, 'import warnings\n'), ((6014, 6109), 'warnings.warn', 'warnings.warn', (['"""Reached maximum number of minimization calls"""', 'RuntimeWarning'], {'stacklevel': '(1)'}), "('Reached maximum number of minimization calls',\n RuntimeWarning, stacklevel=1)\n", (6027, 6109), False, 'import warnings\n'), ((11545, 11610), 'warnings.warn', 'warnings.warn', (['"""Minimum in FCN scan is not valid"""', 'RuntimeWarning'], {}), "('Minimum in FCN scan is not valid', RuntimeWarning)\n", (11558, 11610), False, 'import warnings\n')]
# -*- coding: utf-8 -*- """ Discreption : Data crawler, automatically get treasury rates and interpolate Created on Tue May 12 14:07:21 2020 @author : <NAME> email : <EMAIL> """ import pandas as pd import numpy as np from selenium import webdriver from selenium.webdriver.chrome.options import Options from scipy.interpolate import interp1d def term_structure(chromdriver_path): '''Get the treasury rate data from the U.S Department of The Treasury, do interpolation to get annual rate of 60 years. Chrome browser and chrome driver are needed. chromdriver_path is the local path to chromedriver. ''' url = 'https://www.treasury.gov/resource-center/data-chart-center/interest-rates/Pages/TextView.aspx?data=yield' chrome_options = Options() chrome_options.add_argument("--incognito") chrome_options.add_argument("--window-size=1920x1080") chrome_options.add_argument('headless') # initialize chrome driver driver = webdriver.Chrome(chromdriver_path, options = chrome_options) driver.get(url) # xml style data interest_xml = driver.find_elements_by_xpath('//*[@id="t-content-main-content"]/\ div/table/tbody/tr/td/div/table/tbody') # list of strings style data interest_text = interest_xml[0].text.split('\n') # get the dataframe of the treasury rates nrow = len(interest_text)-1 ncol = len(interest_text[1].split(' ')) col_names = [interest_text[0][i*5:(i*5+5)] for i in range(ncol)] interests = pd.DataFrame(np.zeros([nrow,ncol]), columns = col_names ) for row in range(nrow): interests.iloc[row,:] = interest_text[row+1].split(' ') interests.iloc[:,1:] = interests.iloc[:,1:].astype(float) # use interpolation to get discount rate every year interpolation = interp1d([1,2,3,5,7,10,20,30],interests.iloc[-1,5:]) term_structure = interpolation(range(1,31))/100 # extend term structure to 60 years, # for terms that are longer than 30 years use the rate of 30 years. term_structure = np.concatenate((np.array(term_structure), np.repeat(interests.iloc[-1,-1]/100,30))) print('interestes data successfully collected') return term_structure # test and exemple if __name__ == '__main__': chromdriver_path = 'D:\\chromedriver\\chromedriver_win32\\chromedriver.exe' interests = term_structure(chromdriver_path)
[ "selenium.webdriver.chrome.options.Options", "numpy.zeros", "numpy.array", "selenium.webdriver.Chrome", "scipy.interpolate.interp1d", "numpy.repeat" ]
[((805, 814), 'selenium.webdriver.chrome.options.Options', 'Options', ([], {}), '()\n', (812, 814), False, 'from selenium.webdriver.chrome.options import Options\n'), ((1016, 1074), 'selenium.webdriver.Chrome', 'webdriver.Chrome', (['chromdriver_path'], {'options': 'chrome_options'}), '(chromdriver_path, options=chrome_options)\n', (1032, 1074), False, 'from selenium import webdriver\n'), ((1908, 1969), 'scipy.interpolate.interp1d', 'interp1d', (['[1, 2, 3, 5, 7, 10, 20, 30]', 'interests.iloc[-1, 5:]'], {}), '([1, 2, 3, 5, 7, 10, 20, 30], interests.iloc[-1, 5:])\n', (1916, 1969), False, 'from scipy.interpolate import interp1d\n'), ((1622, 1644), 'numpy.zeros', 'np.zeros', (['[nrow, ncol]'], {}), '([nrow, ncol])\n', (1630, 1644), True, 'import numpy as np\n'), ((2173, 2197), 'numpy.array', 'np.array', (['term_structure'], {}), '(term_structure)\n', (2181, 2197), True, 'import numpy as np\n'), ((2237, 2280), 'numpy.repeat', 'np.repeat', (['(interests.iloc[-1, -1] / 100)', '(30)'], {}), '(interests.iloc[-1, -1] / 100, 30)\n', (2246, 2280), True, 'import numpy as np\n')]
import numpy as np import os import cv2 def main(info, datadir, resultdir): level = len(info) img_width, img_height = info[0][1] filename = '0-1.png' filepath = os.path.join(datadir, filename) img_zero = cv2.imread(filepath, cv2.IMREAD_COLOR) result_name = 'clean0.png' result_path = os.path.join(resultdir, result_name) cv2.imwrite(result_path, img_zero) return for i in range(1, level): img_merge = np.empty(shape=(img_height, img_width, 3)) acc_array = np.empty(shape=(img_height, img_width, 3)) nx, ny = info[i][0] partial_width, partial_height = info[i][1] stride = info[i][2] num = 1 for y in range(ny): if y != ny - 1: for x in range(nx): filename = str(i)+'-'+str(num)+'.png' filepath = os.path.join(datadir, filename) partial_image = cv2.imread(filepath, cv2.IMREAD_COLOR) temp = np.empty(shape=(partial_width, partial_height)) if x == nx - 1: temp = img_merge[y * stride[1]: y * stride[1] + partial_height,\ img_width-1-partial_width:img_width-1] temp = (temp+partial_image) img_merge[y * stride[1]: y * stride[1] + partial_height,\ img_width-1-partial_width:img_width-1] = temp acc_array[y * stride[1]: y * stride[1] + partial_height,\ img_width-1-partial_width:img_width-1] += 1 else: temp = img_merge[y * stride[1]: y * stride[1] + partial_height,\ x * stride[0]: x * stride[0] + partial_width] temp = (temp+partial_image) img_merge[y * stride[1]: y * stride[1] + partial_height,\ x * stride[0]: x * stride[0] + partial_width] = temp acc_array[y * stride[1]: y * stride[1] + partial_height,\ x * stride[0]: x * stride[0] + partial_width] += 1 num += 1 else: for x in range(nx): filename = str(i)+'-'+str(num)+'.png' filepath = os.path.join(datadir, filename) partial_image = cv2.imread(filepath, cv2.IMREAD_COLOR) if x == nx - 1: temp = img_merge[img_height-1-partial_height:img_height-1,\ img_width-1-partial_width:img_width-1] temp = (temp+partial_image) img_merge[img_height-1-partial_height:img_height-1,\ img_width-1-partial_width:img_width-1] = temp acc_array[img_height-1-partial_height:img_height-1,\ img_width-1-partial_width:img_width-1] += 1 else: temp = img_merge[img_height-1-partial_height:img_height-1,\ x * stride[0]: x * stride[0] + partial_width] temp = (temp+partial_image) img_merge[img_height-1-partial_height:img_height-1,\ x * stride[0]: x * stride[0] + partial_width] = temp acc_array[img_height-1-partial_height:img_height-1,\ x * stride[0]: x * stride[0] + partial_width] += 1 num += 1 result_name = 'clean'+str(i)+'.png' result_path = os.path.join(resultdir, result_name) np.seterr(divide='ignore', invalid='ignore') cv2.imwrite(result_path, img_merge/acc_array)
[ "numpy.seterr", "numpy.empty", "cv2.imwrite", "cv2.imread", "os.path.join" ]
[((183, 214), 'os.path.join', 'os.path.join', (['datadir', 'filename'], {}), '(datadir, filename)\n', (195, 214), False, 'import os\n'), ((230, 268), 'cv2.imread', 'cv2.imread', (['filepath', 'cv2.IMREAD_COLOR'], {}), '(filepath, cv2.IMREAD_COLOR)\n', (240, 268), False, 'import cv2\n'), ((319, 355), 'os.path.join', 'os.path.join', (['resultdir', 'result_name'], {}), '(resultdir, result_name)\n', (331, 355), False, 'import os\n'), ((360, 394), 'cv2.imwrite', 'cv2.imwrite', (['result_path', 'img_zero'], {}), '(result_path, img_zero)\n', (371, 394), False, 'import cv2\n'), ((457, 499), 'numpy.empty', 'np.empty', ([], {'shape': '(img_height, img_width, 3)'}), '(shape=(img_height, img_width, 3))\n', (465, 499), True, 'import numpy as np\n'), ((520, 562), 'numpy.empty', 'np.empty', ([], {'shape': '(img_height, img_width, 3)'}), '(shape=(img_height, img_width, 3))\n', (528, 562), True, 'import numpy as np\n'), ((3708, 3744), 'os.path.join', 'os.path.join', (['resultdir', 'result_name'], {}), '(resultdir, result_name)\n', (3720, 3744), False, 'import os\n'), ((3753, 3797), 'numpy.seterr', 'np.seterr', ([], {'divide': '"""ignore"""', 'invalid': '"""ignore"""'}), "(divide='ignore', invalid='ignore')\n", (3762, 3797), True, 'import numpy as np\n'), ((3806, 3853), 'cv2.imwrite', 'cv2.imwrite', (['result_path', '(img_merge / acc_array)'], {}), '(result_path, img_merge / acc_array)\n', (3817, 3853), False, 'import cv2\n'), ((868, 899), 'os.path.join', 'os.path.join', (['datadir', 'filename'], {}), '(datadir, filename)\n', (880, 899), False, 'import os\n'), ((936, 974), 'cv2.imread', 'cv2.imread', (['filepath', 'cv2.IMREAD_COLOR'], {}), '(filepath, cv2.IMREAD_COLOR)\n', (946, 974), False, 'import cv2\n'), ((1003, 1050), 'numpy.empty', 'np.empty', ([], {'shape': '(partial_width, partial_height)'}), '(shape=(partial_width, partial_height))\n', (1011, 1050), True, 'import numpy as np\n'), ((2407, 2438), 'os.path.join', 'os.path.join', (['datadir', 'filename'], {}), '(datadir, filename)\n', (2419, 2438), False, 'import os\n'), ((2475, 2513), 'cv2.imread', 'cv2.imread', (['filepath', 'cv2.IMREAD_COLOR'], {}), '(filepath, cv2.IMREAD_COLOR)\n', (2485, 2513), False, 'import cv2\n')]
# Orthogonal Lowrank Embedding for Caffe # # Copyright (c) <NAME>, 2017 # # <EMAIL> # MAKE SURE scipy is linked against openblas import caffe import numpy as np import scipy as sp class OLELossLayer(caffe.Layer): """ Computes the OLE Loss in CPU """ def setup(self, bottom, top): # check input pair if len(bottom) != 2: raise Exception("Need two inputs to compute distance.") params = eval(self.param_str) self.lambda_ = np.float(params['lambda_']) def reshape(self, bottom, top): # check input dimensions match if bottom[0].shape[0] != bottom[1].shape[0]: raise Exception("Inputs must have the same number of samples.") # difference is shape of inputs self.diff = np.zeros_like(bottom[0].data, dtype=np.float32) # loss output is scalar top[0].reshape(1) def forward(self, bottom, top): # bottom[0] should be X # bottom[1] should be classes X = bottom[0].data y = bottom[1].data classes = np.unique(y) C = classes.size N, D = X.shape DELTA = 1. # gradients initialization Obj_c = 0 dX_c = np.zeros((N, D)) Obj_all = 0; dX_all = np.zeros((N,D)) eigThd = 1e-6 # threshold small eigenvalues for a better subgradient # compute objective and gradient for first term \sum ||TX_c||* for c in classes: A = X[y==c,:] # intra-class SVD U, S, V = sp.linalg.svd(A, full_matrices = False, lapack_driver='gesvd') V = V.T nuclear = np.sum(S); ## L_c = max(DELTA, ||TY_c||_*)-DELTA if nuclear>DELTA: Obj_c += nuclear; # discard small singular values r = np.sum(S<eigThd) uprod = U[:,0:U.shape[1]-r].dot(V[:,0:V.shape[1]-r].T) dX_c[y==c,:] += uprod else: Obj_c+= DELTA # compute objective and gradient for secon term ||TX||* U, S, V = sp.linalg.svd(X, full_matrices = False, lapack_driver='gesvd') # all classes V = V.T Obj_all = np.sum(S); r = np.sum(S<eigThd) uprod = U[:,0:U.shape[1]-r].dot(V[:,0:V.shape[1]-r].T) dX_all = uprod obj = (Obj_c - Obj_all)/N*self.lambda_ dX = (dX_c - dX_all)/N*self.lambda_ self.diff[...] = dX top[0].data[...] = obj def backward(self, top, propagate_down, bottom): propagate_down[1] = 0 # labels don't need backpropagation for i in range(2): if not propagate_down[i]: continue # # # print '----------------------------------------------' # # # print '------------- DOING GRADIENT UPDATE ----------' # # # print '----------------------------------------------' # # # print # # # print 'norm(self.diff)', np.linalg.norm(self.diff) # # # print '' # # # print '' bottom[i].diff[...] = self.diff
[ "numpy.zeros_like", "numpy.sum", "numpy.zeros", "numpy.float", "scipy.linalg.svd", "numpy.unique" ]
[((489, 516), 'numpy.float', 'np.float', (["params['lambda_']"], {}), "(params['lambda_'])\n", (497, 516), True, 'import numpy as np\n'), ((792, 839), 'numpy.zeros_like', 'np.zeros_like', (['bottom[0].data'], {'dtype': 'np.float32'}), '(bottom[0].data, dtype=np.float32)\n', (805, 839), True, 'import numpy as np\n'), ((1080, 1092), 'numpy.unique', 'np.unique', (['y'], {}), '(y)\n', (1089, 1092), True, 'import numpy as np\n'), ((1258, 1274), 'numpy.zeros', 'np.zeros', (['(N, D)'], {}), '((N, D))\n', (1266, 1274), True, 'import numpy as np\n'), ((1313, 1329), 'numpy.zeros', 'np.zeros', (['(N, D)'], {}), '((N, D))\n', (1321, 1329), True, 'import numpy as np\n'), ((2226, 2286), 'scipy.linalg.svd', 'sp.linalg.svd', (['X'], {'full_matrices': '(False)', 'lapack_driver': '"""gesvd"""'}), "(X, full_matrices=False, lapack_driver='gesvd')\n", (2239, 2286), True, 'import scipy as sp\n'), ((2340, 2349), 'numpy.sum', 'np.sum', (['S'], {}), '(S)\n', (2346, 2349), True, 'import numpy as np\n'), ((2364, 2382), 'numpy.sum', 'np.sum', (['(S < eigThd)'], {}), '(S < eigThd)\n', (2370, 2382), True, 'import numpy as np\n'), ((1584, 1644), 'scipy.linalg.svd', 'sp.linalg.svd', (['A'], {'full_matrices': '(False)', 'lapack_driver': '"""gesvd"""'}), "(A, full_matrices=False, lapack_driver='gesvd')\n", (1597, 1644), True, 'import scipy as sp\n'), ((1702, 1711), 'numpy.sum', 'np.sum', (['S'], {}), '(S)\n', (1708, 1711), True, 'import numpy as np\n'), ((1916, 1934), 'numpy.sum', 'np.sum', (['(S < eigThd)'], {}), '(S < eigThd)\n', (1922, 1934), True, 'import numpy as np\n')]
from builtin_interfaces.msg import Duration from ros2pkg.api import get_prefix_path from geometry_msgs.msg import Pose from std_srvs.srv import Empty from std_msgs.msg import String from gazebo_msgs.msg import ContactState, ModelState from gazebo_msgs.srv import DeleteEntity from control_msgs.msg import JointTrajectoryControllerState from trajectory_msgs.msg import JointTrajectory, JointTrajectoryPoint from rclpy.qos import QoSProfile, qos_profile_sensor_data from rclpy.node import Node import rclpy import transforms3d as tf3d import argparse import subprocess from gazebo_msgs.srv import SpawnEntity from gazebo_msgs.msg import ContactsState from gym.utils import seeding from gym_gazebo2.utils import ut_generic, ut_launch, ut_mara, ut_math, ut_gazebo, tree_urdf, general_utils from gym import utils, spaces from scipy.stats import skew import sys import signal import psutil import os import math import copy import numpy as np import time import gym from PyKDL import ChainJntToJacSolver # For KDL Jacobians import pandas as pd from ament_index_python.packages import get_package_share_directory from hrim_actuator_gripper_srvs.srv import ControlFinger from std_msgs.msg import String, Int32MultiArray from sensor_msgs.msg import Image import cv2 gym.logger.set_level(40) # hide warnings # FLAG_DEBUG_CAMERA = True FLAG_DEBUG_CAMERA = False JOINT_SUBSCRIBER = '/mara_controller/state' JOINT_PUBLISHER = '/mara_controller/command' # joint names: MOTOR1_JOINT = 'motor1' MOTOR2_JOINT = 'motor2' MOTOR3_JOINT = 'motor3' MOTOR4_JOINT = 'motor4' MOTOR5_JOINT = 'motor5' MOTOR6_JOINT = 'motor6' EE_LINK = 'ee_link' JOINT_ORDER = [MOTOR1_JOINT, MOTOR2_JOINT, MOTOR3_JOINT, MOTOR4_JOINT, MOTOR5_JOINT, MOTOR6_JOINT] class Robot(Node): def __init__(self): super().__init__('Robot') self.subcription = self.create_subscription( JointTrajectoryControllerState, JOINT_SUBSCRIBER, self.observation_callback, qos_profile=qos_profile_sensor_data) self.pub = self.create_publisher( JointTrajectory, JOINT_PUBLISHER, qos_profile=qos_profile_sensor_data) self.spawn_cli = self.create_client(SpawnEntity, '/spawn_entity') # delete entity self.delete_entity_cli = self.create_client( DeleteEntity, '/delete_entity') # Create a gripper client for service "/hrim_actuation_gripper_000000000004/goal" self.gripper = self.create_client( ControlFinger, "/hrim_actuator_gripper_000000000004/fingercontrol") # Wait for service to be avaiable before calling it while not self.gripper.wait_for_service(timeout_sec=1.0): self.get_logger().info('service not available, waiting again...') self.initArm() self.subscription_img = self.create_subscription( Image, '/rs_camera/rs_d435/image_raw', self.get_img, 10) self.subscription_img # prevent unused variable warning self.subscription_contact = self.create_subscription(ContactState,'/gazebo_contacts', self.get_contact, qos_profile=qos_profile_sensor_data) # QoS profile for reading (joint) sensors def initArm(self): print('start initArm()') urdf = "reinforcement_learning/mara_robot_gripper_140_camera_train.urdf" urdfPath = get_prefix_path("mara_description") + \ "/share/mara_description/urdf/" + urdf # Set constants for links WORLD = 'world' BASE = 'base_robot' MARA_MOTOR1_LINK = 'motor1_link' MARA_MOTOR2_LINK = 'motor2_link' MARA_MOTOR3_LINK = 'motor3_link' MARA_MOTOR4_LINK = 'motor4_link' MARA_MOTOR5_LINK = 'motor5_link' MARA_MOTOR6_LINK = 'motor6_link' EE_LINK = 'ee_link' LINK_NAMES = [WORLD, BASE, MARA_MOTOR1_LINK, MARA_MOTOR2_LINK, MARA_MOTOR3_LINK, MARA_MOTOR4_LINK, MARA_MOTOR5_LINK, MARA_MOTOR6_LINK, EE_LINK] EE_POINTS = np.asmatrix([[0, 0, 0]]) self.m_linkNames = copy.deepcopy(LINK_NAMES) self.ee_points = copy.deepcopy(EE_POINTS) self.m_jointOrder = copy.deepcopy(JOINT_ORDER) self.target_orientation = np.asarray( [0., 0.7071068, 0.7071068, 0.]) # arrow looking down [w, x, y, z] self.current_joints = np.array([0, 0, 0, 0, 0, 0]) _, self.ur_tree = tree_urdf.treeFromFile(urdfPath) # Retrieve a chain structure between the base and the start of the end effector. self.mara_chain = self.ur_tree.getChain( self.m_linkNames[0], self.m_linkNames[-1]) self.numJoints = self.mara_chain.getNrOfJoints() # Initialize a KDL Jacobian solver from the chain. self.jacSolver = ChainJntToJacSolver(self.mara_chain) def gripper_angle(self, angle=1.57): req = ControlFinger.Request() req.goal_angularposition = angle # self.gripper.call(req) # rclpy.spin_once(self) future = self.gripper.call_async(req) rclpy.spin_until_future_complete(self, future) # Analyze the result if future.result() is not None: self.get_logger().info('Goal accepted: %d: ' % future.result().goal_accepted) else: self.get_logger().error('Exception while calling service: %r' % future.exception()) def observation_callback(self, message): """ Callback method for the subscriber of JointTrajectoryControllerState """ self._observation_msg = message # self.get_logger().info(str(observation_msg)) def moving(self, joints): if type(joints) is list: joints = np.array(joints) # lift arm step1 = copy.deepcopy(self.current_joints) step1[1] = 0 self.moving_like_robot(step1) # rotate step2 = step1 step2[0] = joints[0] self.moving_like_robot(step2) # stetch arm self.moving_like_robot(joints) def moving_like_robot(self, joints): STEPS = 10 source = self.current_joints diff = joints - source # print('diff, ',diff) step_size = diff / STEPS for i in range(1, 11): self.stretch(source + i * step_size) time.sleep(0.1) self.current_joints = copy.deepcopy(joints) def stretch(self, joints): # m_jointOrder = copy.deepcopy(JOINT_ORDER) self.pub.publish(ut_mara.getTrajectoryMessage( joints, self.m_jointOrder, 0.1)) rclpy.spin_once(self) def take_observation(self, targetPosition): """ Take observation from the environment and return it. :return: state. """ # # Take an observation rclpy.spin_once(self) self.ros_clock = rclpy.clock.Clock().now().nanoseconds obs_message = self._observation_msg # Check that the observation is not prior to the action while obs_message is None or int(str(obs_message.header.stamp.sec)+(str(obs_message.header.stamp.nanosec))) < self.ros_clock: rclpy.spin_once(self) obs_message = self._observation_msg # Collect the end effector points and velocities in cartesian coordinates for the processObservations state. # Collect the present joint angles and velocities from ROS for the state. agent = {'jointOrder': self.m_jointOrder} lastObservations = ut_mara.processObservations(obs_message, agent) # Set observation to None after it has been read. self._observation_msg = None # Get Jacobians from present joint angles and KDL trees # The Jacobians consist of a 6x6 matrix getting its from from # (joint angles) x (len[x, y, z] + len[roll, pitch, yaw]) ee_link_jacobians = ut_mara.getJacobians( lastObservations, self.numJoints, self.jacSolver) if self.m_linkNames[-1] is None: print("End link is empty!!") return None else: translation, rot = general_utils.forwardKinematics(self.mara_chain, self.m_linkNames, lastObservations[:self.numJoints], # use the base_robot coordinate system baseLink=self.m_linkNames[0], endLink=self.m_linkNames[-1]) current_eePos_tgt = np.ndarray.flatten( general_utils.getEePoints(self.ee_points, translation, rot).T) eePos_points = current_eePos_tgt - targetPosition eeVelocities = ut_mara.getEePointsVelocities( ee_link_jacobians, self.ee_points, rot, lastObservations) # Concatenate the information that defines the robot state # vector, typically denoted asrobot_id 'x'. # state = np.r_[np.reshape(lastObservations, -1), # np.reshape(eePos_points, -1), # np.reshape(eeVelocities, -1), # np.reshape(current_eePos_tgt,-1), # np.reshape(rot.reshape(1, 9),-1)] # #np.reshape(self.targetPosition,-1)] # return state # sample data. # translation, [[-0.67344571 0.00105318 0.3273965 ]] rot, [[ 1.28011341e-06 -5.88501156e-01 -8.08496376e-01] # [-1.00000000e+00 -3.34320541e-07 -1.33997557e-06] # [ 5.18280224e-07 8.08496376e-01 -5.88501156e-01]] # [-0.67344571 0.00105318 0.3273965 ] # print('translation,',translation,' rot,',rot) return current_eePos_tgt def delete_can(self, target_name): # delete entity while not self.delete_entity_cli.wait_for_service(timeout_sec=1.0): self.get_logger().info('/reset_simulation service not available, waiting again...') req = DeleteEntity.Request() req.name = target_name delete_future = self.delete_entity_cli.call_async(req) rclpy.spin_until_future_complete(self, delete_future) if delete_future.result() is not None: self.get_logger().info('delete_future response: %r' % delete_future.result()) def spawn_target(self, urdf_obj, position): # self.targetPosition = self.sample_position() self.targetPosition = position while not self.spawn_cli.wait_for_service(timeout_sec=1.0): self.get_logger().info('/spawn_entity service not available, waiting again...') # modelXml = self.getTargetSdf() # modelXml = self.load_random_urdf(urdf_obj) modelXml = self.load_coke_can() pose = Pose() pose.position.x = self.targetPosition[0] pose.position.y = self.targetPosition[1] pose.position.z = self.targetPosition[2] pose.orientation.x = self.target_orientation[1] pose.orientation.y = self.target_orientation[2] pose.orientation.z = self.target_orientation[3] pose.orientation.w = self.target_orientation[0] # override previous spawn_request element. self.spawn_request = SpawnEntity.Request() self.spawn_request.name = urdf_obj self.spawn_request.xml = modelXml self.spawn_request.robot_namespace = "" self.spawn_request.initial_pose = pose self.spawn_request.reference_frame = "world" # ROS2 Spawn Entity target_future = self.spawn_cli.call_async(self.spawn_request) rclpy.spin_until_future_complete(self, target_future) if target_future.result() is not None: print('spawn_request response: %r' % target_future.result()) return pose def load_coke_can(self): modelXml = """<?xml version='1.0'?> <sdf version='1.5'> <model name="can1"> <include> <static>false</static> <uri>model://coke_can</uri> </include> </model> </sdf>""" return modelXml def getTargetSdf(self): modelXml = """<?xml version='1.0'?> <sdf version='1.6'> <model name='target'> <link name='cylinder0'> <pose frame=''>0 0 0 0 0 0</pose> <inertial> <pose frame=''>0 0 0 0 0 0</pose> <mass>5</mass> <inertia> <ixx>1</ixx> <ixy>0</ixy> <ixz>0</ixz> <iyy>1</iyy> <iyz>0</iyz> <izz>1</izz> </inertia> </inertial> <gravity>1</gravity> <velocity_decay/> <self_collide>1</self_collide> <enable_wind>0</enable_wind> <kinematic>1</kinematic> <visual name='cylinder0_visual'> <pose frame=''>0 0 0 0 0 0</pose> <geometry> <sphere> <radius>0.01</radius> </sphere> </geometry> <material> <script> <name>Gazebo/Green</name> <uri>file://media/materials/scripts/gazebo.material</uri> </script> <shader type='pixel'/> </material> <transparency>0.1</transparency> <cast_shadows>1</cast_shadows> </visual> </link> <static>0</static> <allow_auto_disable>1</allow_auto_disable> </model> </sdf>""" return modelXml def sample_position(self): # [ -0.5 , 0.2 , 0.1 ], [ -0.5 , -0.2 , 0.1 ] #sample data. initial 2 points in original setup. pos = [-1 * np.random.uniform(0.1, 0.6), np.random.uniform(0.1, 0.6), 0.15] print('object pos, ', pos) return pos # sample_x = np.random.uniform(0,1) # if sample > 0.5: # return [ -0.8 , 0.0 , 0.1 ] # else: # return [ -0.5 , 0.0 , 0.1 ] def load_random_urdf(self, obj): urdfPath = get_prefix_path( "mara_description") + "/share/mara_description/random_urdfs/" + obj urdf_file = open(urdfPath, "r") urdf_string = urdf_file.read() print("urdf_string:", urdf_string) return urdf_string def get_img(self, msg): # print(type(msg.data)) # print(len(msg.data)) self.raw_img = msg.data # if self.capturing: # img = np.array(msg.data).reshape((480, 640, 3)) # self.image = cv2.rotate(img, cv2.ROTATE_180) # #image still upside down. Need to rotate 180 degree? # if FLAG_DEBUG_CAMERA: # image = cv2.cvtColor(self.image, cv2.COLOR_RGB2BGR) # cv2.imshow('RS D435 Camera Image', image) # key = cv2.waitKey(1) # # Press esc or 'q' to close the image window # if key & 0xFF == ord('q') or key == 27: # cv2.destroyAllWindows() def captureImage(self): img = np.array(self.raw_img).reshape((480, 640, 3)) self.image = cv2.rotate(img, cv2.ROTATE_180) def get_contact(self, msg): ''' Retrieve contact points for gripper fingers ''' if msg.collision1_name in ['mara::left_inner_finger::left_inner_finger_collision', 'mara::right_inner_finger::right_inner_finger_collision']: collision1_side = msg.collision1_name contact1_positions = len(msg.contact_positions) # print(msg.collision1_name) # print(len(msg.contact_positions)) def generate_joints_for_length(args=None): rclpy.init(args=args) robot = Robot() rclpy.spin_once(robot) STEP = 0.01 data_frame = pd.DataFrame(columns=['m2', 'm3', 'm5', 'x', 'y', 'z']) # can we fix motor 1 4,6, to train free moving arm on a line? for change in np.arange(-0.3, 1, STEP): # # sample data, [-np.pi/2, 0.5, -.5, 0, -1.2, 0] m2 = 0+change m3 = -np.pi/2+change m5 = -np.pi/2+change robot.stretch(np.array([-np.pi/2, m2, m3, 0, m5, 0])) rclpy.spin_once(robot) rclpy.spin_once(robot) current_eePos_tgt = robot.take_observation([0, 0, 0]) rclpy.spin_once(robot) if 0 <= current_eePos_tgt[2] < 1: data = [m2, m3, m5] data.extend(current_eePos_tgt) # print('data,', data) df = pd.Series(data, index=data_frame.columns) # print('df,', df) data_frame = data_frame.append(df, ignore_index=True) robot.get_logger().info(str(data)) data_frame.to_csv('../resource/joints_xyz.csv', index=False) change = 1 robot.stretch( np.array([-np.pi/2, 0+change, -np.pi/2+change, 0, -np.pi/2+change, 0])) rclpy.spin_once(robot) current_eePos_tgt = robot.take_observation([0, 0, 0]) rclpy.spin_once(robot) # print('current_eePos_tgt, ', current_eePos_tgt) robot.destroy_node() rclpy.shutdown() print('END generate_joints_for_length().') def generate_joints_for_length_core(robot): STEP = 0.01 for change in np.arange(-0.3, 1, STEP): m2 = 0+change m3 = -np.pi/2+change m5 = -np.pi/2+change robot.stretch(np.array([-np.pi/2, m2, m3, 0, m5, 0])) rclpy.spin_once(robot) end_effector_pose = robot.take_observation([0, 0, 0]) def generate_joints_for_line_outdated(args=None): rclpy.init(args=args) robot = Robot() rclpy.spin_once(robot) STEP = 0.05 data_frame = pd.DataFrame(columns=['m2', 'm3', 'm5', 'x', 'y', 'z']) # can we fix motor 1 4,6, to train free moving arm on a line? for m2 in np.arange(0, 0.2, STEP): for m3 in np.arange(-np.pi/2+0.5, -np.pi/2-0.1, -1*STEP): for m5 in np.arange(0, -np.pi/2-0.5, -1*STEP): # sample data, [-np.pi/2, 0.5, -.5, 0, -1.2, 0] robot.stretch(np.array([-np.pi/2, m2, m3, 0, m5, 0])) rclpy.spin_once(robot) rclpy.spin_once(robot) current_eePos_tgt = robot.take_observation([0, 0, 0]) rclpy.spin_once(robot) if 0.08 <= current_eePos_tgt[2] < 0.12: data = [m2, m3, m5] data.extend(current_eePos_tgt) # print('data,', data) df = pd.Series(data, index=data_frame.columns) # print('df,', df) data_frame = data_frame.append(df, ignore_index=True) robot.get_logger().info(str(data)) data_frame.to_csv('../resource/joints_xyz.csv', index=False) robot.stretch(np.array([-np.pi/2, 0, -np.pi/2-0.1, 0, -np.pi/2-0.5, 0])) rclpy.spin_once(robot) current_eePos_tgt = robot.take_observation([0, 0, 0]) rclpy.spin_once(robot) print('current_eePos_tgt, ', current_eePos_tgt) robot.destroy_node() rclpy.shutdown() print('END generate_joints_for_line().') def drop_coke_can(robot=None): if robot is None: rclpy.init() robot = Robot() rclpy.spin_once(robot) obj = "coke0" robot.delete_can(obj) pose = robot.spawn_target(obj, robot.sample_position()) rclpy.spin_once(robot) return pose def drop_coke_can_on(robot, position): obj = "coke0" robot.delete_can(obj) pose = robot.spawn_target(obj, position) rclpy.spin_once(robot) return pose # pos, [[-1.05369001e-03 1.92728881e-05 1.11664069e+00]] rot: [[ 1.00000000e+00 -4.47419942e-06 -2.23629828e-11] # [ 4.47419942e-06 1.00000000e+00 2.87694329e-05] # [-1.06357197e-10 -2.87694329e-05 1.00000000e+00]] # print(rot[0, 1]) # print(general_utils.inverseKinematics(mara_chain, pos, rot)) # can't understand rot and generate data for that. # def inverseKinematics(robotChain, pos, rot, qGuess=None, minJoints=None, maxJoints=None): def grab_can_and_drop_delete_entity(robot, pose): if robot is None: rclpy.init() robot = Robot() rclpy.spin_once(robot) joints = load_joints() x, y, z = pose.position.x, pose.position.y, pose.position.z distance = np.sqrt(x*x+y*y) rotation = np.arctan2(-x, y) print("x, y, rotation :", x, y, rotation) # reverse sign of x to let it handle things appear on left hand side. +y move along green axis. m1 = -np.pi + rotation joints = search_joints(joints, distance, 0.2) # joints = calculate_joints() if joints is not None: m2 = joints['m2'] m3 = joints['m3'] m5 = joints['m5'] print('distance m1 m2 m3 m5:', distance, m1, m2, m3, m5) robot.moving(np.array([m1, m2, m3, 0.0, m5, 0.0])) # rclpy.spin_once(robot) # # robot.stretch(np.array([m1, m2, m3, 0.0, m5, 0.0])) # rclpy.spin_once(robot) # rclpy.spin_once(robot) else: print('No Joints found.') robot.gripper_angle(0.3) time.sleep(3) robot.moving(np.array([m1+np.pi, m2, m3, 0.0, m5, 0.0])) robot.gripper_angle(1.57) def look_for_can(robot): robot.moving([-np.pi*3/4, 0, 0, 0, -np.pi, 0]) # time.sleep(2) print('look_for_can, moved') # robot.image # robot.img def search_joints(joints, x_distance, z): data = None idx = np.where((x_distance < joints['x']) & ( joints['x'] < x_distance+0.1) & (joints['z'] < z)) if np.sum(idx) > 0: # print('data count:', np.sum(idx)) data = joints.loc[idx][['m2', 'm3', 'm5']].iloc[0] # data = joints.loc[idx][['m2','m3','m5']].median() return data def load_joints(): joints_df = pd.read_csv(get_package_share_directory( 'recycler_package')+'/resource/joints_xyz.csv') joints_df['x'] = joints_df['x']*-1 joints = joints_df.sort_values(by='x') # joints = joints_df.drop('index', axis=1) return joints def main(args=None): rclpy.init(args=args) robot = Robot() rclpy.spin_once(robot) for i in range(5, 12): ## for images collection if FLAG_DEBUG_CAMERA: pose = drop_coke_can_on(robot, [-0.05*i, 0.05*i, 0.15]) else: pose = drop_coke_can(robot) if FLAG_DEBUG_CAMERA: look_for_can(robot) time.sleep(1) robot.captureImage() image = robot.image cv2.imwrite(str(i)+'.png', image) image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) cv2.imshow('RS D435 Camera Image', image) key = cv2.waitKey(1) # Press esc or 'q' to close the image window if key & 0xFF == ord('q') or key == 27: cv2.destroyAllWindows() grab_can_and_drop_delete_entity(robot, pose) def main_(args=None): generate_joints_for_length(args) if __name__ == '__main__': main()
[ "gym_gazebo2.utils.ut_mara.getTrajectoryMessage", "rclpy.spin_once", "numpy.arctan2", "gym_gazebo2.utils.ut_mara.getJacobians", "numpy.sum", "gym_gazebo2.utils.ut_mara.processObservations", "rclpy.shutdown", "numpy.arange", "cv2.imshow", "pandas.DataFrame", "gym_gazebo2.utils.general_utils.forwa...
[((1259, 1283), 'gym.logger.set_level', 'gym.logger.set_level', (['(40)'], {}), '(40)\n', (1279, 1283), False, 'import gym\n'), ((16836, 16857), 'rclpy.init', 'rclpy.init', ([], {'args': 'args'}), '(args=args)\n', (16846, 16857), False, 'import rclpy\n'), ((16882, 16904), 'rclpy.spin_once', 'rclpy.spin_once', (['robot'], {}), '(robot)\n', (16897, 16904), False, 'import rclpy\n'), ((16939, 16994), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['m2', 'm3', 'm5', 'x', 'y', 'z']"}), "(columns=['m2', 'm3', 'm5', 'x', 'y', 'z'])\n", (16951, 16994), True, 'import pandas as pd\n'), ((17081, 17105), 'numpy.arange', 'np.arange', (['(-0.3)', '(1)', 'STEP'], {}), '(-0.3, 1, STEP)\n', (17090, 17105), True, 'import numpy as np\n'), ((18016, 18038), 'rclpy.spin_once', 'rclpy.spin_once', (['robot'], {}), '(robot)\n', (18031, 18038), False, 'import rclpy\n'), ((18101, 18123), 'rclpy.spin_once', 'rclpy.spin_once', (['robot'], {}), '(robot)\n', (18116, 18123), False, 'import rclpy\n'), ((18208, 18224), 'rclpy.shutdown', 'rclpy.shutdown', ([], {}), '()\n', (18222, 18224), False, 'import rclpy\n'), ((18353, 18377), 'numpy.arange', 'np.arange', (['(-0.3)', '(1)', 'STEP'], {}), '(-0.3, 1, STEP)\n', (18362, 18377), True, 'import numpy as np\n'), ((18670, 18691), 'rclpy.init', 'rclpy.init', ([], {'args': 'args'}), '(args=args)\n', (18680, 18691), False, 'import rclpy\n'), ((18716, 18738), 'rclpy.spin_once', 'rclpy.spin_once', (['robot'], {}), '(robot)\n', (18731, 18738), False, 'import rclpy\n'), ((18773, 18828), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['m2', 'm3', 'm5', 'x', 'y', 'z']"}), "(columns=['m2', 'm3', 'm5', 'x', 'y', 'z'])\n", (18785, 18828), True, 'import pandas as pd\n'), ((18911, 18934), 'numpy.arange', 'np.arange', (['(0)', '(0.2)', 'STEP'], {}), '(0, 0.2, STEP)\n', (18920, 18934), True, 'import numpy as np\n'), ((19957, 19979), 'rclpy.spin_once', 'rclpy.spin_once', (['robot'], {}), '(robot)\n', (19972, 19979), False, 'import rclpy\n'), ((20042, 20064), 'rclpy.spin_once', 'rclpy.spin_once', (['robot'], {}), '(robot)\n', (20057, 20064), False, 'import rclpy\n'), ((20147, 20163), 'rclpy.shutdown', 'rclpy.shutdown', ([], {}), '()\n', (20161, 20163), False, 'import rclpy\n'), ((20450, 20472), 'rclpy.spin_once', 'rclpy.spin_once', (['robot'], {}), '(robot)\n', (20465, 20472), False, 'import rclpy\n'), ((20624, 20646), 'rclpy.spin_once', 'rclpy.spin_once', (['robot'], {}), '(robot)\n', (20639, 20646), False, 'import rclpy\n'), ((21402, 21424), 'numpy.sqrt', 'np.sqrt', (['(x * x + y * y)'], {}), '(x * x + y * y)\n', (21409, 21424), True, 'import numpy as np\n'), ((21434, 21451), 'numpy.arctan2', 'np.arctan2', (['(-x)', 'y'], {}), '(-x, y)\n', (21444, 21451), True, 'import numpy as np\n'), ((22183, 22196), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)\n', (22193, 22196), False, 'import time\n'), ((22524, 22620), 'numpy.where', 'np.where', (["((x_distance < joints['x']) & (joints['x'] < x_distance + 0.1) & (joints[\n 'z'] < z))"], {}), "((x_distance < joints['x']) & (joints['x'] < x_distance + 0.1) & (\n joints['z'] < z))\n", (22532, 22620), True, 'import numpy as np\n'), ((23134, 23155), 'rclpy.init', 'rclpy.init', ([], {'args': 'args'}), '(args=args)\n', (23144, 23155), False, 'import rclpy\n'), ((23180, 23202), 'rclpy.spin_once', 'rclpy.spin_once', (['robot'], {}), '(robot)\n', (23195, 23202), False, 'import rclpy\n'), ((4057, 4081), 'numpy.asmatrix', 'np.asmatrix', (['[[0, 0, 0]]'], {}), '([[0, 0, 0]])\n', (4068, 4081), True, 'import numpy as np\n'), ((4110, 4135), 'copy.deepcopy', 'copy.deepcopy', (['LINK_NAMES'], {}), '(LINK_NAMES)\n', (4123, 4135), False, 'import copy\n'), ((4161, 4185), 'copy.deepcopy', 'copy.deepcopy', (['EE_POINTS'], {}), '(EE_POINTS)\n', (4174, 4185), False, 'import copy\n'), ((4214, 4240), 'copy.deepcopy', 'copy.deepcopy', (['JOINT_ORDER'], {}), '(JOINT_ORDER)\n', (4227, 4240), False, 'import copy\n'), ((4275, 4319), 'numpy.asarray', 'np.asarray', (['[0.0, 0.7071068, 0.7071068, 0.0]'], {}), '([0.0, 0.7071068, 0.7071068, 0.0])\n', (4285, 4319), True, 'import numpy as np\n'), ((4396, 4424), 'numpy.array', 'np.array', (['[0, 0, 0, 0, 0, 0]'], {}), '([0, 0, 0, 0, 0, 0])\n', (4404, 4424), True, 'import numpy as np\n'), ((4452, 4484), 'gym_gazebo2.utils.tree_urdf.treeFromFile', 'tree_urdf.treeFromFile', (['urdfPath'], {}), '(urdfPath)\n', (4474, 4484), False, 'from gym_gazebo2.utils import ut_generic, ut_launch, ut_mara, ut_math, ut_gazebo, tree_urdf, general_utils\n'), ((4819, 4855), 'PyKDL.ChainJntToJacSolver', 'ChainJntToJacSolver', (['self.mara_chain'], {}), '(self.mara_chain)\n', (4838, 4855), False, 'from PyKDL import ChainJntToJacSolver\n'), ((4912, 4935), 'hrim_actuator_gripper_srvs.srv.ControlFinger.Request', 'ControlFinger.Request', ([], {}), '()\n', (4933, 4935), False, 'from hrim_actuator_gripper_srvs.srv import ControlFinger\n'), ((5097, 5143), 'rclpy.spin_until_future_complete', 'rclpy.spin_until_future_complete', (['self', 'future'], {}), '(self, future)\n', (5129, 5143), False, 'import rclpy\n'), ((5794, 5828), 'copy.deepcopy', 'copy.deepcopy', (['self.current_joints'], {}), '(self.current_joints)\n', (5807, 5828), False, 'import copy\n'), ((6390, 6411), 'copy.deepcopy', 'copy.deepcopy', (['joints'], {}), '(joints)\n', (6403, 6411), False, 'import copy\n'), ((6630, 6651), 'rclpy.spin_once', 'rclpy.spin_once', (['self'], {}), '(self)\n', (6645, 6651), False, 'import rclpy\n'), ((6850, 6871), 'rclpy.spin_once', 'rclpy.spin_once', (['self'], {}), '(self)\n', (6865, 6871), False, 'import rclpy\n'), ((7538, 7585), 'gym_gazebo2.utils.ut_mara.processObservations', 'ut_mara.processObservations', (['obs_message', 'agent'], {}), '(obs_message, agent)\n', (7565, 7585), False, 'from gym_gazebo2.utils import ut_generic, ut_launch, ut_mara, ut_math, ut_gazebo, tree_urdf, general_utils\n'), ((7910, 7980), 'gym_gazebo2.utils.ut_mara.getJacobians', 'ut_mara.getJacobians', (['lastObservations', 'self.numJoints', 'self.jacSolver'], {}), '(lastObservations, self.numJoints, self.jacSolver)\n', (7930, 7980), False, 'from gym_gazebo2.utils import ut_generic, ut_launch, ut_mara, ut_math, ut_gazebo, tree_urdf, general_utils\n'), ((10198, 10220), 'gazebo_msgs.srv.DeleteEntity.Request', 'DeleteEntity.Request', ([], {}), '()\n', (10218, 10220), False, 'from gazebo_msgs.srv import DeleteEntity\n'), ((10323, 10376), 'rclpy.spin_until_future_complete', 'rclpy.spin_until_future_complete', (['self', 'delete_future'], {}), '(self, delete_future)\n', (10355, 10376), False, 'import rclpy\n'), ((10968, 10974), 'geometry_msgs.msg.Pose', 'Pose', ([], {}), '()\n', (10972, 10974), False, 'from geometry_msgs.msg import Pose\n'), ((11426, 11447), 'gazebo_msgs.srv.SpawnEntity.Request', 'SpawnEntity.Request', ([], {}), '()\n', (11445, 11447), False, 'from gazebo_msgs.srv import SpawnEntity\n'), ((11788, 11841), 'rclpy.spin_until_future_complete', 'rclpy.spin_until_future_complete', (['self', 'target_future'], {}), '(self, target_future)\n', (11820, 11841), False, 'import rclpy\n'), ((16263, 16294), 'cv2.rotate', 'cv2.rotate', (['img', 'cv2.ROTATE_180'], {}), '(img, cv2.ROTATE_180)\n', (16273, 16294), False, 'import cv2\n'), ((17327, 17349), 'rclpy.spin_once', 'rclpy.spin_once', (['robot'], {}), '(robot)\n', (17342, 17349), False, 'import rclpy\n'), ((17358, 17380), 'rclpy.spin_once', 'rclpy.spin_once', (['robot'], {}), '(robot)\n', (17373, 17380), False, 'import rclpy\n'), ((17451, 17473), 'rclpy.spin_once', 'rclpy.spin_once', (['robot'], {}), '(robot)\n', (17466, 17473), False, 'import rclpy\n'), ((17940, 18026), 'numpy.array', 'np.array', (['[-np.pi / 2, 0 + change, -np.pi / 2 + change, 0, -np.pi / 2 + change, 0]'], {}), '([-np.pi / 2, 0 + change, -np.pi / 2 + change, 0, -np.pi / 2 +\n change, 0])\n', (17948, 18026), True, 'import numpy as np\n'), ((18529, 18551), 'rclpy.spin_once', 'rclpy.spin_once', (['robot'], {}), '(robot)\n', (18544, 18551), False, 'import rclpy\n'), ((18954, 19010), 'numpy.arange', 'np.arange', (['(-np.pi / 2 + 0.5)', '(-np.pi / 2 - 0.1)', '(-1 * STEP)'], {}), '(-np.pi / 2 + 0.5, -np.pi / 2 - 0.1, -1 * STEP)\n', (18963, 19010), True, 'import numpy as np\n'), ((19894, 19961), 'numpy.array', 'np.array', (['[-np.pi / 2, 0, -np.pi / 2 - 0.1, 0, -np.pi / 2 - 0.5, 0]'], {}), '([-np.pi / 2, 0, -np.pi / 2 - 0.1, 0, -np.pi / 2 - 0.5, 0])\n', (19902, 19961), True, 'import numpy as np\n'), ((20273, 20285), 'rclpy.init', 'rclpy.init', ([], {}), '()\n', (20283, 20285), False, 'import rclpy\n'), ((20318, 20340), 'rclpy.spin_once', 'rclpy.spin_once', (['robot'], {}), '(robot)\n', (20333, 20340), False, 'import rclpy\n'), ((21225, 21237), 'rclpy.init', 'rclpy.init', ([], {}), '()\n', (21235, 21237), False, 'import rclpy\n'), ((21270, 21292), 'rclpy.spin_once', 'rclpy.spin_once', (['robot'], {}), '(robot)\n', (21285, 21292), False, 'import rclpy\n'), ((22214, 22258), 'numpy.array', 'np.array', (['[m1 + np.pi, m2, m3, 0.0, m5, 0.0]'], {}), '([m1 + np.pi, m2, m3, 0.0, m5, 0.0])\n', (22222, 22258), True, 'import numpy as np\n'), ((22630, 22641), 'numpy.sum', 'np.sum', (['idx'], {}), '(idx)\n', (22636, 22641), True, 'import numpy as np\n'), ((5741, 5757), 'numpy.array', 'np.array', (['joints'], {}), '(joints)\n', (5749, 5757), True, 'import numpy as np\n'), ((6343, 6358), 'time.sleep', 'time.sleep', (['(0.1)'], {}), '(0.1)\n', (6353, 6358), False, 'import time\n'), ((6522, 6582), 'gym_gazebo2.utils.ut_mara.getTrajectoryMessage', 'ut_mara.getTrajectoryMessage', (['joints', 'self.m_jointOrder', '(0.1)'], {}), '(joints, self.m_jointOrder, 0.1)\n', (6550, 6582), False, 'from gym_gazebo2.utils import ut_generic, ut_launch, ut_mara, ut_math, ut_gazebo, tree_urdf, general_utils\n'), ((7191, 7212), 'rclpy.spin_once', 'rclpy.spin_once', (['self'], {}), '(self)\n', (7206, 7212), False, 'import rclpy\n'), ((8145, 8314), 'gym_gazebo2.utils.general_utils.forwardKinematics', 'general_utils.forwardKinematics', (['self.mara_chain', 'self.m_linkNames', 'lastObservations[:self.numJoints]'], {'baseLink': 'self.m_linkNames[0]', 'endLink': 'self.m_linkNames[-1]'}), '(self.mara_chain, self.m_linkNames,\n lastObservations[:self.numJoints], baseLink=self.m_linkNames[0],\n endLink=self.m_linkNames[-1])\n', (8176, 8314), False, 'from gym_gazebo2.utils import ut_generic, ut_launch, ut_mara, ut_math, ut_gazebo, tree_urdf, general_utils\n'), ((8883, 8974), 'gym_gazebo2.utils.ut_mara.getEePointsVelocities', 'ut_mara.getEePointsVelocities', (['ee_link_jacobians', 'self.ee_points', 'rot', 'lastObservations'], {}), '(ee_link_jacobians, self.ee_points, rot,\n lastObservations)\n', (8912, 8974), False, 'from gym_gazebo2.utils import ut_generic, ut_launch, ut_mara, ut_math, ut_gazebo, tree_urdf, general_utils\n'), ((14883, 14910), 'numpy.random.uniform', 'np.random.uniform', (['(0.1)', '(0.6)'], {}), '(0.1, 0.6)\n', (14900, 14910), True, 'import numpy as np\n'), ((17279, 17319), 'numpy.array', 'np.array', (['[-np.pi / 2, m2, m3, 0, m5, 0]'], {}), '([-np.pi / 2, m2, m3, 0, m5, 0])\n', (17287, 17319), True, 'import numpy as np\n'), ((17645, 17686), 'pandas.Series', 'pd.Series', (['data'], {'index': 'data_frame.columns'}), '(data, index=data_frame.columns)\n', (17654, 17686), True, 'import pandas as pd\n'), ((18481, 18521), 'numpy.array', 'np.array', (['[-np.pi / 2, m2, m3, 0, m5, 0]'], {}), '([-np.pi / 2, m2, m3, 0, m5, 0])\n', (18489, 18521), True, 'import numpy as np\n'), ((19024, 19065), 'numpy.arange', 'np.arange', (['(0)', '(-np.pi / 2 - 0.5)', '(-1 * STEP)'], {}), '(0, -np.pi / 2 - 0.5, -1 * STEP)\n', (19033, 19065), True, 'import numpy as np\n'), ((21903, 21939), 'numpy.array', 'np.array', (['[m1, m2, m3, 0.0, m5, 0.0]'], {}), '([m1, m2, m3, 0.0, m5, 0.0])\n', (21911, 21939), True, 'import numpy as np\n'), ((22875, 22922), 'ament_index_python.packages.get_package_share_directory', 'get_package_share_directory', (['"""recycler_package"""'], {}), "('recycler_package')\n", (22902, 22922), False, 'from ament_index_python.packages import get_package_share_directory\n'), ((23500, 23513), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (23510, 23513), False, 'import time\n'), ((23646, 23684), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_RGB2BGR'], {}), '(image, cv2.COLOR_RGB2BGR)\n', (23658, 23684), False, 'import cv2\n'), ((23697, 23738), 'cv2.imshow', 'cv2.imshow', (['"""RS D435 Camera Image"""', 'image'], {}), "('RS D435 Camera Image', image)\n", (23707, 23738), False, 'import cv2\n'), ((23757, 23771), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (23768, 23771), False, 'import cv2\n'), ((3365, 3400), 'ros2pkg.api.get_prefix_path', 'get_prefix_path', (['"""mara_description"""'], {}), "('mara_description')\n", (3380, 3400), False, 'from ros2pkg.api import get_prefix_path\n'), ((14839, 14866), 'numpy.random.uniform', 'np.random.uniform', (['(0.1)', '(0.6)'], {}), '(0.1, 0.6)\n', (14856, 14866), True, 'import numpy as np\n'), ((15200, 15235), 'ros2pkg.api.get_prefix_path', 'get_prefix_path', (['"""mara_description"""'], {}), "('mara_description')\n", (15215, 15235), False, 'from ros2pkg.api import get_prefix_path\n'), ((16196, 16218), 'numpy.array', 'np.array', (['self.raw_img'], {}), '(self.raw_img)\n', (16204, 16218), True, 'import numpy as np\n'), ((19212, 19234), 'rclpy.spin_once', 'rclpy.spin_once', (['robot'], {}), '(robot)\n', (19227, 19234), False, 'import rclpy\n'), ((19251, 19273), 'rclpy.spin_once', 'rclpy.spin_once', (['robot'], {}), '(robot)\n', (19266, 19273), False, 'import rclpy\n'), ((19360, 19382), 'rclpy.spin_once', 'rclpy.spin_once', (['robot'], {}), '(robot)\n', (19375, 19382), False, 'import rclpy\n'), ((23897, 23920), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (23918, 23920), False, 'import cv2\n'), ((6897, 6916), 'rclpy.clock.Clock', 'rclpy.clock.Clock', ([], {}), '()\n', (6914, 6916), False, 'import rclpy\n'), ((8730, 8789), 'gym_gazebo2.utils.general_utils.getEePoints', 'general_utils.getEePoints', (['self.ee_points', 'translation', 'rot'], {}), '(self.ee_points, translation, rot)\n', (8755, 8789), False, 'from gym_gazebo2.utils import ut_generic, ut_launch, ut_mara, ut_math, ut_gazebo, tree_urdf, general_utils\n'), ((19156, 19196), 'numpy.array', 'np.array', (['[-np.pi / 2, m2, m3, 0, m5, 0]'], {}), '([-np.pi / 2, m2, m3, 0, m5, 0])\n', (19164, 19196), True, 'import numpy as np\n'), ((19600, 19641), 'pandas.Series', 'pd.Series', (['data'], {'index': 'data_frame.columns'}), '(data, index=data_frame.columns)\n', (19609, 19641), True, 'import pandas as pd\n')]
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Functions for plotting.""" import os import pickle import re import matplotlib.pyplot as plt import numpy as np import tensorflow as tf from tensorflow_graphics.projects.points_to_3Dobjects.utils import tf_utils from google3.pyglib import gfile def plot_to_image(figure): """Converts a matplotlib figure into a TF image e.g. for TensorBoard.""" figure.canvas.draw() width, height = figure.canvas.get_width_height() data_np = np.frombuffer(figure.canvas.tostring_rgb(), dtype='uint8') data_np = data_np.reshape([width, height, 3]) image = tf.expand_dims(data_np, 0) return image def resize_heatmap(centers, color=(1, 0, 0), stride=4): assert len(centers.shape) == 2 centers = np.repeat(np.repeat(centers, stride, axis=0), stride, axis=1) centers = np.expand_dims(centers, axis=-1) cmin, cmax = np.min(centers), np.max(centers) centers = np.concatenate([np.ones(centers.shape) * color[0], np.ones(centers.shape) * color[1], np.ones(centers.shape) * color[2], (centers-cmin)/cmax], axis=-1) return centers def plot_heatmaps(image, detections, figsize=5): """Plot.""" figure = plt.figure(figsize=(figsize, figsize)) plt.clf() width, height = image.shape[1], image.shape[0] if width != height: image = tf.image.pad_to_bounding_box(image, 0, 0, 640, 640) image = image.numpy() width, height = image.shape[1], image.shape[0] plt.imshow(np.concatenate([image.astype(float)/255.0, 1.0 * np.ones([height, width, 1])], axis=-1)) num_predicted_objects = detections['detection_classes'].numpy().shape[0] for object_id in range(num_predicted_objects): for k, color in [['centers', [0, 1, 0]] ]: class_id = int(detections['detection_classes'][object_id].numpy()) centers = detections[k][:, :, class_id].numpy() color = [[1, 0, 0], [0, 1, 0], [0, 0, 1]][object_id] plt.imshow(resize_heatmap(centers, color=color)) plt.axis('off') plt.tight_layout() return figure def draw_coordinate_frame(camera_intrinsic, pose_world2camera, dot): """Draw coordinate system frame.""" print(dot) width = camera_intrinsic[0, 2] * 2.0 height = camera_intrinsic[1, 2] * 2.0 plt.plot([0, width], [height / 4.0 * 3.0, height / 4.0 * 3.0], 'g--') plt.plot([width / 2.0, width / 2.0], [0.0, height], 'g--') camera_intrinsic = np.reshape(camera_intrinsic, [3, 3]) pose_world2camera = np.reshape(pose_world2camera, [3, 4]) frame = np.array([[0, 0, 0, 1], [0.1, 0, 0, 1], [0, 0.1, 0, 1], [0, 0, 0.1, 1]], dtype=np.float32).T # Shape: (4, 4) projected_frame = camera_intrinsic @ pose_world2camera @ frame projected_frame = projected_frame[0:2, :] / projected_frame[2, :] plt.plot(projected_frame[0, [0, 1]], projected_frame[1, [0, 1]], 'r-') plt.plot(projected_frame[0, [0, 2]], projected_frame[1, [0, 2]], 'g-') plt.plot(projected_frame[0, [0, 3]], projected_frame[1, [0, 3]], 'b-') dot_proj = camera_intrinsic @ \ pose_world2camera @ [dot[0, 0], dot[0, 1], dot[0, 2], 1.0] dot_proj /= dot_proj[2] print(dot_proj) plt.plot(dot_proj[0], dot_proj[1], 'y*') def plot_gt_boxes_2d(sample, shape_pointclouds, figsize=5): """Plot.""" _ = plt.figure(figsize=(figsize, figsize)) plt.clf() plt.imshow(sample['image']) # Plot ground truth boxes sample['detection_boxes'] = sample['groundtruth_boxes'].numpy() colors = ['r.', 'g.', 'b.'] for i in range(sample['num_boxes'].numpy()): shape_id = sample['shapes'][i] pointcloud = tf.transpose(shape_pointclouds[shape_id]) translation = sample['translations_3d'][i] rotation = tf.reshape(sample['rotations_3d'][i], [3, 3]) size = np.diag(sample['sizes_3d'][i]) trafo_pc = \ rotation @ size @ (pointcloud / 2.0) + tf.expand_dims(translation, 1) trafo_pc = tf.concat([trafo_pc, tf.ones([1, 512])], axis=0) projected_pointcloud = \ tf.reshape(sample['k'], [3, 3]) @ sample['rt'] @ trafo_pc projected_pointcloud /= projected_pointcloud[2, :] plt.plot(projected_pointcloud[0, :], projected_pointcloud[1, :], colors[i % 3]) y_min, x_min, y_max, x_max = sample['detection_boxes'][i] y_min *= sample['original_image_spatial_shape'][1].numpy() y_max *= sample['original_image_spatial_shape'][1].numpy() x_min *= sample['original_image_spatial_shape'][0].numpy() x_max *= sample['original_image_spatial_shape'][0].numpy() plt.plot([x_min, x_max, x_max, x_min, x_min], [y_min, y_min, y_max, y_max, y_min], linestyle='dashed') def show_sdf(sdf, figsize=5, resolution=32): _, axis = plt.subplots(1, 3, figsize=(3*figsize, figsize)) sdf = tf.reshape(sdf, [resolution, resolution, resolution]) for a in range(3): proj_sdf = tf.transpose(tf.reduce_min(sdf, axis=a)) c = axis[a].matshow(proj_sdf.numpy()) plt.colorbar(c, ax=axis[a]) def plot_gt_boxes_3d(sample, shape_pointclouds, figsize=5): """Plot.""" intrinsics = sample['k'].numpy() pose_world2camera = sample['rt'].numpy() _ = plt.figure(figsize=(figsize, figsize)) plt.clf() intrinsics = np.reshape(intrinsics, [3, 3]) pose_world2camera = np.reshape(pose_world2camera, [3, 4]) # Plot ground truth boxes # num_boxes = sample['groundtruth_boxes'].shape[0] colors = ['r', 'g', 'b', 'c', 'm', 'y'] colors2 = ['r.', 'g.', 'b.'] for i in [2, 1, 0]: shape_id = sample['shapes'][i] pointcloud = tf.transpose(shape_pointclouds[shape_id]) translation = sample['translations_3d'][i] rotation = tf.reshape(sample['rotations_3d'][i], [3, 3]) size = np.diag(sample['sizes_3d'][i]) trafo_pc = \ rotation @ size @ (pointcloud / 2.0) + tf.expand_dims(translation, 1) trafo_pc = tf.concat([trafo_pc, tf.ones([1, 512])], axis=0) projected_pointcloud = \ tf.reshape(sample['k'], [3, 3]) @ sample['rt'] @ trafo_pc projected_pointcloud /= projected_pointcloud[2, :] plt.plot(projected_pointcloud[0, :], projected_pointcloud[1, :], 'w.', markersize=5) plt.plot(projected_pointcloud[0, :], projected_pointcloud[1, :], colors2[i], markersize=3) predicted_pose_obj2world = np.eye(4) predicted_pose_obj2world[0:3, 0:3] = \ tf.reshape(sample['rotations_3d'][i], [3, 3]).numpy() predicted_pose_obj2world[0:3, 3] = sample['translations_3d'][i].numpy() draw_bounding_box_3d(sample['sizes_3d'][i].numpy(), predicted_pose_obj2world, intrinsics, pose_world2camera, linestyle='solid', color='w', linewidth=3) draw_bounding_box_3d(sample['sizes_3d'][i].numpy(), predicted_pose_obj2world, intrinsics, pose_world2camera, linestyle='solid', color=colors[i], linewidth=1) # draw_coordinate_frame(intrinsics, pose_world2camera, sample['dot']) CLASSES = ('chair', 'sofa', 'table', 'bottle', 'bowl', 'mug', 'bowl', 'mug') def plot_boxes_2d(image, sample, predictions, projection=True, groundtruth=True, figsize=5, class_id_to_name=CLASSES): """Plot.""" batch_id = 0 figure = plt.figure(figsize=(figsize, figsize)) plt.clf() plt.imshow(image) if projection: points = predictions['projected_pointclouds'].numpy() colors = ['r.', 'g.', 'b.', 'c.', 'm.', 'y.'] # print('HERE:', points.shape) for i in range(points.shape[0]): # print(i, points.shape) plt.plot(points[i, :, 0], points[i, :, 1], colors[int(predictions['detection_classes'][i])]) # Plot ground truth boxes if groundtruth: sample['detection_boxes'] = sample['groundtruth_boxes'][batch_id].numpy() for i in range(sample['detection_boxes'].shape[0]): y_min, x_min, y_max, x_max = sample['detection_boxes'][i] y_min *= sample['original_image_spatial_shape'][batch_id][1].numpy() y_max *= sample['original_image_spatial_shape'][batch_id][1].numpy() x_min *= sample['original_image_spatial_shape'][batch_id][0].numpy() x_max *= sample['original_image_spatial_shape'][batch_id][0].numpy() plt.plot([x_min, x_max, x_max, x_min, x_min], [y_min, y_min, y_max, y_max, y_min], linestyle='dashed') # Plot predicted boxes colors = ['r', 'g', 'b', 'c', 'm', 'y'] for i in range(predictions['detection_boxes'].shape[0]): x_min, y_min, x_max, y_max = predictions['detection_boxes'][i] plt.plot([x_min, x_max, x_max, x_min, x_min], [y_min, y_min, y_max, y_max, y_min], linestyle='solid', color=colors[int(predictions['detection_classes'][i])]) plt.text(x_min, y_min, str(i) + '_' + class_id_to_name[int(predictions['detection_classes'][i])] + str(int(predictions['detection_scores'][i]*1000) / 1000.0)) plt.axis('off') plt.tight_layout() return figure def plot_boxes_3d(image, sample, predictions, figsize=5, groundtruth=True, class_id_to_name=CLASSES): """Plot.""" batch_id = 0 intrinsics = sample['k'][batch_id].numpy() pose_world2camera = sample['rt'][batch_id].numpy() figure = plt.figure(figsize=(figsize, figsize)) plt.clf() plt.imshow(image) intrinsics = np.reshape(intrinsics, [3, 3]) pose_world2camera = np.reshape(pose_world2camera, [3, 4]) # Plot ground truth boxes if groundtruth: num_boxes = sample['groundtruth_boxes'][batch_id].shape[0] sample['detection_boxes'] = sample['groundtruth_boxes'][batch_id].numpy() colors = ['c', 'm', 'y'] for i in range(num_boxes): predicted_pose_obj2world = np.eye(4) predicted_pose_obj2world[0:3, 0:3] = \ tf.reshape(sample['rotations_3d'][batch_id][i], [3, 3]).numpy() predicted_pose_obj2world[0:3, 3] = \ sample['translations_3d'][batch_id][i].numpy() draw_bounding_box_3d(sample['sizes_3d'][batch_id][i].numpy(), predicted_pose_obj2world, intrinsics, pose_world2camera, linestyle='dashed', color=colors[i % 3]) y_min, x_min, y_max, x_max = sample['detection_boxes'][i] y_min *= sample['original_image_spatial_shape'][batch_id][1].numpy() y_max *= sample['original_image_spatial_shape'][batch_id][1].numpy() x_min *= sample['original_image_spatial_shape'][batch_id][0].numpy() x_max *= sample['original_image_spatial_shape'][batch_id][0].numpy() plt.text(x_max, y_min, str(i) + '_gt_' + \ class_id_to_name[int(sample['groundtruth_valid_classes'][batch_id][i])]) # Plot predicted boxes colors = ['r', 'g', 'b', 'c', 'm', 'y', 'c', 'm', 'y', 'c', 'm', 'y'] num_boxes = predictions['rotations_3d'].shape[0] for i in range(num_boxes): predicted_pose_obj2world = np.eye(4) predicted_pose_obj2world[0:3, 0:3] = predictions['rotations_3d'][i].numpy() predicted_pose_obj2world[0:3, 3] = predictions['translations_3d'][i].numpy() draw_bounding_box_3d(predictions['sizes_3d'].numpy()[i], predicted_pose_obj2world, intrinsics, pose_world2camera, linestyle='solid', color=colors[int(predictions['detection_classes'][i])]) x_min, y_min, x_max, y_max = predictions['detection_boxes'][i] plt.text(x_min, y_min, str(i) + '_' + class_id_to_name[int(predictions['detection_classes'][i])] + str(int(predictions['detection_scores'][i] * 1000) / 1000.0)) plt.axis('off') plt.tight_layout() return figure def plot_detections( image, intrinsics, pose_world2camera, detections, labels, figsize=0.1): """Plot.""" figure = plt.figure(figsize=(figsize, figsize)) plt.clf() plt.imshow(np.concatenate([image.astype(float)/255.0, 0.2 * np.ones([256, 256, 1])], axis=-1)) # Plot heatmaps num_predicted_objects = detections['detection_classes'].numpy().shape[0] for object_id in range(num_predicted_objects): for k, color in [['centers_sigmoid', [0, 1, 0]], ['centers_nms', [1, 0, 0]]]: class_id = int(detections['detection_classes'][object_id].numpy()) centers = detections[k][:, :, class_id].numpy() plt.imshow(resize_heatmap(centers, color=color)) intrinsics = np.reshape(intrinsics, [3, 3]) pose_world2camera = np.reshape(pose_world2camera, [3, 4]) for j, [boxes, style] in enumerate([[labels, 'dashed'], [detections, 'solid']]): number_of_boxes = boxes['detection_boxes'].shape[0] for i in range(number_of_boxes): predicted_pose_obj2world = np.eye(4) predicted_pose_obj2world[0:3, 0:3] = boxes['rotations_3d'][i].numpy() predicted_pose_obj2world[0:3, 3] = boxes['center3d'][i].numpy() draw_bounding_box_3d(boxes['size3d'].numpy()[i], predicted_pose_obj2world, intrinsics, pose_world2camera, linestyle=style) if j == 0: if isinstance(boxes['detection_boxes'], tf.Tensor): boxes['detection_boxes'] = boxes['detection_boxes'].numpy() # if isinstance(boxes['detection_classes'], tf.Tensor): # boxes['detection_classes'] = boxes['detection_classes'].numpy() x_min, y_min, x_max, y_max = boxes['detection_boxes'][i] # plt.text(x_min, y_min, # class_id_to_name[int(boxes['detection_classes'][i])]) plt.plot([x_min, x_max, x_max, x_min, x_min], [y_min, y_min, y_max, y_max, y_min], linestyle=style) plt.axis('off') plt.tight_layout() return figure def plot_all_heatmaps(image, detections, figsize=0.1, num_classes=6): """Plot.""" if figsize: print(figsize) figure, axis = plt.subplots(1, num_classes, figsize=(num_classes * 5, 5)) for class_id in range(num_classes): for k, color in [['centers_sigmoid', [0, 1, 0]], ['centers_nms', [1, 0, 0]]]: axis[class_id].imshow(np.concatenate( [image.astype(float)/255.0, 0.5 * np.ones([256, 256, 1])], axis=-1)) centers = detections[k][:, :, class_id].numpy() axis[class_id].imshow(resize_heatmap(centers, color=color)) return figure def plot_gt_heatmaps(image, heatmaps, num_classes=6): figure, axis = plt.subplots(1, num_classes, figsize=(num_classes * 4, 4)) for class_id in range(num_classes): axis[class_id].imshow(np.concatenate( [image, 0.5 * np.ones([image.shape[0], image.shape[1], 1])], axis=-1)) centers = heatmaps[:, :, class_id].numpy() axis[class_id].imshow(resize_heatmap(centers, color=[255, 0, 0])) return figure def draw_bounding_box_3d(size, pose, camera_intrinsic, world2camera, linestyle='solid', color=None, linewidth=1): """Draw bounding box.""" size = size * 0.5 origin = np.zeros([4, 1]) origin[3, 0] = 1.0 bbox3d = np.tile(origin, [1, 10]) # shape: (4, 10) bbox3d[0:3, 0] += np.array([-size[0], -size[1], -size[2]]) bbox3d[0:3, 1] += np.array([size[0], -size[1], -size[2]]) bbox3d[0:3, 2] += np.array([size[0], -size[1], size[2]]) bbox3d[0:3, 3] += np.array([-size[0], -size[1], size[2]]) bbox3d[0:3, 4] += np.array([-size[0], size[1], -size[2]]) bbox3d[0:3, 5] += np.array([size[0], size[1], -size[2]]) bbox3d[0:3, 6] += np.array([size[0], size[1], size[2]]) bbox3d[0:3, 7] += np.array([-size[0], size[1], size[2]]) bbox3d[0:3, 8] += np.array([0.0, -size[1], 0.0]) bbox3d[0:3, 9] += np.array([0.0, -size[1], -size[2]]) projected_bbox3d = camera_intrinsic @ world2camera @ pose @ bbox3d projected_bbox3d = projected_bbox3d[0:2, :] / projected_bbox3d[2, :] lw = linewidth plt.plot(projected_bbox3d[0, [0, 4, 7, 3]], projected_bbox3d[1, [0, 4, 7, 3]], linewidth=lw, linestyle=linestyle, color=color) plt.plot(projected_bbox3d[0, [1, 5, 6, 2]], projected_bbox3d[1, [1, 5, 6, 2]], linewidth=lw, linestyle=linestyle, color=color) plt.plot(projected_bbox3d[0, [0, 1, 2, 3, 0]], projected_bbox3d[1, [0, 1, 2, 3, 0]], linewidth=lw, linestyle=linestyle, color=color) plt.plot(projected_bbox3d[0, [4, 5, 6, 7, 4]], projected_bbox3d[1, [4, 5, 6, 7, 4]], linewidth=lw, linestyle=linestyle, color=color) plt.plot(projected_bbox3d[0, [8, 9]], projected_bbox3d[1, [8, 9]], linewidth=lw, linestyle=linestyle, color=color) def plot_prediction(inputs, outputs, figsize=0.1, batch_id=0, plot_2d=False): """Plot bounding box predictions along ground truth labels. Args: inputs: Dict of batched inputs to the network. outputs: Dict of batched outputs of the network. figsize: The size of the figure. batch_id: The batch entry to plot. plot_2d: Whether 2D bounding boxes should be shown or not. Returns: A matplotlib figure. """ image = inputs['image'][batch_id].numpy() size2d = inputs['box_dim2d'][batch_id].numpy() size3d = inputs['box_dim3d'][batch_id].numpy()[[0, 2, 1]] center2d = inputs['center2d'][batch_id].numpy() center3d = inputs['center3d'][batch_id].numpy() predicted_center2d = outputs['center2d'][batch_id].numpy() predicted_size2d = outputs['size2d'][batch_id].numpy() predicted_rotation = outputs['rotation'][batch_id].numpy() predicted_center3d = outputs['center3d'][batch_id].numpy().T predicted_size3d = outputs['size3d'][batch_id].numpy()[[0, 2, 1]] # dot = outputs['dot'][batch_id].numpy() intrinsics = inputs['k'][batch_id].numpy() pose_world2camera = inputs['rt'][batch_id].numpy() object_translation = np.squeeze(center3d[0:3]) object_rotation = inputs['rotation'][batch_id].numpy() pose_obj2world = np.eye(4) rad = np.deg2rad(object_rotation*-1) cos = np.cos(rad) sin = np.sin(rad) pose_obj2world[0, 0] = cos pose_obj2world[0, 1] = sin pose_obj2world[1, 1] = cos pose_obj2world[1, 0] = -sin pose_obj2world[0:3, 3] = object_translation predicted_pose_obj2world = np.eye(4) predicted_pose_obj2world[0:2, 0:2] = predicted_rotation predicted_pose_obj2world[0:3, 3] = predicted_center3d figure = plt.figure(figsize=(figsize, figsize)) plt.clf() plt.imshow(image / 255.) plt.plot(center2d[0], center2d[1], 'g*') def draw_ground_plane(camera_intrinsic, pose_world2camera): """Draw ground plane as grid. Args: camera_intrinsic: Camera intrinsic. pose_world2camera: Camera extrinsic. """ line = np.array([[-3, 3, 0, 1], [3, 3, 0, 1]]).T projected_line = camera_intrinsic @ pose_world2camera @ line projected_line = projected_line[0:2, :] / projected_line[2, :] plt.plot(projected_line[0, [0, 1]], projected_line[1, [0, 1]], 'black', linewidth=1) def draw_bounding_box_2d(center, size, style='b+-'): bbox2d = np.tile(np.reshape(center, [1, 2]), [4, 1]) # shape: (4, 2) bbox2d[0, :] += np.array([-size[0], -size[1]]) bbox2d[1, :] += np.array([size[0], -size[1]]) bbox2d[2, :] += np.array([size[0], size[1]]) bbox2d[3, :] += np.array([-size[0], size[1]]) plt.plot(bbox2d[[0, 1, 2, 3, 0], 0], bbox2d[[0, 1, 2, 3, 0], 1], style) draw_bounding_box_3d(size3d, pose_obj2world, intrinsics, pose_world2camera, 'dashed') draw_ground_plane(intrinsics, pose_world2camera) # draw_coordinate_frame(intrinsics, pose_world2camera) draw_bounding_box_3d(predicted_size3d, predicted_pose_obj2world, intrinsics, pose_world2camera) if plot_2d: draw_bounding_box_2d(center2d, size2d / 2, 'g-') draw_bounding_box_2d(predicted_center2d, predicted_size2d / 2, 'b-') return figure def matrix_from_angle(angle: float, axis: int): matrix = np.eye(3) if axis == 1: matrix[0, 0] = np.cos(angle) matrix[2, 2] = np.cos(angle) matrix[2, 0] = -np.sin(angle) matrix[0, 2] = np.sin(angle) return matrix def save_for_blender(detections, sample, log_dir, dict_clusters, shape_pointclouds, class_id_to_name=CLASSES): """Save for blender.""" # VisualDebugging uses the OpenCV coordinate representation # while the dataset uses OpenGL (left-hand) so make sure to convert y and z. batch_id = 0 prefix = '/cns/lu-d/home/giotto3d/datasets/shapenet/raw/' sufix = 'models/model_normalized.obj' blender_dict = {} blender_dict['image'] = \ tf.io.decode_image(sample['image_data'][batch_id]).numpy() blender_dict['world_to_cam'] = sample['rt'].numpy() num_predicted_shapes = int(detections['sizes_3d'].shape[0]) blender_dict['num_predicted_shapes'] = num_predicted_shapes blender_dict['predicted_rotations_3d'] = \ tf.reshape(detections['rotations_3d'], [-1, 3, 3]).numpy() blender_dict['predicted_rotations_y'] = [ tf_utils.euler_from_rotation_matrix( tf.reshape(detections['rotations_3d'][i], [3, 3]), 1).numpy() for i in range(num_predicted_shapes)] blender_dict['predicted_translations_3d'] = \ detections['translations_3d'].numpy() blender_dict['predicted_sizes_3d'] = detections['sizes_3d'].numpy() predicted_shapes_path = [] for i in range(num_predicted_shapes): shape = detections['shapes'][i].numpy() _, class_str, model_str = dict_clusters[shape] filename = os.path.join(prefix, class_str, model_str, sufix) predicted_shapes_path.append(filename) blender_dict['predicted_shapes_path'] = predicted_shapes_path blender_dict['predicted_class'] = [ class_id_to_name[int(detections['detection_classes'][i].numpy())] for i in range(num_predicted_shapes)] blender_dict['predicted_pointcloud'] = [ shape_pointclouds[int(detections['shapes'][i].numpy())] for i in range(num_predicted_shapes)] num_groundtruth_shapes = int(sample['sizes_3d'][batch_id].shape[0]) blender_dict['num_groundtruth_shapes'] = num_groundtruth_shapes blender_dict['groundtruth_rotations_3d'] = \ tf.reshape(sample['rotations_3d'][batch_id], [-1, 3, 3]).numpy() blender_dict['groundtruth_rotations_y'] = [ tf_utils.euler_from_rotation_matrix( tf.reshape(sample['rotations_3d'][batch_id][i], [3, 3]), 1).numpy() for i in range(sample['num_boxes'][batch_id].numpy())] blender_dict['groundtruth_translations_3d'] = \ sample['translations_3d'][batch_id].numpy() blender_dict['groundtruth_sizes_3d'] = sample['sizes_3d'][batch_id].numpy() groundtruth_shapes_path = [] for i in range(num_groundtruth_shapes): class_str = str(sample['classes'][batch_id, i].numpy()).zfill(8) model_str = str(sample['mesh_names'][batch_id, i].numpy())[2:-1] filename = os.path.join(prefix, class_str, model_str, sufix) groundtruth_shapes_path.append(filename) blender_dict['groundtruth_shapes_path'] = groundtruth_shapes_path blender_dict['groundtruth_classes'] = \ sample['groundtruth_valid_classes'].numpy() path = log_dir + '.pkl' with gfile.Open(path, 'wb') as file: pickle.dump(blender_dict, file) def obj_read_for_gl(filename, texture_size=(32, 32)): """Read vertex and part information from OBJ file.""" if texture_size: print(texture_size) with gfile.Open(filename, 'r') as f: content = f.readlines() vertices = [] texture_coords = [] vertex_normals = [] group_name = None material_name = None faces = [] faces_tex = [] faces_normals = [] face_groups = [] material_ids = [] for i in range(len(content)): line = content[i] parts = re.split(r'\s+', line) # if parts[0] == 'mtllib': # material_file = parts[1] # Vertex information ----------------------------------------------------- if parts[0] == 'v': vertices.append([float(v) for v in parts[1:4]]) if parts[0] == 'vt': texture_coords.append([float(v) for v in parts[1:4]]) if parts[0] == 'vn': vertex_normals.append([float(v) for v in parts[1:4]]) if parts[0] == 'g': group_name = parts[1] if parts[0] == 'usemtl': material_name = parts[1] # Face information ------------------------------------------------------ if parts[0] == 'f': vertex_index, tex_index, normal_index = 0, 0, 0 current_face, current_face_tex, current_face_norm = [], [], [] for j in range(1, 4): face_info = parts[j] if face_info.count('/') == 2: vertex_index, tex_index, normal_index = face_info.split('/') if not tex_index: tex_index = 0 elif face_info.count('/') == 1: vertex_index, tex_index = face_info.split('/') elif face_info.count('/') == 0: vertex_index = face_info current_face.append(int(vertex_index)-1) current_face_tex.append(int(tex_index)-1) current_face_norm.append(int(normal_index)-1) faces.append(current_face) faces_tex.append(current_face_tex) faces_normals.append(current_face_norm) face_groups.append(group_name) material_ids.append(material_name) vertices = np.array(vertices) texture_coords = np.array(texture_coords) vertex_normals = np.array(vertex_normals) has_tex_coord, has_normals = True, True if texture_coords.shape[0] == 0: has_tex_coord = False if vertex_normals.shape[0] == 0: has_normals = False faces = np.array(faces) faces_tex = np.array(faces_tex) faces_normals = np.array(faces_normals) n_faces = faces.shape[0] vertex_positions = np.zeros((n_faces, 3, 3), dtype=np.float32) tex_coords = np.zeros((n_faces, 3, 2), dtype=np.float32) normals = np.zeros((n_faces, 3, 3), dtype=np.float32) for i in range(n_faces): for j in range(3): vertex_positions[i, j, :] = vertices[faces[i, j], :] if has_tex_coord: tex_coords[i, j, :] = texture_coords[faces_tex[i, j], :2] if has_normals: normals[i, j, :] = vertex_normals[faces_normals[i, j], :] # Material info -------------------------------------------------------------- return vertex_positions, \ tex_coords, \ normals, \ material_ids, \ vertices, \ faces def plot_labeled_2d_boxes(sample, batch_id=0): """Plot.""" image = tf.io.decode_image(sample['image_data'][batch_id]).numpy() / 255. image = sample['image'][batch_id].numpy()[..., ::-1] image2 = np.reshape(image, [-1, 3]) image2 -= np.min(image2, axis=0) image2 /= np.max(image2, axis=0) image = np.reshape(image2, [256, 256, 3]) sample['detection_boxes'] = sample['groundtruth_boxes'][batch_id].numpy() figure = plt.figure(figsize=(5, 5)) plt.clf() plt.imshow(image) for i in range(sample['groundtruth_boxes'][batch_id].shape[0]): y_min, x_min, y_max, x_max = sample['detection_boxes'][i] * 256.0 plt.plot([x_min, x_max, x_max, x_min, x_min], [y_min, y_min, y_max, y_max, y_min], linestyle='dashed') return figure
[ "pickle.dump", "tensorflow.io.decode_image", "matplotlib.pyplot.clf", "tensorflow.reshape", "numpy.ones", "matplotlib.pyplot.figure", "numpy.sin", "numpy.tile", "numpy.diag", "matplotlib.pyplot.tight_layout", "os.path.join", "matplotlib.pyplot.imshow", "matplotlib.pyplot.colorbar", "numpy....
[((1144, 1170), 'tensorflow.expand_dims', 'tf.expand_dims', (['data_np', '(0)'], {}), '(data_np, 0)\n', (1158, 1170), True, 'import tensorflow as tf\n'), ((1363, 1395), 'numpy.expand_dims', 'np.expand_dims', (['centers'], {'axis': '(-1)'}), '(centers, axis=-1)\n', (1377, 1395), True, 'import numpy as np\n'), ((1785, 1823), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(figsize, figsize)'}), '(figsize=(figsize, figsize))\n', (1795, 1823), True, 'import matplotlib.pyplot as plt\n'), ((1826, 1835), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (1833, 1835), True, 'import matplotlib.pyplot as plt\n'), ((2614, 2629), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (2622, 2629), True, 'import matplotlib.pyplot as plt\n'), ((2632, 2650), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (2648, 2650), True, 'import matplotlib.pyplot as plt\n'), ((2872, 2941), 'matplotlib.pyplot.plot', 'plt.plot', (['[0, width]', '[height / 4.0 * 3.0, height / 4.0 * 3.0]', '"""g--"""'], {}), "([0, width], [height / 4.0 * 3.0, height / 4.0 * 3.0], 'g--')\n", (2880, 2941), True, 'import matplotlib.pyplot as plt\n'), ((2944, 3002), 'matplotlib.pyplot.plot', 'plt.plot', (['[width / 2.0, width / 2.0]', '[0.0, height]', '"""g--"""'], {}), "([width / 2.0, width / 2.0], [0.0, height], 'g--')\n", (2952, 3002), True, 'import matplotlib.pyplot as plt\n'), ((3025, 3061), 'numpy.reshape', 'np.reshape', (['camera_intrinsic', '[3, 3]'], {}), '(camera_intrinsic, [3, 3])\n', (3035, 3061), True, 'import numpy as np\n'), ((3084, 3121), 'numpy.reshape', 'np.reshape', (['pose_world2camera', '[3, 4]'], {}), '(pose_world2camera, [3, 4])\n', (3094, 3121), True, 'import numpy as np\n'), ((3437, 3507), 'matplotlib.pyplot.plot', 'plt.plot', (['projected_frame[0, [0, 1]]', 'projected_frame[1, [0, 1]]', '"""r-"""'], {}), "(projected_frame[0, [0, 1]], projected_frame[1, [0, 1]], 'r-')\n", (3445, 3507), True, 'import matplotlib.pyplot as plt\n'), ((3510, 3580), 'matplotlib.pyplot.plot', 'plt.plot', (['projected_frame[0, [0, 2]]', 'projected_frame[1, [0, 2]]', '"""g-"""'], {}), "(projected_frame[0, [0, 2]], projected_frame[1, [0, 2]], 'g-')\n", (3518, 3580), True, 'import matplotlib.pyplot as plt\n'), ((3583, 3653), 'matplotlib.pyplot.plot', 'plt.plot', (['projected_frame[0, [0, 3]]', 'projected_frame[1, [0, 3]]', '"""b-"""'], {}), "(projected_frame[0, [0, 3]], projected_frame[1, [0, 3]], 'b-')\n", (3591, 3653), True, 'import matplotlib.pyplot as plt\n'), ((3800, 3840), 'matplotlib.pyplot.plot', 'plt.plot', (['dot_proj[0]', 'dot_proj[1]', '"""y*"""'], {}), "(dot_proj[0], dot_proj[1], 'y*')\n", (3808, 3840), True, 'import matplotlib.pyplot as plt\n'), ((3923, 3961), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(figsize, figsize)'}), '(figsize=(figsize, figsize))\n', (3933, 3961), True, 'import matplotlib.pyplot as plt\n'), ((3964, 3973), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (3971, 3973), True, 'import matplotlib.pyplot as plt\n'), ((3976, 4003), 'matplotlib.pyplot.imshow', 'plt.imshow', (["sample['image']"], {}), "(sample['image'])\n", (3986, 4003), True, 'import matplotlib.pyplot as plt\n'), ((5334, 5384), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(3)'], {'figsize': '(3 * figsize, figsize)'}), '(1, 3, figsize=(3 * figsize, figsize))\n', (5346, 5384), True, 'import matplotlib.pyplot as plt\n'), ((5391, 5444), 'tensorflow.reshape', 'tf.reshape', (['sdf', '[resolution, resolution, resolution]'], {}), '(sdf, [resolution, resolution, resolution])\n', (5401, 5444), True, 'import tensorflow as tf\n'), ((5757, 5795), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(figsize, figsize)'}), '(figsize=(figsize, figsize))\n', (5767, 5795), True, 'import matplotlib.pyplot as plt\n'), ((5798, 5807), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (5805, 5807), True, 'import matplotlib.pyplot as plt\n'), ((5824, 5854), 'numpy.reshape', 'np.reshape', (['intrinsics', '[3, 3]'], {}), '(intrinsics, [3, 3])\n', (5834, 5854), True, 'import numpy as np\n'), ((5877, 5914), 'numpy.reshape', 'np.reshape', (['pose_world2camera', '[3, 4]'], {}), '(pose_world2camera, [3, 4])\n', (5887, 5914), True, 'import numpy as np\n'), ((7896, 7934), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(figsize, figsize)'}), '(figsize=(figsize, figsize))\n', (7906, 7934), True, 'import matplotlib.pyplot as plt\n'), ((7937, 7946), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (7944, 7946), True, 'import matplotlib.pyplot as plt\n'), ((7949, 7966), 'matplotlib.pyplot.imshow', 'plt.imshow', (['image'], {}), '(image)\n', (7959, 7966), True, 'import matplotlib.pyplot as plt\n'), ((9580, 9595), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (9588, 9595), True, 'import matplotlib.pyplot as plt\n'), ((9598, 9616), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (9614, 9616), True, 'import matplotlib.pyplot as plt\n'), ((9895, 9933), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(figsize, figsize)'}), '(figsize=(figsize, figsize))\n', (9905, 9933), True, 'import matplotlib.pyplot as plt\n'), ((9936, 9945), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (9943, 9945), True, 'import matplotlib.pyplot as plt\n'), ((9948, 9965), 'matplotlib.pyplot.imshow', 'plt.imshow', (['image'], {}), '(image)\n', (9958, 9965), True, 'import matplotlib.pyplot as plt\n'), ((9982, 10012), 'numpy.reshape', 'np.reshape', (['intrinsics', '[3, 3]'], {}), '(intrinsics, [3, 3])\n', (9992, 10012), True, 'import numpy as np\n'), ((10035, 10072), 'numpy.reshape', 'np.reshape', (['pose_world2camera', '[3, 4]'], {}), '(pose_world2camera, [3, 4])\n', (10045, 10072), True, 'import numpy as np\n'), ((12279, 12294), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (12287, 12294), True, 'import matplotlib.pyplot as plt\n'), ((12297, 12315), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (12313, 12315), True, 'import matplotlib.pyplot as plt\n'), ((12476, 12514), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(figsize, figsize)'}), '(figsize=(figsize, figsize))\n', (12486, 12514), True, 'import matplotlib.pyplot as plt\n'), ((12517, 12526), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (12524, 12526), True, 'import matplotlib.pyplot as plt\n'), ((13097, 13127), 'numpy.reshape', 'np.reshape', (['intrinsics', '[3, 3]'], {}), '(intrinsics, [3, 3])\n', (13107, 13127), True, 'import numpy as np\n'), ((13150, 13187), 'numpy.reshape', 'np.reshape', (['pose_world2camera', '[3, 4]'], {}), '(pose_world2camera, [3, 4])\n', (13160, 13187), True, 'import numpy as np\n'), ((14406, 14421), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (14414, 14421), True, 'import matplotlib.pyplot as plt\n'), ((14424, 14442), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (14440, 14442), True, 'import matplotlib.pyplot as plt\n'), ((14595, 14653), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', 'num_classes'], {'figsize': '(num_classes * 5, 5)'}), '(1, num_classes, figsize=(num_classes * 5, 5))\n', (14607, 14653), True, 'import matplotlib.pyplot as plt\n'), ((15127, 15185), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', 'num_classes'], {'figsize': '(num_classes * 4, 4)'}), '(1, num_classes, figsize=(num_classes * 4, 4))\n', (15139, 15185), True, 'import matplotlib.pyplot as plt\n'), ((15678, 15694), 'numpy.zeros', 'np.zeros', (['[4, 1]'], {}), '([4, 1])\n', (15686, 15694), True, 'import numpy as np\n'), ((15727, 15751), 'numpy.tile', 'np.tile', (['origin', '[1, 10]'], {}), '(origin, [1, 10])\n', (15734, 15751), True, 'import numpy as np\n'), ((15790, 15830), 'numpy.array', 'np.array', (['[-size[0], -size[1], -size[2]]'], {}), '([-size[0], -size[1], -size[2]])\n', (15798, 15830), True, 'import numpy as np\n'), ((15851, 15890), 'numpy.array', 'np.array', (['[size[0], -size[1], -size[2]]'], {}), '([size[0], -size[1], -size[2]])\n', (15859, 15890), True, 'import numpy as np\n'), ((15911, 15949), 'numpy.array', 'np.array', (['[size[0], -size[1], size[2]]'], {}), '([size[0], -size[1], size[2]])\n', (15919, 15949), True, 'import numpy as np\n'), ((15970, 16009), 'numpy.array', 'np.array', (['[-size[0], -size[1], size[2]]'], {}), '([-size[0], -size[1], size[2]])\n', (15978, 16009), True, 'import numpy as np\n'), ((16031, 16070), 'numpy.array', 'np.array', (['[-size[0], size[1], -size[2]]'], {}), '([-size[0], size[1], -size[2]])\n', (16039, 16070), True, 'import numpy as np\n'), ((16091, 16129), 'numpy.array', 'np.array', (['[size[0], size[1], -size[2]]'], {}), '([size[0], size[1], -size[2]])\n', (16099, 16129), True, 'import numpy as np\n'), ((16150, 16187), 'numpy.array', 'np.array', (['[size[0], size[1], size[2]]'], {}), '([size[0], size[1], size[2]])\n', (16158, 16187), True, 'import numpy as np\n'), ((16208, 16246), 'numpy.array', 'np.array', (['[-size[0], size[1], size[2]]'], {}), '([-size[0], size[1], size[2]])\n', (16216, 16246), True, 'import numpy as np\n'), ((16268, 16298), 'numpy.array', 'np.array', (['[0.0, -size[1], 0.0]'], {}), '([0.0, -size[1], 0.0])\n', (16276, 16298), True, 'import numpy as np\n'), ((16319, 16354), 'numpy.array', 'np.array', (['[0.0, -size[1], -size[2]]'], {}), '([0.0, -size[1], -size[2]])\n', (16327, 16354), True, 'import numpy as np\n'), ((16516, 16647), 'matplotlib.pyplot.plot', 'plt.plot', (['projected_bbox3d[0, [0, 4, 7, 3]]', 'projected_bbox3d[1, [0, 4, 7, 3]]'], {'linewidth': 'lw', 'linestyle': 'linestyle', 'color': 'color'}), '(projected_bbox3d[0, [0, 4, 7, 3]], projected_bbox3d[1, [0, 4, 7, 3\n ]], linewidth=lw, linestyle=linestyle, color=color)\n', (16524, 16647), True, 'import matplotlib.pyplot as plt\n'), ((16667, 16798), 'matplotlib.pyplot.plot', 'plt.plot', (['projected_bbox3d[0, [1, 5, 6, 2]]', 'projected_bbox3d[1, [1, 5, 6, 2]]'], {'linewidth': 'lw', 'linestyle': 'linestyle', 'color': 'color'}), '(projected_bbox3d[0, [1, 5, 6, 2]], projected_bbox3d[1, [1, 5, 6, 2\n ]], linewidth=lw, linestyle=linestyle, color=color)\n', (16675, 16798), True, 'import matplotlib.pyplot as plt\n'), ((16818, 16954), 'matplotlib.pyplot.plot', 'plt.plot', (['projected_bbox3d[0, [0, 1, 2, 3, 0]]', 'projected_bbox3d[1, [0, 1, 2, 3, 0]]'], {'linewidth': 'lw', 'linestyle': 'linestyle', 'color': 'color'}), '(projected_bbox3d[0, [0, 1, 2, 3, 0]], projected_bbox3d[1, [0, 1, 2,\n 3, 0]], linewidth=lw, linestyle=linestyle, color=color)\n', (16826, 16954), True, 'import matplotlib.pyplot as plt\n'), ((16975, 17111), 'matplotlib.pyplot.plot', 'plt.plot', (['projected_bbox3d[0, [4, 5, 6, 7, 4]]', 'projected_bbox3d[1, [4, 5, 6, 7, 4]]'], {'linewidth': 'lw', 'linestyle': 'linestyle', 'color': 'color'}), '(projected_bbox3d[0, [4, 5, 6, 7, 4]], projected_bbox3d[1, [4, 5, 6,\n 7, 4]], linewidth=lw, linestyle=linestyle, color=color)\n', (16983, 17111), True, 'import matplotlib.pyplot as plt\n'), ((17132, 17250), 'matplotlib.pyplot.plot', 'plt.plot', (['projected_bbox3d[0, [8, 9]]', 'projected_bbox3d[1, [8, 9]]'], {'linewidth': 'lw', 'linestyle': 'linestyle', 'color': 'color'}), '(projected_bbox3d[0, [8, 9]], projected_bbox3d[1, [8, 9]],\n linewidth=lw, linestyle=linestyle, color=color)\n', (17140, 17250), True, 'import matplotlib.pyplot as plt\n'), ((18434, 18459), 'numpy.squeeze', 'np.squeeze', (['center3d[0:3]'], {}), '(center3d[0:3])\n', (18444, 18459), True, 'import numpy as np\n'), ((18537, 18546), 'numpy.eye', 'np.eye', (['(4)'], {}), '(4)\n', (18543, 18546), True, 'import numpy as np\n'), ((18555, 18587), 'numpy.deg2rad', 'np.deg2rad', (['(object_rotation * -1)'], {}), '(object_rotation * -1)\n', (18565, 18587), True, 'import numpy as np\n'), ((18594, 18605), 'numpy.cos', 'np.cos', (['rad'], {}), '(rad)\n', (18600, 18605), True, 'import numpy as np\n'), ((18614, 18625), 'numpy.sin', 'np.sin', (['rad'], {}), '(rad)\n', (18620, 18625), True, 'import numpy as np\n'), ((18819, 18828), 'numpy.eye', 'np.eye', (['(4)'], {}), '(4)\n', (18825, 18828), True, 'import numpy as np\n'), ((18955, 18993), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(figsize, figsize)'}), '(figsize=(figsize, figsize))\n', (18965, 18993), True, 'import matplotlib.pyplot as plt\n'), ((18996, 19005), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (19003, 19005), True, 'import matplotlib.pyplot as plt\n'), ((19008, 19033), 'matplotlib.pyplot.imshow', 'plt.imshow', (['(image / 255.0)'], {}), '(image / 255.0)\n', (19018, 19033), True, 'import matplotlib.pyplot as plt\n'), ((19035, 19075), 'matplotlib.pyplot.plot', 'plt.plot', (['center2d[0]', 'center2d[1]', '"""g*"""'], {}), "(center2d[0], center2d[1], 'g*')\n", (19043, 19075), True, 'import matplotlib.pyplot as plt\n'), ((20543, 20552), 'numpy.eye', 'np.eye', (['(3)'], {}), '(3)\n', (20549, 20552), True, 'import numpy as np\n'), ((27254, 27280), 'numpy.reshape', 'np.reshape', (['image', '[-1, 3]'], {}), '(image, [-1, 3])\n', (27264, 27280), True, 'import numpy as np\n'), ((27293, 27315), 'numpy.min', 'np.min', (['image2'], {'axis': '(0)'}), '(image2, axis=0)\n', (27299, 27315), True, 'import numpy as np\n'), ((27328, 27350), 'numpy.max', 'np.max', (['image2'], {'axis': '(0)'}), '(image2, axis=0)\n', (27334, 27350), True, 'import numpy as np\n'), ((27361, 27394), 'numpy.reshape', 'np.reshape', (['image2', '[256, 256, 3]'], {}), '(image2, [256, 256, 3])\n', (27371, 27394), True, 'import numpy as np\n'), ((27483, 27509), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(5, 5)'}), '(figsize=(5, 5))\n', (27493, 27509), True, 'import matplotlib.pyplot as plt\n'), ((27512, 27521), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (27519, 27521), True, 'import matplotlib.pyplot as plt\n'), ((27524, 27541), 'matplotlib.pyplot.imshow', 'plt.imshow', (['image'], {}), '(image)\n', (27534, 27541), True, 'import matplotlib.pyplot as plt\n'), ((1299, 1333), 'numpy.repeat', 'np.repeat', (['centers', 'stride'], {'axis': '(0)'}), '(centers, stride, axis=0)\n', (1308, 1333), True, 'import numpy as np\n'), ((1411, 1426), 'numpy.min', 'np.min', (['centers'], {}), '(centers)\n', (1417, 1426), True, 'import numpy as np\n'), ((1428, 1443), 'numpy.max', 'np.max', (['centers'], {}), '(centers)\n', (1434, 1443), True, 'import numpy as np\n'), ((1919, 1970), 'tensorflow.image.pad_to_bounding_box', 'tf.image.pad_to_bounding_box', (['image', '(0)', '(0)', '(640)', '(640)'], {}), '(image, 0, 0, 640, 640)\n', (1947, 1970), True, 'import tensorflow as tf\n'), ((3132, 3226), 'numpy.array', 'np.array', (['[[0, 0, 0, 1], [0.1, 0, 0, 1], [0, 0.1, 0, 1], [0, 0, 0.1, 1]]'], {'dtype': 'np.float32'}), '([[0, 0, 0, 1], [0.1, 0, 0, 1], [0, 0.1, 0, 1], [0, 0, 0.1, 1]],\n dtype=np.float32)\n', (3140, 3226), True, 'import numpy as np\n'), ((4228, 4269), 'tensorflow.transpose', 'tf.transpose', (['shape_pointclouds[shape_id]'], {}), '(shape_pointclouds[shape_id])\n', (4240, 4269), True, 'import tensorflow as tf\n'), ((4332, 4377), 'tensorflow.reshape', 'tf.reshape', (["sample['rotations_3d'][i]", '[3, 3]'], {}), "(sample['rotations_3d'][i], [3, 3])\n", (4342, 4377), True, 'import tensorflow as tf\n'), ((4389, 4419), 'numpy.diag', 'np.diag', (["sample['sizes_3d'][i]"], {}), "(sample['sizes_3d'][i])\n", (4396, 4419), True, 'import numpy as np\n'), ((4734, 4813), 'matplotlib.pyplot.plot', 'plt.plot', (['projected_pointcloud[0, :]', 'projected_pointcloud[1, :]', 'colors[i % 3]'], {}), '(projected_pointcloud[0, :], projected_pointcloud[1, :], colors[i % 3])\n', (4742, 4813), True, 'import matplotlib.pyplot as plt\n'), ((5146, 5252), 'matplotlib.pyplot.plot', 'plt.plot', (['[x_min, x_max, x_max, x_min, x_min]', '[y_min, y_min, y_max, y_max, y_min]'], {'linestyle': '"""dashed"""'}), "([x_min, x_max, x_max, x_min, x_min], [y_min, y_min, y_max, y_max,\n y_min], linestyle='dashed')\n", (5154, 5252), True, 'import matplotlib.pyplot as plt\n'), ((5568, 5595), 'matplotlib.pyplot.colorbar', 'plt.colorbar', (['c'], {'ax': 'axis[a]'}), '(c, ax=axis[a])\n', (5580, 5595), True, 'import matplotlib.pyplot as plt\n'), ((6144, 6185), 'tensorflow.transpose', 'tf.transpose', (['shape_pointclouds[shape_id]'], {}), '(shape_pointclouds[shape_id])\n', (6156, 6185), True, 'import tensorflow as tf\n'), ((6248, 6293), 'tensorflow.reshape', 'tf.reshape', (["sample['rotations_3d'][i]", '[3, 3]'], {}), "(sample['rotations_3d'][i], [3, 3])\n", (6258, 6293), True, 'import tensorflow as tf\n'), ((6305, 6335), 'numpy.diag', 'np.diag', (["sample['sizes_3d'][i]"], {}), "(sample['sizes_3d'][i])\n", (6312, 6335), True, 'import numpy as np\n'), ((6650, 6738), 'matplotlib.pyplot.plot', 'plt.plot', (['projected_pointcloud[0, :]', 'projected_pointcloud[1, :]', '"""w."""'], {'markersize': '(5)'}), "(projected_pointcloud[0, :], projected_pointcloud[1, :], 'w.',\n markersize=5)\n", (6658, 6738), True, 'import matplotlib.pyplot as plt\n'), ((6752, 6846), 'matplotlib.pyplot.plot', 'plt.plot', (['projected_pointcloud[0, :]', 'projected_pointcloud[1, :]', 'colors2[i]'], {'markersize': '(3)'}), '(projected_pointcloud[0, :], projected_pointcloud[1, :], colors2[i],\n markersize=3)\n', (6760, 6846), True, 'import matplotlib.pyplot as plt\n'), ((6888, 6897), 'numpy.eye', 'np.eye', (['(4)'], {}), '(4)\n', (6894, 6897), True, 'import numpy as np\n'), ((11555, 11564), 'numpy.eye', 'np.eye', (['(4)'], {}), '(4)\n', (11561, 11564), True, 'import numpy as np\n'), ((19466, 19554), 'matplotlib.pyplot.plot', 'plt.plot', (['projected_line[0, [0, 1]]', 'projected_line[1, [0, 1]]', '"""black"""'], {'linewidth': '(1)'}), "(projected_line[0, [0, 1]], projected_line[1, [0, 1]], 'black',\n linewidth=1)\n", (19474, 19554), True, 'import matplotlib.pyplot as plt\n'), ((19727, 19757), 'numpy.array', 'np.array', (['[-size[0], -size[1]]'], {}), '([-size[0], -size[1]])\n', (19735, 19757), True, 'import numpy as np\n'), ((19778, 19807), 'numpy.array', 'np.array', (['[size[0], -size[1]]'], {}), '([size[0], -size[1]])\n', (19786, 19807), True, 'import numpy as np\n'), ((19828, 19856), 'numpy.array', 'np.array', (['[size[0], size[1]]'], {}), '([size[0], size[1]])\n', (19836, 19856), True, 'import numpy as np\n'), ((19877, 19906), 'numpy.array', 'np.array', (['[-size[0], size[1]]'], {}), '([-size[0], size[1]])\n', (19885, 19906), True, 'import numpy as np\n'), ((19911, 19982), 'matplotlib.pyplot.plot', 'plt.plot', (['bbox2d[[0, 1, 2, 3, 0], 0]', 'bbox2d[[0, 1, 2, 3, 0], 1]', 'style'], {}), '(bbox2d[[0, 1, 2, 3, 0], 0], bbox2d[[0, 1, 2, 3, 0], 1], style)\n', (19919, 19982), True, 'import matplotlib.pyplot as plt\n'), ((20588, 20601), 'numpy.cos', 'np.cos', (['angle'], {}), '(angle)\n', (20594, 20601), True, 'import numpy as np\n'), ((20621, 20634), 'numpy.cos', 'np.cos', (['angle'], {}), '(angle)\n', (20627, 20634), True, 'import numpy as np\n'), ((20688, 20701), 'numpy.sin', 'np.sin', (['angle'], {}), '(angle)\n', (20694, 20701), True, 'import numpy as np\n'), ((22123, 22172), 'os.path.join', 'os.path.join', (['prefix', 'class_str', 'model_str', 'sufix'], {}), '(prefix, class_str, model_str, sufix)\n', (22135, 22172), False, 'import os\n'), ((23471, 23520), 'os.path.join', 'os.path.join', (['prefix', 'class_str', 'model_str', 'sufix'], {}), '(prefix, class_str, model_str, sufix)\n', (23483, 23520), False, 'import os\n'), ((23760, 23782), 'google3.pyglib.gfile.Open', 'gfile.Open', (['path', '"""wb"""'], {}), "(path, 'wb')\n", (23770, 23782), False, 'from google3.pyglib import gfile\n'), ((23796, 23827), 'pickle.dump', 'pickle.dump', (['blender_dict', 'file'], {}), '(blender_dict, file)\n', (23807, 23827), False, 'import pickle\n'), ((23991, 24016), 'google3.pyglib.gfile.Open', 'gfile.Open', (['filename', '"""r"""'], {}), "(filename, 'r')\n", (24001, 24016), False, 'from google3.pyglib import gfile\n'), ((25924, 25942), 'numpy.array', 'np.array', (['vertices'], {}), '(vertices)\n', (25932, 25942), True, 'import numpy as np\n'), ((25964, 25988), 'numpy.array', 'np.array', (['texture_coords'], {}), '(texture_coords)\n', (25972, 25988), True, 'import numpy as np\n'), ((26010, 26034), 'numpy.array', 'np.array', (['vertex_normals'], {}), '(vertex_normals)\n', (26018, 26034), True, 'import numpy as np\n'), ((26220, 26235), 'numpy.array', 'np.array', (['faces'], {}), '(faces)\n', (26228, 26235), True, 'import numpy as np\n'), ((26252, 26271), 'numpy.array', 'np.array', (['faces_tex'], {}), '(faces_tex)\n', (26260, 26271), True, 'import numpy as np\n'), ((26292, 26315), 'numpy.array', 'np.array', (['faces_normals'], {}), '(faces_normals)\n', (26300, 26315), True, 'import numpy as np\n'), ((26369, 26412), 'numpy.zeros', 'np.zeros', (['(n_faces, 3, 3)'], {'dtype': 'np.float32'}), '((n_faces, 3, 3), dtype=np.float32)\n', (26377, 26412), True, 'import numpy as np\n'), ((26430, 26473), 'numpy.zeros', 'np.zeros', (['(n_faces, 3, 2)'], {'dtype': 'np.float32'}), '((n_faces, 3, 2), dtype=np.float32)\n', (26438, 26473), True, 'import numpy as np\n'), ((26488, 26531), 'numpy.zeros', 'np.zeros', (['(n_faces, 3, 3)'], {'dtype': 'np.float32'}), '((n_faces, 3, 3), dtype=np.float32)\n', (26496, 26531), True, 'import numpy as np\n'), ((27683, 27789), 'matplotlib.pyplot.plot', 'plt.plot', (['[x_min, x_max, x_max, x_min, x_min]', '[y_min, y_min, y_max, y_max, y_min]'], {'linestyle': '"""dashed"""'}), "([x_min, x_max, x_max, x_min, x_min], [y_min, y_min, y_max, y_max,\n y_min], linestyle='dashed')\n", (27691, 27789), True, 'import matplotlib.pyplot as plt\n'), ((4485, 4515), 'tensorflow.expand_dims', 'tf.expand_dims', (['translation', '(1)'], {}), '(translation, 1)\n', (4499, 4515), True, 'import tensorflow as tf\n'), ((5494, 5520), 'tensorflow.reduce_min', 'tf.reduce_min', (['sdf'], {'axis': 'a'}), '(sdf, axis=a)\n', (5507, 5520), True, 'import tensorflow as tf\n'), ((6401, 6431), 'tensorflow.expand_dims', 'tf.expand_dims', (['translation', '(1)'], {}), '(translation, 1)\n', (6415, 6431), True, 'import tensorflow as tf\n'), ((8861, 8967), 'matplotlib.pyplot.plot', 'plt.plot', (['[x_min, x_max, x_max, x_min, x_min]', '[y_min, y_min, y_max, y_max, y_min]'], {'linestyle': '"""dashed"""'}), "([x_min, x_max, x_max, x_min, x_min], [y_min, y_min, y_max, y_max,\n y_min], linestyle='dashed')\n", (8869, 8967), True, 'import matplotlib.pyplot as plt\n'), ((10354, 10363), 'numpy.eye', 'np.eye', (['(4)'], {}), '(4)\n', (10360, 10363), True, 'import numpy as np\n'), ((13436, 13445), 'numpy.eye', 'np.eye', (['(4)'], {}), '(4)\n', (13442, 13445), True, 'import numpy as np\n'), ((19288, 19327), 'numpy.array', 'np.array', (['[[-3, 3, 0, 1], [3, 3, 0, 1]]'], {}), '([[-3, 3, 0, 1], [3, 3, 0, 1]])\n', (19296, 19327), True, 'import numpy as np\n'), ((19654, 19680), 'numpy.reshape', 'np.reshape', (['center', '[1, 2]'], {}), '(center, [1, 2])\n', (19664, 19680), True, 'import numpy as np\n'), ((20655, 20668), 'numpy.sin', 'np.sin', (['angle'], {}), '(angle)\n', (20661, 20668), True, 'import numpy as np\n'), ((21232, 21282), 'tensorflow.io.decode_image', 'tf.io.decode_image', (["sample['image_data'][batch_id]"], {}), "(sample['image_data'][batch_id])\n", (21250, 21282), True, 'import tensorflow as tf\n'), ((21520, 21570), 'tensorflow.reshape', 'tf.reshape', (["detections['rotations_3d']", '[-1, 3, 3]'], {}), "(detections['rotations_3d'], [-1, 3, 3])\n", (21530, 21570), True, 'import tensorflow as tf\n'), ((22774, 22830), 'tensorflow.reshape', 'tf.reshape', (["sample['rotations_3d'][batch_id]", '[-1, 3, 3]'], {}), "(sample['rotations_3d'][batch_id], [-1, 3, 3])\n", (22784, 22830), True, 'import tensorflow as tf\n'), ((24340, 24362), 're.split', 're.split', (['"""\\\\s+"""', 'line'], {}), "('\\\\s+', line)\n", (24348, 24362), False, 'import re\n'), ((1472, 1494), 'numpy.ones', 'np.ones', (['centers.shape'], {}), '(centers.shape)\n', (1479, 1494), True, 'import numpy as np\n'), ((1535, 1557), 'numpy.ones', 'np.ones', (['centers.shape'], {}), '(centers.shape)\n', (1542, 1557), True, 'import numpy as np\n'), ((1598, 1620), 'numpy.ones', 'np.ones', (['centers.shape'], {}), '(centers.shape)\n', (1605, 1620), True, 'import numpy as np\n'), ((4552, 4569), 'tensorflow.ones', 'tf.ones', (['[1, 512]'], {}), '([1, 512])\n', (4559, 4569), True, 'import tensorflow as tf\n'), ((4617, 4648), 'tensorflow.reshape', 'tf.reshape', (["sample['k']", '[3, 3]'], {}), "(sample['k'], [3, 3])\n", (4627, 4648), True, 'import tensorflow as tf\n'), ((6468, 6485), 'tensorflow.ones', 'tf.ones', (['[1, 512]'], {}), '([1, 512])\n', (6475, 6485), True, 'import tensorflow as tf\n'), ((6533, 6564), 'tensorflow.reshape', 'tf.reshape', (["sample['k']", '[3, 3]'], {}), "(sample['k'], [3, 3])\n", (6543, 6564), True, 'import tensorflow as tf\n'), ((6949, 6994), 'tensorflow.reshape', 'tf.reshape', (["sample['rotations_3d'][i]", '[3, 3]'], {}), "(sample['rotations_3d'][i], [3, 3])\n", (6959, 6994), True, 'import tensorflow as tf\n'), ((14269, 14372), 'matplotlib.pyplot.plot', 'plt.plot', (['[x_min, x_max, x_max, x_min, x_min]', '[y_min, y_min, y_max, y_max, y_min]'], {'linestyle': 'style'}), '([x_min, x_max, x_max, x_min, x_min], [y_min, y_min, y_max, y_max,\n y_min], linestyle=style)\n', (14277, 14372), True, 'import matplotlib.pyplot as plt\n'), ((27121, 27171), 'tensorflow.io.decode_image', 'tf.io.decode_image', (["sample['image_data'][batch_id]"], {}), "(sample['image_data'][batch_id])\n", (27139, 27171), True, 'import tensorflow as tf\n'), ((2139, 2166), 'numpy.ones', 'np.ones', (['[height, width, 1]'], {}), '([height, width, 1])\n', (2146, 2166), True, 'import numpy as np\n'), ((10419, 10474), 'tensorflow.reshape', 'tf.reshape', (["sample['rotations_3d'][batch_id][i]", '[3, 3]'], {}), "(sample['rotations_3d'][batch_id][i], [3, 3])\n", (10429, 10474), True, 'import tensorflow as tf\n'), ((12618, 12640), 'numpy.ones', 'np.ones', (['[256, 256, 1]'], {}), '([256, 256, 1])\n', (12625, 12640), True, 'import numpy as np\n'), ((21676, 21725), 'tensorflow.reshape', 'tf.reshape', (["detections['rotations_3d'][i]", '[3, 3]'], {}), "(detections['rotations_3d'][i], [3, 3])\n", (21686, 21725), True, 'import tensorflow as tf\n'), ((22938, 22993), 'tensorflow.reshape', 'tf.reshape', (["sample['rotations_3d'][batch_id][i]", '[3, 3]'], {}), "(sample['rotations_3d'][batch_id][i], [3, 3])\n", (22948, 22993), True, 'import tensorflow as tf\n'), ((15288, 15332), 'numpy.ones', 'np.ones', (['[image.shape[0], image.shape[1], 1]'], {}), '([image.shape[0], image.shape[1], 1])\n', (15295, 15332), True, 'import numpy as np\n'), ((14883, 14905), 'numpy.ones', 'np.ones', (['[256, 256, 1]'], {}), '([256, 256, 1])\n', (14890, 14905), True, 'import numpy as np\n')]
"""A module to help perform analyses on various observatioanl studies. This module was implemented following studies of M249, Book 1. Dependencies: - **scipy** - **statsmodels** - **pandas** - **numpy** """ from __future__ import annotations as _annotations import math as _math from scipy import stats as _st from statsmodels.stats import contingency_tables as _tables import pandas as _pd import numpy as _np def riskratio(obs: _np.ndarray, alpha: float = 0.05) -> _pd.DataFrame: """Return the point and (1-alpha)% confidence interval estimates for the relative risk. Args: alpha: Significance level for the confidence interval. Returns: Point and (1-alpha)% confidence interval estimates for\ the relative risk. """ z: float = _st.norm().ppf(1-alpha/2) a = obs[0, 1] n1: int = _np.sum(obs[0]) df = _pd.DataFrame(index=["riskratio", "stderr", "lower", "upper"]) # add the reference category results df["Exposed1 (-)"] = [1.0, 0.0, "NA", "NA"] # gather results from array for i in range(1, obs.shape[0]): # get exposure results c = obs[i, 1] n2: int = _np.sum(obs[i]) # calculate the risk ratio rr: float = (c/n2) / (a/n1) stderr: float = _math.sqrt((1/a - 1/n1) + (1/c - 1/n2)) ci: tuple[float, float] = ( rr * _math.exp(-z * stderr), rr * _math.exp(z * stderr) ) # append to df df[f"Exposed{i+1} (+)"] = [rr, stderr, ci[0], ci[1]] return df.T def oddsratio(obs: _np.ndarray, alpha: float = 0.05) -> _pd.DataFrame: """Return the point and (1-alpha)% confidence interval estimates for the odds ratio. Args: alpha: Significance level for the confidence interval. Returns: Point and (1-alpha)% confidence interval estimates for\ the odds ratio. """ # gather results z: float = _st.norm().ppf(1-alpha/2) a: float = obs[0, 0] b: float = obs[0, 1] df = _pd.DataFrame(index=["oddsratio", "stderr", "lower", "upper"]) # add the reference category results df["Exposed1 (-)"] = [1.0, 0.0, "NA", "NA"] # gather results from array for i in range(1, obs.shape[0]): # get exposure results c: float = obs[i, 0] d: float = obs[i, 1] # calculate the odds ratio or_: float = (a * d) / (b * c) stderr: float = _math.sqrt(1/a + 1/b + 1/c + 1/d) ci: tuple[float, float] =( or_ * _math.exp(-z * stderr), or_ * _math.exp(z * stderr) ) # append to df df[f"Exposed{i+1} (+)"] = [or_, stderr, ci[0], ci[1]] return df.T def expectedfreq(obs: _np.ndarray) -> _np.ndarray: """Return the expected frequencies from a contingency table under the hypothesis of no association. Returns: Expected frequencies. """ return _st.contingency.expected_freq(obs) def chisqcontribs(obs: _np.ndarray) -> _np.ndarray: """Return the chi-squared contributions for each observation used in a chi-squared test of no association. Returns: chi-squared contributions. """ exp = expectedfreq(obs) contribs = _np.divide(_np.square(obs-exp), exp) return contribs def chisqtest( obs: _np.ndarray) -> _pd.DataFrame: """Return the results of a chi-squared test of no association. Returns: Results of a chi-squared test of no association. """ res = _st.chi2_contingency(obs, correction=False) df = _pd.DataFrame(index=["chisq", "pval", "df"]) df["result"] = [res[0], res[1], res[2]] return df.T def aggregate(obs) -> _np.ndarray: """Return an aggregated array. """ agg: _np.ndarray = _np.empty((2, 2)) for table in obs: agg += table return agg def adjusted_oddsratio(obs: _np.ndarray, alpha: float = 0.05) -> _pd.DataFrame: """Return the point and (1-alpha)% confidence interval estimates for the adjusted odds ratio. It uses the Mantel-Haenszel odds ratio. Args: alpha: Significance level for the confidence interval. Returns: Point and (1-alpha)% confidence interval estimates for\ the adjusted odds ratio. """ strattable = _tables.StratifiedTable(obs.tolist()) est = strattable.oddsratio_pooled stderr = strattable.logodds_pooled_se ci = strattable.oddsratio_pooled_confint(alpha) """ elif isinstance(table, OneToOneMatched): est = table.table[0][1] /table.table[1][0] se = (1/table.table[0][1] + 1/table.table[1][0]) ** 0.5 zscore = _st.norm.ppf(1-alpha/2) ci = (est * _exp(-zscore * se), est * _exp(zscore * se)) else: "Not defined for table type." """ df = _pd.DataFrame(index=["oddsratio", "stderr", "lower", "upper"]) df["result"] = [est, stderr, ci[0], ci[1]] return df.T def crude_oddsratio(obs: _np.ndarray, alpha: float = 0.05) -> _pd.DataFrame: """Return the point and (1-alpha)% confidence interval estimates for the crude odds ratio. Args: alpha: Significance level for the confidence interval. Returns: Point and (1-alpha)% confidence interval estimates for\ the crude odds ratio. """ return oddsratio(aggregate(obs), alpha) def test_equalodds(obs: _np.ndarray) -> _pd.DataFrame: """Return the results test of the null hypothesis that the odds ratio is the same in all _k_ strata. This is the Tarone test. Args: adjust: If true, use the Tarone adjustment to achieve the chi^2\ asymptotic distribution. Returns: test statistic and the p-value. """ strattable = _tables.StratifiedTable(obs.tolist()) res = strattable.test_equal_odds(True) df = _pd.DataFrame(index=["chisq", "pval"]) df["result"] = [res.statistic, res.pvalue] return df.T def test_nullodds(obs: _np.ndarray) -> _pd.DataFrame: """Return the results of a test of the null hypothesis of no association between the exposure and the disease, adjusted for the stratifying variable. Uses the Mantel-Haenszel test. Returns: test statistic and the p-value. """ strattable = _tables.StratifiedTable(obs.tolist()) res = strattable.test_null_odds(False) df = _pd.DataFrame(index=["chisq", "pval"]) df["result"] = [res.statistic, res.pvalue] return df.T def matched_oddsratio(obs: _np.ndarray, alpha: float = 0.05) -> _pd.DataFrame: """Return the point and (1-alpha)% confidence interval estimates for the odds ratio in a 1-1 matched case-control study. Args: alpha: Significance level for the confidence interval. Returns: Point and (1-alpha)% confidence interval estimates for\ the odds ratio. """ or_ = obs[1, 0] / obs[0, 1] stderr = _math.sqrt(1/obs[1, 0] + 1/obs[0, 1]) z = _st.norm.ppf(1-alpha/2) ci = (or_ * _math.exp(-z * stderr), or_ * _math.exp(z * stderr)) df = _pd.DataFrame(index=["oddsratio", "stderr", "lcb", "ucb"]) df["result"] = [or_, stderr, ci[0], ci[1]] return df.T def mcnemar(obs: _np.ndarray) -> _pd.DataFrame: """Return the results of a test of the null hypothesis of no association in a 1-1 matched case-control study. This is the McNemar test. Returns: test statistic and the p-value. """ f = obs[1, 0] g = obs[0, 1] num = (abs(f-g) - 1) ** 2 den = f + g chisq = num / den pval = _st.chi2(df=1).sf(chisq) df = _pd.DataFrame(index=["chisq", "pval"]) df["result"] = [chisq, pval] return df.T def odds(obs: _np.ndarray) -> _pd.DataFrame: """Return the odds of disease for each exposure dose in a dose-response\ analysis. Args: obs: Rx2 contingency table representing representing dose-response\ analysis. Returns: Odds of disease given exposure-dose. """ return _np.divide(obs[:, 1], obs[:, 0]) def doseexposure_odds(obs: _np.ndarray) -> _pd.DataFrame: """Return the odds and log-odds of disease for each exposure dose\ in a dose-response analysis. Args: obs: Rx2 contingency table representing representing dose-response\ analysis. Returns: Dataframe showing odds, log-odds of each exposure-dose """ od = odds(obs) log_od = _np.log(od) df = _pd.DataFrame(index=["odds", "log-odds"]) for i in range(obs.shape[0]): df[f"Exposed{i+1}"] = [od[i], log_od[i]] return df.T def midranks(obs: _np.ndarray) -> _np.ndarray: """Return the midrank scores for an array. Ref: https://online.stat.psu.edu/stat504/lesson/4/4.1/4.1.2 Args: obs: Rx2 contingency table representing representing a\ dose-response analysis. Returns: Midranks of each dose to be used as the weighted scores. """ scores = _np.empty(shape=(obs.shape[0])) rowsums = obs.sum(1) rowcounter = 0 for i in range(len(rowsums)): scores[i] += (rowcounter + ((1 + rowsums[i]) / 2)) rowcounter += rowsums[i] return scores def weighted_means(obs: _np.ndarray, scores: _np.ndarray) -> tuple[float, float]: """Return the weighted row and column means of an Rx2 contingency table. Args: obs: Rx2 contingency table representing representing a\ dose-response analysis. scores: Weightings of each dose. Returns: Weighted row mean, weighted col mean """ r, c = scores[0], scores[1] ubar, vbar = 0, 0 for i in range(obs.shape[0]): for j in range(obs.shape[1]): ubar += ((r[i] * obs[i, j]) / obs.sum()) vbar += ((c[j] * obs[i, j]) / obs.sum()) return ubar, vbar def cov(obs: _np.ndarray, scores: _np.ndarray) -> float: """Return the covariance of an RxC array. Args: obs: Rx2 contingency table representing representing a\ dose-response analysis. Returns: Covariance of rows and columns. """ r, c = scores[0], scores[1] rbar, cbar = weighted_means(obs, r, c) cov = 0 for i in range(len(r)): for j in range(len(c)): cov += (r[i] - rbar) * (c[j] - cbar) * obs[i, j] return cov def stddev(obs: _np.ndarray, scores: _np.ndarray) -> float: """Return the standard deviation of the rows and columns. Args: obs: Rx2 contingency table representing representing a\ dose-response analysis. Returns: Covariance of rows and columns. """ r, c = scores[0], scores[1] rbar, cbar = weighted_means(obs, scores) rvar, cvar = 0, 0 for i in range(len(r)): for j in range(len(c)): rvar += (r[i] - rbar)**2 * obs[i, j] cvar += (c[j] - cbar)**2 * obs[i, j] return _math.sqrt(rvar), _math.sqrt(cvar) def corrcoeff(obs: _np.ndarray, scores: _np.ndarray) -> float: """Return Pearson's correlation coefficients for an array. Args: obs: [description] Returns: Pearson's correlation coefficient, r """ return cov(obs, scores) / (stddev(obs, scores)[0] * stddev(obs, scores)[1]) def chisq_lineartrend(obs: _np.ndarray) -> _pd.DataFrame: """Return the test statistic and p-value for a chi-squared test of no linear trend. Reference: https://online.stat.psu.edu/stat504/book/export/html/710 Args: obs: Rx2 contingency table representing representing dose-response\ analysis. Returns: chi-square, p-value as a DataFrame. """ # select the ranks => row score then col score scores = midranks(obs), [0, 1] # gather results r = corrcoeff(obs, scores) chisq = (obs.sum() - 1) * (r ** 2) pval = _st.chi2(df=1).sf(chisq) # results to dataframe df = _pd.DataFrame(index=["chisq", "pval"]) df["result"] = [chisq, pval] return df.T def samplesize( alpha: float, gamma: float, prop_treat: float, prop_cont: float, loss: float = 0.0 ) -> float: """Return the sample size for a trial with equal sized treatment and\ control groups. Args: alpha: Significance level. gamma: Power of test. prop_treat: Design value, estimated value of P(Disease|Treatment). prop_cont: Design value, estimated value of P(Disease|Control). loss: estimated loss to follow-up as a percentage. Default is 0.0 Returns: Required sample size of each group, rounded to 6 dp. """ qsig = _st.norm().ppf(1-alpha/2) qpow = _st.norm().ppf(gamma) prop_zero = 0.5 * (prop_treat + prop_cont) size = ( 2 * ((qsig + qpow) ** 2) * prop_zero * (1 - prop_zero) / ((prop_treat - prop_cont) ** 2) ) adj: float = 1 / (1-(loss/100)) return round(size * adj, 6) def power( size: int, alpha: float, prop_treat: float, prop_cont: float ) -> int: """Return the power available in trial with treatment, control groups\ of a given size. Args: size: Number of participants in a single. Note total size of\ trial would be 2 * size. alpha: Significance level. gamma: Power of test prop_treat: Design value, estimated value of P(Disease|Treatment) prop_cont: Design value, estimated value of P(Disease|Control) Returns: Power of the trial as a percentage, rounded to 6dp. """ prop_diff = abs(prop_treat - prop_cont) prop_zero = 0.5 * (prop_treat + prop_cont) qsig = _st.norm().ppf(1-alpha/2) qpow = prop_diff * _math.sqrt(size / (2*prop_zero*(1-prop_zero))) - qsig return round(100 * _st.norm().cdf(qpow), 6)
[ "pandas.DataFrame", "scipy.stats.norm.ppf", "numpy.divide", "scipy.stats.norm", "numpy.sum", "numpy.log", "math.sqrt", "math.exp", "numpy.empty", "numpy.square", "scipy.stats.chi2_contingency", "scipy.stats.chi2", "scipy.stats.contingency.expected_freq" ]
[((861, 876), 'numpy.sum', '_np.sum', (['obs[0]'], {}), '(obs[0])\n', (868, 876), True, 'import numpy as _np\n'), ((886, 948), 'pandas.DataFrame', '_pd.DataFrame', ([], {'index': "['riskratio', 'stderr', 'lower', 'upper']"}), "(index=['riskratio', 'stderr', 'lower', 'upper'])\n", (899, 948), True, 'import pandas as _pd\n'), ((2015, 2077), 'pandas.DataFrame', '_pd.DataFrame', ([], {'index': "['oddsratio', 'stderr', 'lower', 'upper']"}), "(index=['oddsratio', 'stderr', 'lower', 'upper'])\n", (2028, 2077), True, 'import pandas as _pd\n'), ((2900, 2934), 'scipy.stats.contingency.expected_freq', '_st.contingency.expected_freq', (['obs'], {}), '(obs)\n', (2929, 2934), True, 'from scipy import stats as _st\n'), ((3470, 3513), 'scipy.stats.chi2_contingency', '_st.chi2_contingency', (['obs'], {'correction': '(False)'}), '(obs, correction=False)\n', (3490, 3513), True, 'from scipy import stats as _st\n'), ((3523, 3567), 'pandas.DataFrame', '_pd.DataFrame', ([], {'index': "['chisq', 'pval', 'df']"}), "(index=['chisq', 'pval', 'df'])\n", (3536, 3567), True, 'import pandas as _pd\n'), ((3731, 3748), 'numpy.empty', '_np.empty', (['(2, 2)'], {}), '((2, 2))\n', (3740, 3748), True, 'import numpy as _np\n'), ((4755, 4817), 'pandas.DataFrame', '_pd.DataFrame', ([], {'index': "['oddsratio', 'stderr', 'lower', 'upper']"}), "(index=['oddsratio', 'stderr', 'lower', 'upper'])\n", (4768, 4817), True, 'import pandas as _pd\n'), ((5780, 5818), 'pandas.DataFrame', '_pd.DataFrame', ([], {'index': "['chisq', 'pval']"}), "(index=['chisq', 'pval'])\n", (5793, 5818), True, 'import pandas as _pd\n'), ((6305, 6343), 'pandas.DataFrame', '_pd.DataFrame', ([], {'index': "['chisq', 'pval']"}), "(index=['chisq', 'pval'])\n", (6318, 6343), True, 'import pandas as _pd\n'), ((6846, 6887), 'math.sqrt', '_math.sqrt', (['(1 / obs[1, 0] + 1 / obs[0, 1])'], {}), '(1 / obs[1, 0] + 1 / obs[0, 1])\n', (6856, 6887), True, 'import math as _math\n'), ((6892, 6919), 'scipy.stats.norm.ppf', '_st.norm.ppf', (['(1 - alpha / 2)'], {}), '(1 - alpha / 2)\n', (6904, 6919), True, 'from scipy import stats as _st\n'), ((6994, 7052), 'pandas.DataFrame', '_pd.DataFrame', ([], {'index': "['oddsratio', 'stderr', 'lcb', 'ucb']"}), "(index=['oddsratio', 'stderr', 'lcb', 'ucb'])\n", (7007, 7052), True, 'import pandas as _pd\n'), ((7526, 7564), 'pandas.DataFrame', '_pd.DataFrame', ([], {'index': "['chisq', 'pval']"}), "(index=['chisq', 'pval'])\n", (7539, 7564), True, 'import pandas as _pd\n'), ((7940, 7972), 'numpy.divide', '_np.divide', (['obs[:, 1]', 'obs[:, 0]'], {}), '(obs[:, 1], obs[:, 0])\n', (7950, 7972), True, 'import numpy as _np\n'), ((8369, 8380), 'numpy.log', '_np.log', (['od'], {}), '(od)\n', (8376, 8380), True, 'import numpy as _np\n'), ((8390, 8431), 'pandas.DataFrame', '_pd.DataFrame', ([], {'index': "['odds', 'log-odds']"}), "(index=['odds', 'log-odds'])\n", (8403, 8431), True, 'import pandas as _pd\n'), ((8907, 8936), 'numpy.empty', '_np.empty', ([], {'shape': 'obs.shape[0]'}), '(shape=obs.shape[0])\n', (8916, 8936), True, 'import numpy as _np\n'), ((11833, 11871), 'pandas.DataFrame', '_pd.DataFrame', ([], {'index': "['chisq', 'pval']"}), "(index=['chisq', 'pval'])\n", (11846, 11871), True, 'import pandas as _pd\n'), ((1178, 1193), 'numpy.sum', '_np.sum', (['obs[i]'], {}), '(obs[i])\n', (1185, 1193), True, 'import numpy as _np\n'), ((1289, 1334), 'math.sqrt', '_math.sqrt', (['(1 / a - 1 / n1 + (1 / c - 1 / n2))'], {}), '(1 / a - 1 / n1 + (1 / c - 1 / n2))\n', (1299, 1334), True, 'import math as _math\n'), ((2423, 2464), 'math.sqrt', '_math.sqrt', (['(1 / a + 1 / b + 1 / c + 1 / d)'], {}), '(1 / a + 1 / b + 1 / c + 1 / d)\n', (2433, 2464), True, 'import math as _math\n'), ((3215, 3236), 'numpy.square', '_np.square', (['(obs - exp)'], {}), '(obs - exp)\n', (3225, 3236), True, 'import numpy as _np\n'), ((10836, 10852), 'math.sqrt', '_math.sqrt', (['rvar'], {}), '(rvar)\n', (10846, 10852), True, 'import math as _math\n'), ((10854, 10870), 'math.sqrt', '_math.sqrt', (['cvar'], {}), '(cvar)\n', (10864, 10870), True, 'import math as _math\n'), ((803, 813), 'scipy.stats.norm', '_st.norm', ([], {}), '()\n', (811, 813), True, 'from scipy import stats as _st\n'), ((1930, 1940), 'scipy.stats.norm', '_st.norm', ([], {}), '()\n', (1938, 1940), True, 'from scipy import stats as _st\n'), ((6932, 6954), 'math.exp', '_math.exp', (['(-z * stderr)'], {}), '(-z * stderr)\n', (6941, 6954), True, 'import math as _math\n'), ((6962, 6983), 'math.exp', '_math.exp', (['(z * stderr)'], {}), '(z * stderr)\n', (6971, 6983), True, 'import math as _math\n'), ((7492, 7506), 'scipy.stats.chi2', '_st.chi2', ([], {'df': '(1)'}), '(df=1)\n', (7500, 7506), True, 'from scipy import stats as _st\n'), ((11772, 11786), 'scipy.stats.chi2', '_st.chi2', ([], {'df': '(1)'}), '(df=1)\n', (11780, 11786), True, 'from scipy import stats as _st\n'), ((12543, 12553), 'scipy.stats.norm', '_st.norm', ([], {}), '()\n', (12551, 12553), True, 'from scipy import stats as _st\n'), ((12580, 12590), 'scipy.stats.norm', '_st.norm', ([], {}), '()\n', (12588, 12590), True, 'from scipy import stats as _st\n'), ((13552, 13562), 'scipy.stats.norm', '_st.norm', ([], {}), '()\n', (13560, 13562), True, 'from scipy import stats as _st\n'), ((13601, 13653), 'math.sqrt', '_math.sqrt', (['(size / (2 * prop_zero * (1 - prop_zero)))'], {}), '(size / (2 * prop_zero * (1 - prop_zero)))\n', (13611, 13653), True, 'import math as _math\n'), ((1383, 1405), 'math.exp', '_math.exp', (['(-z * stderr)'], {}), '(-z * stderr)\n', (1392, 1405), True, 'import math as _math\n'), ((1412, 1433), 'math.exp', '_math.exp', (['(z * stderr)'], {}), '(z * stderr)\n', (1421, 1433), True, 'import math as _math\n'), ((2512, 2534), 'math.exp', '_math.exp', (['(-z * stderr)'], {}), '(-z * stderr)\n', (2521, 2534), True, 'import math as _math\n'), ((2542, 2563), 'math.exp', '_math.exp', (['(z * stderr)'], {}), '(z * stderr)\n', (2551, 2563), True, 'import math as _math\n'), ((13678, 13688), 'scipy.stats.norm', '_st.norm', ([], {}), '()\n', (13686, 13688), True, 'from scipy import stats as _st\n')]
import os import sys from sys import exit, argv, path from os.path import realpath, dirname import csv import yaml import numpy as np CODE_DIR = '{}/..'.format(dirname(realpath(__file__))) path.insert(1, '{}/src'.format(CODE_DIR)) use_settings_path = False if 'hde_glm' not in sys.modules: import hde_glm as glm __version__ = "unknown" EXIT_SUCCESS = 0 EXIT_FAILURE = 1 """Run parameters""" device_or_run_index = argv[1] recorded_system = argv[2] if len(argv) > 5: data_path = argv[5] else: data_path = '{}/data'.format(CODE_DIR) if device_or_run_index == 'cluster': os.environ['OPENBLAS_NUM_THREADS'] = '1' os.environ['MKL_NUM_THREADS'] = '1' os.environ['NUMEXPR_NUM_THREADS'] = '1' os.environ['OMP_NUM_THREADS'] = '1' def main_Simulation(): # Get run index for computation on the cluster if device_or_run_index == 'cluster': past_range_index = (int(os.environ['SGE_TASK_ID']) - 1) else: past_range_index = int(device_or_run_index) # Load settings with open('{}/settings/{}_glm.yaml'.format(CODE_DIR, recorded_system), 'r') as glm_settings_file: glm_settings = yaml.load(glm_settings_file, Loader=yaml.BaseLoader) if use_settings_path == True: ANALYSIS_DIR = glm_settings['ANALYSIS_DIR'] else: ANALYSIS_DIR = '{}/analysis/{}/glm_ground_truth'.format(CODE_DIR, recorded_system) # Create csv with header if past_range_index == 0: glm_csv_file_name = '{}/glm_estimates_BIC.csv'.format( ANALYSIS_DIR) with open(glm_csv_file_name, 'w', newline='') as glm_csv_file: writer = csv.DictWriter(glm_csv_file, fieldnames=[ "T", "number_of_bins_d", "scaling_kappa", "first_bin_size", "embedding_mode_optimization", "BIC", "R_GLM"]) writer.writeheader() # Load the 900 minute simulated recording DATA_DIR = '{}/{}'.format(data_path, recorded_system) spiketimes = np.load('{}/spiketimes_900min.npy'.format(DATA_DIR)) # Preprocess spiketimes and compute binary counts for current spiking spiketimes, counts = glm.preprocess_spiketimes( spiketimes, glm_settings) # Get the past range for which R should be estimated embedding_past_range_set = np.array( glm_settings['embedding_past_range_set']).astype(float) past_range = embedding_past_range_set[past_range_index] # Compute optimized history dependence for given past range glm_estimates, BIC = glm.compute_estimates_Simulation(past_range, spiketimes, counts, glm_settings) # Save results to glm_benchmarks.csv glm.save_glm_estimates_to_CSV_Simulation( past_range, glm_estimates, BIC, glm_settings, ANALYSIS_DIR) return EXIT_SUCCESS def main_Experiments(): rec_length = '90min' # Get run index for computation on the cluster if device_or_run_index == 'cluster': neuron_index = (int(os.environ['SGE_TASK_ID']) - 1) else: neuron_index = int(device_or_run_index) # Load settings with open('{}/settings/{}_glm.yaml'.format(CODE_DIR, recorded_system), 'r') as glm_settings_file: glm_settings = yaml.load(glm_settings_file, Loader=yaml.BaseLoader) if use_settings_path == True: ANALYSIS_DIR = glm_settings['ANALYSIS_DIR'] else: ANALYSIS_DIR = '{}/analysis/{}/analysis_full_bbc'.format(CODE_DIR, recorded_system) # Load and preprocess spiketimes and compute binary counts for current spiking spiketimes, counts = glm.load_and_preprocess_spiketimes_experiments( recorded_system, neuron_index, glm_settings, data_path) # Get the past range for which R should be estimated temporal_depth_bbc = glm.get_temporal_depth( rec_length, neuron_index, ANALYSIS_DIR, regularization_method = 'bbc') embedding_parameters_bbc, analysis_num_str = glm.load_embedding_parameters( rec_length, neuron_index, ANALYSIS_DIR, regularization_method = 'bbc') embedding_parameters_bbc = embedding_parameters_bbc[:, embedding_parameters_bbc[0] == temporal_depth_bbc] # Compute optimized estimate of R for given past range glm_estimates, BIC = glm.compute_estimates_Experiments( temporal_depth_bbc, embedding_parameters_bbc, spiketimes, counts, glm_settings) # Save results to glm_benchmarks.csv glm.save_glm_estimates_to_CSV_Experiments( temporal_depth_bbc, embedding_parameters_bbc, glm_estimates, BIC, glm_settings, ANALYSIS_DIR, analysis_num_str) return EXIT_SUCCESS if __name__ == "__main__": if (recorded_system == 'glif_22s_kernel' or recorded_system == 'glif_1s_kernel'): exit(main_Simulation()) else: exit(main_Experiments())
[ "yaml.load", "hde_glm.save_glm_estimates_to_CSV_Experiments", "hde_glm.get_temporal_depth", "hde_glm.preprocess_spiketimes", "hde_glm.load_and_preprocess_spiketimes_experiments", "hde_glm.compute_estimates_Simulation", "hde_glm.compute_estimates_Experiments", "os.path.realpath", "hde_glm.save_glm_es...
[((2091, 2142), 'hde_glm.preprocess_spiketimes', 'glm.preprocess_spiketimes', (['spiketimes', 'glm_settings'], {}), '(spiketimes, glm_settings)\n', (2116, 2142), True, 'import hde_glm as glm\n'), ((2465, 2543), 'hde_glm.compute_estimates_Simulation', 'glm.compute_estimates_Simulation', (['past_range', 'spiketimes', 'counts', 'glm_settings'], {}), '(past_range, spiketimes, counts, glm_settings)\n', (2497, 2543), True, 'import hde_glm as glm\n'), ((2590, 2694), 'hde_glm.save_glm_estimates_to_CSV_Simulation', 'glm.save_glm_estimates_to_CSV_Simulation', (['past_range', 'glm_estimates', 'BIC', 'glm_settings', 'ANALYSIS_DIR'], {}), '(past_range, glm_estimates, BIC,\n glm_settings, ANALYSIS_DIR)\n', (2630, 2694), True, 'import hde_glm as glm\n'), ((3480, 3586), 'hde_glm.load_and_preprocess_spiketimes_experiments', 'glm.load_and_preprocess_spiketimes_experiments', (['recorded_system', 'neuron_index', 'glm_settings', 'data_path'], {}), '(recorded_system,\n neuron_index, glm_settings, data_path)\n', (3526, 3586), True, 'import hde_glm as glm\n'), ((3675, 3770), 'hde_glm.get_temporal_depth', 'glm.get_temporal_depth', (['rec_length', 'neuron_index', 'ANALYSIS_DIR'], {'regularization_method': '"""bbc"""'}), "(rec_length, neuron_index, ANALYSIS_DIR,\n regularization_method='bbc')\n", (3697, 3770), True, 'import hde_glm as glm\n'), ((3828, 3930), 'hde_glm.load_embedding_parameters', 'glm.load_embedding_parameters', (['rec_length', 'neuron_index', 'ANALYSIS_DIR'], {'regularization_method': '"""bbc"""'}), "(rec_length, neuron_index, ANALYSIS_DIR,\n regularization_method='bbc')\n", (3857, 3930), True, 'import hde_glm as glm\n'), ((4189, 4306), 'hde_glm.compute_estimates_Experiments', 'glm.compute_estimates_Experiments', (['temporal_depth_bbc', 'embedding_parameters_bbc', 'spiketimes', 'counts', 'glm_settings'], {}), '(temporal_depth_bbc,\n embedding_parameters_bbc, spiketimes, counts, glm_settings)\n', (4222, 4306), True, 'import hde_glm as glm\n'), ((4358, 4519), 'hde_glm.save_glm_estimates_to_CSV_Experiments', 'glm.save_glm_estimates_to_CSV_Experiments', (['temporal_depth_bbc', 'embedding_parameters_bbc', 'glm_estimates', 'BIC', 'glm_settings', 'ANALYSIS_DIR', 'analysis_num_str'], {}), '(temporal_depth_bbc,\n embedding_parameters_bbc, glm_estimates, BIC, glm_settings,\n ANALYSIS_DIR, analysis_num_str)\n', (4399, 4519), True, 'import hde_glm as glm\n'), ((169, 187), 'os.path.realpath', 'realpath', (['__file__'], {}), '(__file__)\n', (177, 187), False, 'from os.path import realpath, dirname\n'), ((1142, 1194), 'yaml.load', 'yaml.load', (['glm_settings_file'], {'Loader': 'yaml.BaseLoader'}), '(glm_settings_file, Loader=yaml.BaseLoader)\n', (1151, 1194), False, 'import yaml\n'), ((3131, 3183), 'yaml.load', 'yaml.load', (['glm_settings_file'], {'Loader': 'yaml.BaseLoader'}), '(glm_settings_file, Loader=yaml.BaseLoader)\n', (3140, 3183), False, 'import yaml\n'), ((1618, 1774), 'csv.DictWriter', 'csv.DictWriter', (['glm_csv_file'], {'fieldnames': "['T', 'number_of_bins_d', 'scaling_kappa', 'first_bin_size',\n 'embedding_mode_optimization', 'BIC', 'R_GLM']"}), "(glm_csv_file, fieldnames=['T', 'number_of_bins_d',\n 'scaling_kappa', 'first_bin_size', 'embedding_mode_optimization', 'BIC',\n 'R_GLM'])\n", (1632, 1774), False, 'import csv\n'), ((2241, 2291), 'numpy.array', 'np.array', (["glm_settings['embedding_past_range_set']"], {}), "(glm_settings['embedding_past_range_set'])\n", (2249, 2291), True, 'import numpy as np\n')]
import numpy as np # type: ignore import pytest # type: ignore # TODO: remove NOQA when isort is fixed from layg.emulator.cholesky_nn_emulator import ( # NOQA all_monomials, monomials_deg, n_coef, ) @pytest.mark.parametrize( ["n", "delta", "true"], [ # Degree 0 -> only 1 (1, 0, 1), (2, 0, 1), (8, 0, 1), # Degree 1 -> n + 1 (1, 1, 2), (2, 1, 3), (8, 1, 9), # Degree 2 (1, 2, 3), (2, 2, 6), ], ) def test_n_coef(n, delta, true): assert n_coef(n, delta) == true @pytest.mark.parametrize( ["x", "delta", "true"], [ # Degree 0 -> only 1 (np.arange(1), 0, np.array([1])), (np.arange(2), 0, np.array([1])), (np.arange(8), 0, np.array([1])), # Degree 1 -> only 1 (np.arange(1), 1, np.concatenate(([1], np.arange(1)))), (np.arange(2), 1, np.concatenate(([1], np.arange(2)))), (np.arange(8), 1, np.concatenate(([1], np.arange(8)))), # Degree 2 (np.arange(1), 2, np.concatenate(([1], np.arange(1), np.arange(1) ** 2))), ], ) def test_monomials(x, delta, true): assert np.allclose(np.sort(all_monomials(x, delta)), np.sort(true)) @pytest.mark.parametrize( ["x", "delta", "true"], [ # Degree 1 -> linear (np.arange(1, 2), 1, np.array([1])), (np.arange(1, 3), 1, np.array([1, 2])), # Degree 2 (np.arange(1, 2), 2, np.array([1])), (np.arange(2, 3), 2, np.array([4])), (np.arange(1, 3), 2, np.array([1, 2, 4])), (np.arange(1, 4), 2, np.array([1, 2, 3, 4, 6, 9])), # Degree 3 (np.arange(2, 3), 3, np.array([8])), (np.arange(1, 3), 3, np.array([1, 2, 4, 8])), (np.arange(2, 4), 3, np.array([8, 12, 18, 27])), ], ) def test_monomials_deg(x, delta, true): assert np.allclose(np.sort(monomials_deg(x, delta)), np.sort(true))
[ "layg.emulator.cholesky_nn_emulator.monomials_deg", "layg.emulator.cholesky_nn_emulator.all_monomials", "layg.emulator.cholesky_nn_emulator.n_coef", "numpy.sort", "numpy.arange", "numpy.array", "pytest.mark.parametrize" ]
[((218, 360), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (["['n', 'delta', 'true']", '[(1, 0, 1), (2, 0, 1), (8, 0, 1), (1, 1, 2), (2, 1, 3), (8, 1, 9), (1, 2, 3\n ), (2, 2, 6)]'], {}), "(['n', 'delta', 'true'], [(1, 0, 1), (2, 0, 1), (8, \n 0, 1), (1, 1, 2), (2, 1, 3), (8, 1, 9), (1, 2, 3), (2, 2, 6)])\n", (241, 360), False, 'import pytest\n'), ((559, 575), 'layg.emulator.cholesky_nn_emulator.n_coef', 'n_coef', (['n', 'delta'], {}), '(n, delta)\n', (565, 575), False, 'from layg.emulator.cholesky_nn_emulator import all_monomials, monomials_deg, n_coef\n'), ((1227, 1240), 'numpy.sort', 'np.sort', (['true'], {}), '(true)\n', (1234, 1240), True, 'import numpy as np\n'), ((1928, 1941), 'numpy.sort', 'np.sort', (['true'], {}), '(true)\n', (1935, 1941), True, 'import numpy as np\n'), ((1201, 1224), 'layg.emulator.cholesky_nn_emulator.all_monomials', 'all_monomials', (['x', 'delta'], {}), '(x, delta)\n', (1214, 1224), False, 'from layg.emulator.cholesky_nn_emulator import all_monomials, monomials_deg, n_coef\n'), ((684, 696), 'numpy.arange', 'np.arange', (['(1)'], {}), '(1)\n', (693, 696), True, 'import numpy as np\n'), ((701, 714), 'numpy.array', 'np.array', (['[1]'], {}), '([1])\n', (709, 714), True, 'import numpy as np\n'), ((726, 738), 'numpy.arange', 'np.arange', (['(2)'], {}), '(2)\n', (735, 738), True, 'import numpy as np\n'), ((743, 756), 'numpy.array', 'np.array', (['[1]'], {}), '([1])\n', (751, 756), True, 'import numpy as np\n'), ((768, 780), 'numpy.arange', 'np.arange', (['(8)'], {}), '(8)\n', (777, 780), True, 'import numpy as np\n'), ((785, 798), 'numpy.array', 'np.array', (['[1]'], {}), '([1])\n', (793, 798), True, 'import numpy as np\n'), ((839, 851), 'numpy.arange', 'np.arange', (['(1)'], {}), '(1)\n', (848, 851), True, 'import numpy as np\n'), ((903, 915), 'numpy.arange', 'np.arange', (['(2)'], {}), '(2)\n', (912, 915), True, 'import numpy as np\n'), ((967, 979), 'numpy.arange', 'np.arange', (['(8)'], {}), '(8)\n', (976, 979), True, 'import numpy as np\n'), ((1050, 1062), 'numpy.arange', 'np.arange', (['(1)'], {}), '(1)\n', (1059, 1062), True, 'import numpy as np\n'), ((1902, 1925), 'layg.emulator.cholesky_nn_emulator.monomials_deg', 'monomials_deg', (['x', 'delta'], {}), '(x, delta)\n', (1915, 1925), False, 'from layg.emulator.cholesky_nn_emulator import all_monomials, monomials_deg, n_coef\n'), ((1342, 1357), 'numpy.arange', 'np.arange', (['(1)', '(2)'], {}), '(1, 2)\n', (1351, 1357), True, 'import numpy as np\n'), ((1362, 1375), 'numpy.array', 'np.array', (['[1]'], {}), '([1])\n', (1370, 1375), True, 'import numpy as np\n'), ((1387, 1402), 'numpy.arange', 'np.arange', (['(1)', '(3)'], {}), '(1, 3)\n', (1396, 1402), True, 'import numpy as np\n'), ((1407, 1423), 'numpy.array', 'np.array', (['[1, 2]'], {}), '([1, 2])\n', (1415, 1423), True, 'import numpy as np\n'), ((1454, 1469), 'numpy.arange', 'np.arange', (['(1)', '(2)'], {}), '(1, 2)\n', (1463, 1469), True, 'import numpy as np\n'), ((1474, 1487), 'numpy.array', 'np.array', (['[1]'], {}), '([1])\n', (1482, 1487), True, 'import numpy as np\n'), ((1499, 1514), 'numpy.arange', 'np.arange', (['(2)', '(3)'], {}), '(2, 3)\n', (1508, 1514), True, 'import numpy as np\n'), ((1519, 1532), 'numpy.array', 'np.array', (['[4]'], {}), '([4])\n', (1527, 1532), True, 'import numpy as np\n'), ((1544, 1559), 'numpy.arange', 'np.arange', (['(1)', '(3)'], {}), '(1, 3)\n', (1553, 1559), True, 'import numpy as np\n'), ((1564, 1583), 'numpy.array', 'np.array', (['[1, 2, 4]'], {}), '([1, 2, 4])\n', (1572, 1583), True, 'import numpy as np\n'), ((1595, 1610), 'numpy.arange', 'np.arange', (['(1)', '(4)'], {}), '(1, 4)\n', (1604, 1610), True, 'import numpy as np\n'), ((1615, 1643), 'numpy.array', 'np.array', (['[1, 2, 3, 4, 6, 9]'], {}), '([1, 2, 3, 4, 6, 9])\n', (1623, 1643), True, 'import numpy as np\n'), ((1674, 1689), 'numpy.arange', 'np.arange', (['(2)', '(3)'], {}), '(2, 3)\n', (1683, 1689), True, 'import numpy as np\n'), ((1694, 1707), 'numpy.array', 'np.array', (['[8]'], {}), '([8])\n', (1702, 1707), True, 'import numpy as np\n'), ((1719, 1734), 'numpy.arange', 'np.arange', (['(1)', '(3)'], {}), '(1, 3)\n', (1728, 1734), True, 'import numpy as np\n'), ((1739, 1761), 'numpy.array', 'np.array', (['[1, 2, 4, 8]'], {}), '([1, 2, 4, 8])\n', (1747, 1761), True, 'import numpy as np\n'), ((1773, 1788), 'numpy.arange', 'np.arange', (['(2)', '(4)'], {}), '(2, 4)\n', (1782, 1788), True, 'import numpy as np\n'), ((1793, 1818), 'numpy.array', 'np.array', (['[8, 12, 18, 27]'], {}), '([8, 12, 18, 27])\n', (1801, 1818), True, 'import numpy as np\n'), ((877, 889), 'numpy.arange', 'np.arange', (['(1)'], {}), '(1)\n', (886, 889), True, 'import numpy as np\n'), ((941, 953), 'numpy.arange', 'np.arange', (['(2)'], {}), '(2)\n', (950, 953), True, 'import numpy as np\n'), ((1005, 1017), 'numpy.arange', 'np.arange', (['(8)'], {}), '(8)\n', (1014, 1017), True, 'import numpy as np\n'), ((1088, 1100), 'numpy.arange', 'np.arange', (['(1)'], {}), '(1)\n', (1097, 1100), True, 'import numpy as np\n'), ((1102, 1114), 'numpy.arange', 'np.arange', (['(1)'], {}), '(1)\n', (1111, 1114), True, 'import numpy as np\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import argparse import os import pathlib import io import re import string import tqdm import numpy as np import tensorflow as tf from tensorflow.keras import layers from modules.reader.reader import DataReader from modules.preprocessing.nlp import NLPPreprocessor from modules.modeling.word_embedding import Word2Vec SEED = 42 NUM_NS = 4 AUTOTUNE = tf.data.AUTOTUNE def main(args): ''' Download text corpus You will use a text file of Shakespeare's writing for this tutorial. Change the following line to run this code on your own data. ''' data_directory = args.data_directory size_data_directory = os.path.getsize(data_directory) path_to_file = os.path.join(data_directory,'shakespeare.txt') if size_data_directory <= 4096: tf.keras.utils.get_file( fname=path_to_file, origin="https://storage.googleapis.com/download.tensorflow.org/data/shakespeare.txt", extract=False, cache_subdir='.', cache_dir=data_directory) lines = DataReader(path_to_file).read_data_file() text_ds = tf.data.TextLineDataset(path_to_file).filter(lambda x: tf.cast(tf.strings.length(x), bool)) # Define the vocabulary size and number of words in a sequence. vocab_size = 4096 sequence_length = 10 # Use the text vectorization layer to normalize, split, and map strings to # integers. Set output_sequence_length length to pad all samples to same length. vectorize_layer = layers.experimental.preprocessing.TextVectorization( standardize=NLPPreprocessor().custom_standardization, max_tokens=vocab_size, output_mode='int', output_sequence_length=sequence_length ) ''' Call adapt on the text dataset to create vocabulary. ''' vectorize_layer.adapt(text_ds.batch(1024)) ''' Once the state of the layer has been adapted to represent the text corpus, the vocabulary can be accessed with get_vocabulary(). This function returns a list of all vocabulary tokens sorted (descending) by their frequency. ''' # Save the created vocabulary for reference. inverse_vocab = vectorize_layer.get_vocabulary() ''' The vectorize_layer can now be used to generate vectors for each element in the text_ds. ''' # Vectorize the data in text_ds. text_vector_ds = text_ds.batch(1024).prefetch(AUTOTUNE).map(vectorize_layer).unbatch() ''' Obtain sequences from the dataset You now have a tf.data.Dataset of integer encoded sentences. To prepare the dataset for training a Word2Vec model, flatten the dataset into a list of sentence vector sequences. This step is required as you would iterate over each sentence in the dataset to produce positive and negative examples. ''' sequences = list(text_vector_ds.as_numpy_iterator()) ''' Generate training examples from sequences sequences is now a list of int encoded sentences. Just call the generate_training_data() function defined earlier to generate training examples for the Word2Vec model. To recap, the function iterates over each word from each sequence to collect positive and negative context words. Length of target, contexts and labels should be same, representing the total number of training examples. ''' targets, contexts, labels = NLPPreprocessor().generate_training_data(sequences=sequences, window_size=2, num_ns=NUM_NS, vocab_size=vocab_size, seed=SEED) targets = np.array(targets) contexts = np.array(contexts)[:,:,0] labels = np.array(labels) print('\n') print(f"targets.shape: {targets.shape}") print(f"contexts.shape: {contexts.shape}") print(f"labels.shape: {labels.shape}") ''' Configure the dataset for performance To perform efficient batching for the potentially large number of training examples, use the tf.data.Dataset API. After this step, you would have a tf.data.Dataset object of (target_word, context_word), (label) elements to train your Word2Vec model! ''' BATCH_SIZE = 1024 BUFFER_SIZE = 10000 dataset = tf.data.Dataset.from_tensor_slices(((targets, contexts), labels)) dataset = dataset.shuffle(BUFFER_SIZE).batch(BATCH_SIZE, drop_remainder=True) print(dataset) ''' Add cache() and prefetch() to improve performance. ''' dataset = dataset.cache().prefetch(buffer_size=AUTOTUNE) print(dataset) ''' It's time to build your model! Instantiate your Word2Vec class with an embedding dimension of 128 (you could experiment with different values). Compile the model with the tf.keras.optimizers.Adam optimizer. ''' embedding_dim = 128 word2vec = Word2Vec(vocab_size, embedding_dim, NUM_NS) word2vec.compile(optimizer='adam', loss=tf.keras.losses.CategoricalCrossentropy(from_logits=True), metrics=['accuracy']) ''' Also define a callback to log training statistics for tensorboard. ''' tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir="logs") ''' Train the model with dataset prepared above for some number of epochs. ''' word2vec.fit(dataset, epochs=20, callbacks=[tensorboard_callback]) if __name__ == "__main__": MODEL_NAME = "speech-recognition-cnn.model" directory_of_script = os.path.dirname(os.path.realpath(__file__)) directory_of_model = os.path.join(directory_of_script,"model") directory_of_results = os.path.join(directory_of_script,"results") directory_of_data = os.path.join(directory_of_script,"DATA","Shakespeare") os.makedirs(directory_of_model,exist_ok=True) os.makedirs(directory_of_results,exist_ok=True) os.makedirs(directory_of_data,exist_ok=True) parser = argparse.ArgumentParser() parser.add_argument("-data_directory", help="Directory of location of the data for training", required=False, default=directory_of_data, nargs='?') # parser.add_argument("-path_model", help="Path of an existing model to use for prediction", required=False, default=os.path.join(directory_of_model,MODEL_NAME), nargs='?') # parser.add_argument("-NaN_imputation_feature_scaling_PCA_usage", help="Apply or not NaN imputation, Feature Scaling and PCA", required=False, choices=["False","True"], default="False", nargs='?') # parser.add_argument("-max_depth", help="Maximum depth of a tree. Increasing this value will make the model more complex and more likely to overfit. 0 is only accepted in lossguided growing policy when tree_method is set as hist or gpu_hist and it indicates no limit on depth. Beware that XGBoost aggressively consumes memory when training a deep tree. range: [0,∞] (0 is only accepted in lossguided growing policy when tree_method is set as hist or gpu_hist)", required=False, default=6, type=int, nargs='?') # parser.add_argument("-eta", help="Step size shrinkage used in update to prevents overfitting. After each boosting step, we can directly get the weights of new features, and eta shrinks the feature weights to make the boosting process more conservative. range: [0,1]", required=False, default=0.3, type=float, nargs='?') # parser.add_argument("-num_round", help="The number of rounds for boosting", required=False, default=100, type=int, nargs='?') args = parser.parse_args() main(args)
[ "modules.preprocessing.nlp.NLPPreprocessor", "os.makedirs", "argparse.ArgumentParser", "os.path.getsize", "modules.modeling.word_embedding.Word2Vec", "os.path.realpath", "tensorflow.data.Dataset.from_tensor_slices", "modules.reader.reader.DataReader", "tensorflow.keras.losses.CategoricalCrossentropy...
[((695, 726), 'os.path.getsize', 'os.path.getsize', (['data_directory'], {}), '(data_directory)\n', (710, 726), False, 'import os\n'), ((746, 793), 'os.path.join', 'os.path.join', (['data_directory', '"""shakespeare.txt"""'], {}), "(data_directory, 'shakespeare.txt')\n", (758, 793), False, 'import os\n'), ((3886, 3903), 'numpy.array', 'np.array', (['targets'], {}), '(targets)\n', (3894, 3903), True, 'import numpy as np\n'), ((3958, 3974), 'numpy.array', 'np.array', (['labels'], {}), '(labels)\n', (3966, 3974), True, 'import numpy as np\n'), ((4514, 4579), 'tensorflow.data.Dataset.from_tensor_slices', 'tf.data.Dataset.from_tensor_slices', (['((targets, contexts), labels)'], {}), '(((targets, contexts), labels))\n', (4548, 4579), True, 'import tensorflow as tf\n'), ((5111, 5154), 'modules.modeling.word_embedding.Word2Vec', 'Word2Vec', (['vocab_size', 'embedding_dim', 'NUM_NS'], {}), '(vocab_size, embedding_dim, NUM_NS)\n', (5119, 5154), False, 'from modules.modeling.word_embedding import Word2Vec\n'), ((5437, 5483), 'tensorflow.keras.callbacks.TensorBoard', 'tf.keras.callbacks.TensorBoard', ([], {'log_dir': '"""logs"""'}), "(log_dir='logs')\n", (5467, 5483), True, 'import tensorflow as tf\n'), ((5833, 5875), 'os.path.join', 'os.path.join', (['directory_of_script', '"""model"""'], {}), "(directory_of_script, 'model')\n", (5845, 5875), False, 'import os\n'), ((5902, 5946), 'os.path.join', 'os.path.join', (['directory_of_script', '"""results"""'], {}), "(directory_of_script, 'results')\n", (5914, 5946), False, 'import os\n'), ((5970, 6026), 'os.path.join', 'os.path.join', (['directory_of_script', '"""DATA"""', '"""Shakespeare"""'], {}), "(directory_of_script, 'DATA', 'Shakespeare')\n", (5982, 6026), False, 'import os\n'), ((6029, 6075), 'os.makedirs', 'os.makedirs', (['directory_of_model'], {'exist_ok': '(True)'}), '(directory_of_model, exist_ok=True)\n', (6040, 6075), False, 'import os\n'), ((6079, 6127), 'os.makedirs', 'os.makedirs', (['directory_of_results'], {'exist_ok': '(True)'}), '(directory_of_results, exist_ok=True)\n', (6090, 6127), False, 'import os\n'), ((6131, 6176), 'os.makedirs', 'os.makedirs', (['directory_of_data'], {'exist_ok': '(True)'}), '(directory_of_data, exist_ok=True)\n', (6142, 6176), False, 'import os\n'), ((6194, 6219), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (6217, 6219), False, 'import argparse\n'), ((837, 1035), 'tensorflow.keras.utils.get_file', 'tf.keras.utils.get_file', ([], {'fname': 'path_to_file', 'origin': '"""https://storage.googleapis.com/download.tensorflow.org/data/shakespeare.txt"""', 'extract': '(False)', 'cache_subdir': '"""."""', 'cache_dir': 'data_directory'}), "(fname=path_to_file, origin=\n 'https://storage.googleapis.com/download.tensorflow.org/data/shakespeare.txt'\n , extract=False, cache_subdir='.', cache_dir=data_directory)\n", (860, 1035), True, 'import tensorflow as tf\n'), ((3919, 3937), 'numpy.array', 'np.array', (['contexts'], {}), '(contexts)\n', (3927, 3937), True, 'import numpy as np\n'), ((5780, 5806), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (5796, 5806), False, 'import os\n'), ((1100, 1124), 'modules.reader.reader.DataReader', 'DataReader', (['path_to_file'], {}), '(path_to_file)\n', (1110, 1124), False, 'from modules.reader.reader import DataReader\n'), ((1156, 1193), 'tensorflow.data.TextLineDataset', 'tf.data.TextLineDataset', (['path_to_file'], {}), '(path_to_file)\n', (1179, 1193), True, 'import tensorflow as tf\n'), ((3453, 3470), 'modules.preprocessing.nlp.NLPPreprocessor', 'NLPPreprocessor', ([], {}), '()\n', (3468, 3470), False, 'from modules.preprocessing.nlp import NLPPreprocessor\n'), ((5220, 5277), 'tensorflow.keras.losses.CategoricalCrossentropy', 'tf.keras.losses.CategoricalCrossentropy', ([], {'from_logits': '(True)'}), '(from_logits=True)\n', (5259, 5277), True, 'import tensorflow as tf\n'), ((1219, 1239), 'tensorflow.strings.length', 'tf.strings.length', (['x'], {}), '(x)\n', (1236, 1239), True, 'import tensorflow as tf\n'), ((1628, 1645), 'modules.preprocessing.nlp.NLPPreprocessor', 'NLPPreprocessor', ([], {}), '()\n', (1643, 1645), False, 'from modules.preprocessing.nlp import NLPPreprocessor\n')]
#!/usr/bin/env python # coding=utf-8 ''' Author: <NAME> / Yulv Email: <EMAIL> Date: 2022-03-19 10:33:38 Motto: Entities should not be multiplied unnecessarily. LastEditors: <NAME> LastEditTime: 2022-03-23 00:32:15 FilePath: /Awesome-Ultrasound-Standard-Plane-Detection/src/ITN/utils/plane.py Description: Functions for plane manipulations. Init from https://github.com/yuanwei1989/plane-detection ''' import numpy as np import scipy.ndimage from utils import geometry def fit_plane(pts): """Fit a plane to a set of 3D points. Args: pts: [point_count, 3] Returns: n: normal vector of plane [3] c: centroid of plane [3] """ c = pts.mean(axis=0) A = pts - c u, s, vh = np.linalg.svd(A) n = vh[-1, :] # ensure z-component of normal vector is always consistent (eg. positive) if n[2] < 0: n = -n return n, c def project_on_plane(pts, n, c): """Project points onto a 2D plane. Args: pts: [point_count, 3] n: normal vector of plane [3] c: centroid of plane [3] Returns: pts_new: points projected onto the plane [point_count, 3] """ t = (np.dot(c, n) - np.dot(pts, n)) / np.dot(n, n) pts_new = pts + np.matmul(np.expand_dims(t, axis=1), np.expand_dims(n, axis=0)) return pts_new def fit_line(pts): """Fit a line to a set of 3D points. Args: pts: [point_count, 3] Returns: d: direction vector of line [3] c: a point on the line [3] """ c = pts.mean(axis=0) A = pts - c u, s, vh = np.linalg.svd(A) d = vh[0, :] # ensure x-component of direction vector is always consistent (eg. positive) if d[0] < 0: d = -d return d, c def extract_tform(landmarks, plane_name): """Compute the transformation that maps the reference xy-plane at origin to the GT standard plane. Args: landmarks: [landmark_count, 3] where landmark_count=16 plane_name: 'tv' or 'tc' Returns: trans_vec: translation vector [3] quat: quaternions [4] mat: 4x4 transformation matrix [4, 4] """ if plane_name == 'tv': # Landmarks lying on the TV plane landmarks_plane = np.vstack((landmarks[1:8], landmarks[12:14])) # Compute transformation z_vec, p_plane = fit_plane(landmarks_plane) landmarks_plane_proj = project_on_plane(landmarks_plane, z_vec, p_plane) landmarks_line = landmarks_plane_proj[[0, 1, 2, 7, 8], :] x_vec, p_line = fit_line(landmarks_line) y_vec = geometry.unit_vector(np.cross(z_vec, x_vec)) # 4x4 transformation matrix mat = np.eye(4) mat[:3, :3] = np.vstack((x_vec, y_vec, z_vec)).transpose() mat[:3, 3] = landmarks_plane_proj[0] # Quaternions and translation vector quat = geometry.quaternion_from_matrix(mat[:3, :3]) trans_vec = mat[:3, 3] elif plane_name == 'tc': # Landmarks lying on the TC plane cr = landmarks[10] cl = landmarks[11] csp = landmarks[12] # Compute transformation csp_cl = cl - csp csp_cr = cr - csp z_vec = np.cross(csp_cl, csp_cr) z_vec = geometry.unit_vector(z_vec) cr_cl_mid = (cr + cl) / 2.0 x_vec = geometry.unit_vector(cr_cl_mid - csp) y_vec = geometry.unit_vector(np.cross(z_vec, x_vec)) # 4x4 transformation matrix mat = np.eye(4) mat[:3, :3] = np.vstack((x_vec, y_vec, z_vec)).transpose() mat[:3, 3] = (cr_cl_mid + csp) / 2.0 # Quaternions and translation vector quat = geometry.quaternion_from_matrix(mat[:3, :3]) trans_vec = mat[:3, 3] else: raise ValueError('Invalid plane name.') return trans_vec, quat, mat def init_mesh(mesh_siz): """Initialise identity plane with a fixed size Args: mesh_siz: size of plane. Odd number only. [2] Returns: mesh: mesh coordinates of identity plane. [4, num_mesh_points] """ mesh_r = (mesh_siz - 1) / 2 x_lin = np.linspace(-mesh_r[0], mesh_r[0], mesh_siz[0]) y_lin = np.linspace(-mesh_r[1], mesh_r[1], mesh_siz[1]) xy_coords = np.meshgrid(y_lin, x_lin) xyz_coords = np.vstack([xy_coords[1].reshape(-1), xy_coords[0].reshape(-1), np.zeros(mesh_siz[0] * mesh_siz[1]), np.ones(mesh_siz[0] * mesh_siz[1])]) return xyz_coords def init_mesh_by_plane(mesh_siz, normal): """Initialise identity plane with a fixed size. Either xy, xz or yz-plane Args: mesh_siz: size of plane. Odd number only. [2] normal: direction of normal vector of mesh. ('x', 'y', 'z') Returns: mesh: mesh coordinates of identity plane. [4, num_mesh_points] """ mesh_r = (mesh_siz - 1) / 2 x_lin = np.linspace(-mesh_r[0], mesh_r[0], mesh_siz[0]) y_lin = np.linspace(-mesh_r[1], mesh_r[1], mesh_siz[1]) xy_coords = np.meshgrid(y_lin, x_lin) if normal=='z': xyz_coords = np.vstack([xy_coords[1].reshape(-1), xy_coords[0].reshape(-1), np.zeros(mesh_siz[0] * mesh_siz[1]), np.ones(mesh_siz[0] * mesh_siz[1])]) elif normal=='y': xyz_coords = np.vstack([xy_coords[1].reshape(-1), np.zeros(mesh_siz[0] * mesh_siz[1]), xy_coords[0].reshape(-1), np.ones(mesh_siz[0] * mesh_siz[1])]) elif normal=='x': xyz_coords = np.vstack([np.zeros(mesh_siz[0] * mesh_siz[1]), xy_coords[1].reshape(-1), xy_coords[0].reshape(-1), np.ones(mesh_siz[0] * mesh_siz[1])]) return xyz_coords def init_mesh_ortho(mesh_siz): """Initialise identity plane with a fixed size. Either xy, xz or yz-plane Args: mesh_siz: size of plane. Odd number only. [2] Returns: xyz_coords: mesh coordinates of xy, xz and yz plane. [3, 4, num_mesh_points] """ xy = init_mesh_by_plane(mesh_siz, 'z') xz = init_mesh_by_plane(mesh_siz, 'y') yz = init_mesh_by_plane(mesh_siz, 'x') xyz_coords = np.stack((xy, xz, yz), axis=0) return xyz_coords def extract_plane_from_mesh(image, mesh, mesh_siz, order): """Extract a 2D plane image from the 3D volume given the mesh coordinates of the plane. Args: image: 3D volume. [x,y,z] mesh: mesh coordinates of a plane. [4, num_mesh_points]. Origin at volume centre mesh_siz: size of mesh [2] order: interpolation order (0-5) Returns: slice: 2D plane image [plane_siz[0], plane_siz[1]] new_coords: mesh coordinates of the plane. Origin at volume corner. numpy array of size [3, plane_siz[0], plane_siz[1] """ # Set image matrix corner as origin img_siz = np.array(image.shape) img_c = (img_siz-1)/2.0 mesh_new = mesh[:3, :] + np.expand_dims(img_c, axis=1) # Reshape coordinates x_coords = mesh_new[0, :].reshape(mesh_siz) y_coords = mesh_new[1, :].reshape(mesh_siz) z_coords = mesh_new[2, :].reshape(mesh_siz) new_coords = np.stack((x_coords, y_coords, z_coords), axis=0) # Extract image plane slice = scipy.ndimage.map_coordinates(image, new_coords, order=order) return slice, new_coords def extract_plane_from_mesh_batch(image, meshes, mesh_siz, order): """Extract a 2D plane image from the 3D volume given the mesh coordinates of the plane. Do it in a batch of planes Args: image: 3D volume. [x,y,z] meshes: mesh coordinates of planes. [mesh_count, 4, num_mesh_points]. Origin at volume centre mesh_siz: size of mesh [2] order: interpolation order (0-5) Returns: slices: 2D plane images [mesh_count, plane_siz[0], plane_siz[1]] meshes_new: mesh coordinates of the plane. Origin at volume corner. numpy array of size [mesh_count, plane_siz[0], plane_siz[1], 3] """ # Set image matrix corner as origin img_siz = np.array(image.shape) img_c = (img_siz-1)/2.0 mesh_count = meshes.shape[0] meshes_new = meshes[:, :3, :] + img_c[np.newaxis, :, np.newaxis] # meshes_new = [mesh_count, 4, num_mesh_pts] meshes_new = np.reshape(np.transpose(meshes_new, (1, 0, 2))[:3], (3, mesh_count, mesh_siz[0], mesh_siz[1])) # [3, mesh_count, plane_siz[0], plane_siz[1]] # Extract image plane slices = scipy.ndimage.map_coordinates(image, meshes_new, order=order) meshes_new = np.transpose(meshes_new, (1, 2, 3, 0)) return slices, meshes_new def extract_plane_from_mesh_ortho_batch(image, meshes, mesh_siz, order): """Extract orthogonal 2D plane images from the 3D volume given the mesh coordinates of the plane. Do it in a batch of planes Args: image: 3D volume. [x,y,z] meshes: mesh coordinates of planes. [mesh_count, mesh_ind, 4, num_mesh_pts]. Origin at volume centre mesh_siz: size of mesh [2] order: interpolation order (0-5) Returns: slices: 2D plane images [mesh_count, mesh_ind, plane_siz[0], plane_siz[1]] meshes_new: mesh coordinates of the plane. Origin at volume corner. numpy array of size [mesh_count, mesh_ind, plane_siz[0], plane_siz[1], 3] """ # Set image matrix corner as origin input_plane = meshes.shape[1] img_siz = np.array(image.shape) img_c = (img_siz-1)/2.0 mesh_count = meshes.shape[0] meshes_new = meshes[:, :, :3, :] + img_c[np.newaxis, :, np.newaxis] # meshes_new = [mesh_count, mesh_ind, 4, num_mesh_pts] meshes_new = np.reshape(np.transpose(meshes_new, (2, 0, 1, 3))[:3], (3, mesh_count, input_plane, mesh_siz[0], mesh_siz[1])) # [3, mesh_count, mesh_ind, plane_siz[0], plane_siz[1]] # Extract image plane slices = scipy.ndimage.map_coordinates(image, meshes_new, order=order) meshes_new = np.transpose(meshes_new, (1, 2, 3, 4, 0)) return slices, meshes_new def extract_plane_from_pose(image, t, q, plane_siz, order): """Extract a 2D plane image from the 3D volume given the pose wrt the identity plane. Args: image: 3D volume. [x,y,z] t: translation of the pose [3] q: rotation of the pose in quaternions [4] plane_siz: size of plane [2] order: interpolation order (0-5) Returns: slice: 2D plane image [plane_siz[0], plane_siz[1]] mesh: mesh coordinates of the plane. Origin at volume corner. numpy array of size [3, plane_siz[0], plane_siz[1]] """ # Initialise identity plane xyz_coords = init_mesh(plane_siz) # Rotate and translate plane mat = geometry.quaternion_matrix(q) mat[:3, 3] = t xyz_coords = np.dot(mat, xyz_coords) # Extract image plane slice, xyz_coords_new = extract_plane_from_mesh(image, xyz_coords, plane_siz, order) return slice, xyz_coords_new
[ "numpy.stack", "numpy.meshgrid", "numpy.eye", "utils.geometry.quaternion_from_matrix", "utils.geometry.quaternion_matrix", "numpy.transpose", "numpy.expand_dims", "numpy.cross", "numpy.zeros", "numpy.ones", "numpy.linalg.svd", "numpy.array", "utils.geometry.unit_vector", "numpy.linspace", ...
[((715, 731), 'numpy.linalg.svd', 'np.linalg.svd', (['A'], {}), '(A)\n', (728, 731), True, 'import numpy as np\n'), ((1546, 1562), 'numpy.linalg.svd', 'np.linalg.svd', (['A'], {}), '(A)\n', (1559, 1562), True, 'import numpy as np\n'), ((4055, 4102), 'numpy.linspace', 'np.linspace', (['(-mesh_r[0])', 'mesh_r[0]', 'mesh_siz[0]'], {}), '(-mesh_r[0], mesh_r[0], mesh_siz[0])\n', (4066, 4102), True, 'import numpy as np\n'), ((4115, 4162), 'numpy.linspace', 'np.linspace', (['(-mesh_r[1])', 'mesh_r[1]', 'mesh_siz[1]'], {}), '(-mesh_r[1], mesh_r[1], mesh_siz[1])\n', (4126, 4162), True, 'import numpy as np\n'), ((4179, 4204), 'numpy.meshgrid', 'np.meshgrid', (['y_lin', 'x_lin'], {}), '(y_lin, x_lin)\n', (4190, 4204), True, 'import numpy as np\n'), ((4875, 4922), 'numpy.linspace', 'np.linspace', (['(-mesh_r[0])', 'mesh_r[0]', 'mesh_siz[0]'], {}), '(-mesh_r[0], mesh_r[0], mesh_siz[0])\n', (4886, 4922), True, 'import numpy as np\n'), ((4935, 4982), 'numpy.linspace', 'np.linspace', (['(-mesh_r[1])', 'mesh_r[1]', 'mesh_siz[1]'], {}), '(-mesh_r[1], mesh_r[1], mesh_siz[1])\n', (4946, 4982), True, 'import numpy as np\n'), ((4999, 5024), 'numpy.meshgrid', 'np.meshgrid', (['y_lin', 'x_lin'], {}), '(y_lin, x_lin)\n', (5010, 5024), True, 'import numpy as np\n'), ((6316, 6346), 'numpy.stack', 'np.stack', (['(xy, xz, yz)'], {'axis': '(0)'}), '((xy, xz, yz), axis=0)\n', (6324, 6346), True, 'import numpy as np\n'), ((7012, 7033), 'numpy.array', 'np.array', (['image.shape'], {}), '(image.shape)\n', (7020, 7033), True, 'import numpy as np\n'), ((7309, 7357), 'numpy.stack', 'np.stack', (['(x_coords, y_coords, z_coords)'], {'axis': '(0)'}), '((x_coords, y_coords, z_coords), axis=0)\n', (7317, 7357), True, 'import numpy as np\n'), ((8206, 8227), 'numpy.array', 'np.array', (['image.shape'], {}), '(image.shape)\n', (8214, 8227), True, 'import numpy as np\n'), ((8688, 8726), 'numpy.transpose', 'np.transpose', (['meshes_new', '(1, 2, 3, 0)'], {}), '(meshes_new, (1, 2, 3, 0))\n', (8700, 8726), True, 'import numpy as np\n'), ((9552, 9573), 'numpy.array', 'np.array', (['image.shape'], {}), '(image.shape)\n', (9560, 9573), True, 'import numpy as np\n'), ((10073, 10114), 'numpy.transpose', 'np.transpose', (['meshes_new', '(1, 2, 3, 4, 0)'], {}), '(meshes_new, (1, 2, 3, 4, 0))\n', (10085, 10114), True, 'import numpy as np\n'), ((10847, 10876), 'utils.geometry.quaternion_matrix', 'geometry.quaternion_matrix', (['q'], {}), '(q)\n', (10873, 10876), False, 'from utils import geometry\n'), ((10913, 10936), 'numpy.dot', 'np.dot', (['mat', 'xyz_coords'], {}), '(mat, xyz_coords)\n', (10919, 10936), True, 'import numpy as np\n'), ((1182, 1194), 'numpy.dot', 'np.dot', (['n', 'n'], {}), '(n, n)\n', (1188, 1194), True, 'import numpy as np\n'), ((2186, 2231), 'numpy.vstack', 'np.vstack', (['(landmarks[1:8], landmarks[12:14])'], {}), '((landmarks[1:8], landmarks[12:14]))\n', (2195, 2231), True, 'import numpy as np\n'), ((2626, 2635), 'numpy.eye', 'np.eye', (['(4)'], {}), '(4)\n', (2632, 2635), True, 'import numpy as np\n'), ((2808, 2852), 'utils.geometry.quaternion_from_matrix', 'geometry.quaternion_from_matrix', (['mat[:3, :3]'], {}), '(mat[:3, :3])\n', (2839, 2852), False, 'from utils import geometry\n'), ((7091, 7120), 'numpy.expand_dims', 'np.expand_dims', (['img_c'], {'axis': '(1)'}), '(img_c, axis=1)\n', (7105, 7120), True, 'import numpy as np\n'), ((1149, 1161), 'numpy.dot', 'np.dot', (['c', 'n'], {}), '(c, n)\n', (1155, 1161), True, 'import numpy as np\n'), ((1164, 1178), 'numpy.dot', 'np.dot', (['pts', 'n'], {}), '(pts, n)\n', (1170, 1178), True, 'import numpy as np\n'), ((1225, 1250), 'numpy.expand_dims', 'np.expand_dims', (['t'], {'axis': '(1)'}), '(t, axis=1)\n', (1239, 1250), True, 'import numpy as np\n'), ((1252, 1277), 'numpy.expand_dims', 'np.expand_dims', (['n'], {'axis': '(0)'}), '(n, axis=0)\n', (1266, 1277), True, 'import numpy as np\n'), ((2551, 2573), 'numpy.cross', 'np.cross', (['z_vec', 'x_vec'], {}), '(z_vec, x_vec)\n', (2559, 2573), True, 'import numpy as np\n'), ((3140, 3164), 'numpy.cross', 'np.cross', (['csp_cl', 'csp_cr'], {}), '(csp_cl, csp_cr)\n', (3148, 3164), True, 'import numpy as np\n'), ((3181, 3208), 'utils.geometry.unit_vector', 'geometry.unit_vector', (['z_vec'], {}), '(z_vec)\n', (3201, 3208), False, 'from utils import geometry\n'), ((3261, 3298), 'utils.geometry.unit_vector', 'geometry.unit_vector', (['(cr_cl_mid - csp)'], {}), '(cr_cl_mid - csp)\n', (3281, 3298), False, 'from utils import geometry\n'), ((3411, 3420), 'numpy.eye', 'np.eye', (['(4)'], {}), '(4)\n', (3417, 3420), True, 'import numpy as np\n'), ((3593, 3637), 'utils.geometry.quaternion_from_matrix', 'geometry.quaternion_from_matrix', (['mat[:3, :3]'], {}), '(mat[:3, :3])\n', (3624, 3637), False, 'from utils import geometry\n'), ((4341, 4376), 'numpy.zeros', 'np.zeros', (['(mesh_siz[0] * mesh_siz[1])'], {}), '(mesh_siz[0] * mesh_siz[1])\n', (4349, 4376), True, 'import numpy as np\n'), ((4406, 4440), 'numpy.ones', 'np.ones', (['(mesh_siz[0] * mesh_siz[1])'], {}), '(mesh_siz[0] * mesh_siz[1])\n', (4413, 4440), True, 'import numpy as np\n'), ((8434, 8469), 'numpy.transpose', 'np.transpose', (['meshes_new', '(1, 0, 2)'], {}), '(meshes_new, (1, 0, 2))\n', (8446, 8469), True, 'import numpy as np\n'), ((9793, 9831), 'numpy.transpose', 'np.transpose', (['meshes_new', '(2, 0, 1, 3)'], {}), '(meshes_new, (2, 0, 1, 3))\n', (9805, 9831), True, 'import numpy as np\n'), ((2658, 2690), 'numpy.vstack', 'np.vstack', (['(x_vec, y_vec, z_vec)'], {}), '((x_vec, y_vec, z_vec))\n', (2667, 2690), True, 'import numpy as np\n'), ((3336, 3358), 'numpy.cross', 'np.cross', (['z_vec', 'x_vec'], {}), '(z_vec, x_vec)\n', (3344, 3358), True, 'import numpy as np\n'), ((5193, 5228), 'numpy.zeros', 'np.zeros', (['(mesh_siz[0] * mesh_siz[1])'], {}), '(mesh_siz[0] * mesh_siz[1])\n', (5201, 5228), True, 'import numpy as np\n'), ((5262, 5296), 'numpy.ones', 'np.ones', (['(mesh_siz[0] * mesh_siz[1])'], {}), '(mesh_siz[0] * mesh_siz[1])\n', (5269, 5296), True, 'import numpy as np\n'), ((3443, 3475), 'numpy.vstack', 'np.vstack', (['(x_vec, y_vec, z_vec)'], {}), '((x_vec, y_vec, z_vec))\n', (3452, 3475), True, 'import numpy as np\n'), ((5411, 5446), 'numpy.zeros', 'np.zeros', (['(mesh_siz[0] * mesh_siz[1])'], {}), '(mesh_siz[0] * mesh_siz[1])\n', (5419, 5446), True, 'import numpy as np\n'), ((5538, 5572), 'numpy.ones', 'np.ones', (['(mesh_siz[0] * mesh_siz[1])'], {}), '(mesh_siz[0] * mesh_siz[1])\n', (5545, 5572), True, 'import numpy as np\n'), ((5629, 5664), 'numpy.zeros', 'np.zeros', (['(mesh_siz[0] * mesh_siz[1])'], {}), '(mesh_siz[0] * mesh_siz[1])\n', (5637, 5664), True, 'import numpy as np\n'), ((5814, 5848), 'numpy.ones', 'np.ones', (['(mesh_siz[0] * mesh_siz[1])'], {}), '(mesh_siz[0] * mesh_siz[1])\n', (5821, 5848), True, 'import numpy as np\n')]
from models.volume_rendering import volume_render import torch import numpy as np from tqdm import tqdm def get_rays_opencv_np(intrinsics: np.ndarray, c2w: np.ndarray, H: int, W: int): ''' ray batch sampling < opencv / colmap convention, standard pinhole camera > the camera is facing [+z] direction, x right, y downwards z ↗ / / o------> x | | | ↓ y :param H: image height :param W: image width :param intrinsics: [3, 3] or [4,4] intrinsic matrix :param c2w: [...,4,4] or [...,3,4] camera to world extrinsic matrix :return: ''' prefix = c2w.shape[:-2] # [...] # [H, W] u, v = np.meshgrid(np.arange(W), np.arange(H)) # [H*W] u = u.reshape(-1).astype(dtype=np.float32) + 0.5 # add half pixel v = v.reshape(-1).astype(dtype=np.float32) + 0.5 # [3, H*W] pixels = np.stack((u, v, np.ones_like(u)), axis=0) # [3, H*W] rays_d = np.matmul(np.linalg.inv(intrinsics[:3, :3]), pixels) # [..., 3, H*W] = [..., 3, 3] @ [1,1,..., 3, H*W], with broadcasting rays_d = np.matmul(c2w[..., :3, :3], rays_d.reshape([*len(prefix)*[1], 3, H*W])) # [..., H*W, 3] rays_d = np.moveaxis(rays_d, -1, -2) # [..., 1, 3] -> [..., H*W, 3] rays_o = np.tile(c2w[..., None, :3, 3], [*len(prefix)*[1], H*W, 1]) return rays_o, rays_d def render_full(intr: np.ndarray, c2w: np.ndarray, H, W, near, far, render_kwargs, scene_model, device="cuda", batch_size=1, imgscale=True): rgbs = [] depths = [] scene_model.to(device) if len(c2w.shape) == 2: c2w = c2w[None, ...] render_kwargs['batched'] = True def to_img(tensor): tensor = tensor.reshape(tensor.shape[0], H, W, -1).data.cpu().numpy() if imgscale: return (255*np.clip(tensor, 0, 1)).astype(np.uint8) else: return tensor def render_chunk(c2w): rays_o, rays_d = get_rays_opencv_np(intr, c2w, H, W) rays_o = torch.from_numpy(rays_o).float().to(device) rays_d = torch.from_numpy(rays_d).float().to(device) with torch.no_grad(): rgb, depth, _ = volume_render( rays_o=rays_o, rays_d=rays_d, detailed_output=False, # to return acc map and disp map show_progress=True, **render_kwargs) if imgscale: depth = (depth-near)/(far-near) return to_img(rgb), to_img(depth) for i in tqdm(range(0, c2w.shape[0], batch_size), desc="=> Rendering..."): rgb_i, depth_i = render_chunk(c2w[i:i+batch_size]) rgbs += [*rgb_i] depths += [*depth_i] return rgbs, depths
[ "numpy.moveaxis", "numpy.ones_like", "numpy.clip", "numpy.linalg.inv", "numpy.arange", "models.volume_rendering.volume_render", "torch.no_grad", "torch.from_numpy" ]
[((1348, 1375), 'numpy.moveaxis', 'np.moveaxis', (['rays_d', '(-1)', '(-2)'], {}), '(rays_d, -1, -2)\n', (1359, 1375), True, 'import numpy as np\n'), ((826, 838), 'numpy.arange', 'np.arange', (['W'], {}), '(W)\n', (835, 838), True, 'import numpy as np\n'), ((840, 852), 'numpy.arange', 'np.arange', (['H'], {}), '(H)\n', (849, 852), True, 'import numpy as np\n'), ((1108, 1141), 'numpy.linalg.inv', 'np.linalg.inv', (['intrinsics[:3, :3]'], {}), '(intrinsics[:3, :3])\n', (1121, 1141), True, 'import numpy as np\n'), ((1041, 1056), 'numpy.ones_like', 'np.ones_like', (['u'], {}), '(u)\n', (1053, 1056), True, 'import numpy as np\n'), ((2258, 2273), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (2271, 2273), False, 'import torch\n'), ((2303, 2410), 'models.volume_rendering.volume_render', 'volume_render', ([], {'rays_o': 'rays_o', 'rays_d': 'rays_d', 'detailed_output': '(False)', 'show_progress': '(True)'}), '(rays_o=rays_o, rays_d=rays_d, detailed_output=False,\n show_progress=True, **render_kwargs)\n', (2316, 2410), False, 'from models.volume_rendering import volume_render\n'), ((1953, 1974), 'numpy.clip', 'np.clip', (['tensor', '(0)', '(1)'], {}), '(tensor, 0, 1)\n', (1960, 1974), True, 'import numpy as np\n'), ((2139, 2163), 'torch.from_numpy', 'torch.from_numpy', (['rays_o'], {}), '(rays_o)\n', (2155, 2163), False, 'import torch\n'), ((2200, 2224), 'torch.from_numpy', 'torch.from_numpy', (['rays_d'], {}), '(rays_d)\n', (2216, 2224), False, 'import torch\n')]
import os import numpy as np import cv2 import torch from torch.utils.data.dataset import Dataset from torchvision import transforms from PIL import Image, ImageFilter class Gaze360(Dataset): def __init__(self, path, root, transform, angle, binwidth, train=True): self.transform = transform self.root = root self.orig_list_len = 0 self.angle = angle if train==False: angle=90 self.binwidth=binwidth self.lines = [] if isinstance(path, list): for i in path: with open(i) as f: print("here") line = f.readlines() line.pop(0) self.lines.extend(line) else: with open(path) as f: lines = f.readlines() lines.pop(0) self.orig_list_len = len(lines) for line in lines: gaze2d = line.strip().split(" ")[5] label = np.array(gaze2d.split(",")).astype("float") if abs((label[0]*180/np.pi)) <= angle and abs((label[1]*180/np.pi)) <= angle: self.lines.append(line) print("{} items removed from dataset that have an angle > {}".format(self.orig_list_len-len(self.lines), angle)) def __len__(self): return len(self.lines) def __getitem__(self, idx): line = self.lines[idx] line = line.strip().split(" ") face = line[0] lefteye = line[1] righteye = line[2] name = line[3] gaze2d = line[5] label = np.array(gaze2d.split(",")).astype("float") label = torch.from_numpy(label).type(torch.FloatTensor) pitch = label[0]* 180 / np.pi yaw = label[1]* 180 / np.pi img = Image.open(os.path.join(self.root, face)) # fimg = cv2.imread(os.path.join(self.root, face)) # fimg = cv2.resize(fimg, (448, 448))/255.0 # fimg = fimg.transpose(2, 0, 1) # img=torch.from_numpy(fimg).type(torch.FloatTensor) if self.transform: img = self.transform(img) # Bin values bins = np.array(range(-1*self.angle, self.angle, self.binwidth)) binned_pose = np.digitize([pitch, yaw], bins) - 1 labels = binned_pose cont_labels = torch.FloatTensor([pitch, yaw]) return img, labels, cont_labels, name class Mpiigaze(Dataset): def __init__(self, pathorg, root, transform, train, angle,fold=0): self.transform = transform self.root = root self.orig_list_len = 0 self.lines = [] path=pathorg.copy() if train==True: path.pop(fold) else: path=path[fold] if isinstance(path, list): for i in path: with open(i) as f: lines = f.readlines() lines.pop(0) self.orig_list_len += len(lines) for line in lines: gaze2d = line.strip().split(" ")[7] label = np.array(gaze2d.split(",")).astype("float") if abs((label[0]*180/np.pi)) <= angle and abs((label[1]*180/np.pi)) <= angle: self.lines.append(line) else: with open(path) as f: lines = f.readlines() lines.pop(0) self.orig_list_len += len(lines) for line in lines: gaze2d = line.strip().split(" ")[7] label = np.array(gaze2d.split(",")).astype("float") if abs((label[0]*180/np.pi)) <= 42 and abs((label[1]*180/np.pi)) <= 42: self.lines.append(line) print("{} items removed from dataset that have an angle > {}".format(self.orig_list_len-len(self.lines),angle)) def __len__(self): return len(self.lines) def __getitem__(self, idx): line = self.lines[idx] line = line.strip().split(" ") name = line[3] gaze2d = line[7] head2d = line[8] lefteye = line[1] righteye = line[2] face = line[0] label = np.array(gaze2d.split(",")).astype("float") label = torch.from_numpy(label).type(torch.FloatTensor) pitch = label[0]* 180 / np.pi yaw = label[1]* 180 / np.pi img = Image.open(os.path.join(self.root, face)) # fimg = cv2.imread(os.path.join(self.root, face)) # fimg = cv2.resize(fimg, (448, 448))/255.0 # fimg = fimg.transpose(2, 0, 1) # img=torch.from_numpy(fimg).type(torch.FloatTensor) if self.transform: img = self.transform(img) # Bin values bins = np.array(range(-42, 42,3)) binned_pose = np.digitize([pitch, yaw], bins) - 1 labels = binned_pose cont_labels = torch.FloatTensor([pitch, yaw]) return img, labels, cont_labels, name
[ "numpy.digitize", "torch.FloatTensor", "os.path.join", "torch.from_numpy" ]
[((2491, 2522), 'torch.FloatTensor', 'torch.FloatTensor', (['[pitch, yaw]'], {}), '([pitch, yaw])\n', (2508, 2522), False, 'import torch\n'), ((4910, 4941), 'torch.FloatTensor', 'torch.FloatTensor', (['[pitch, yaw]'], {}), '([pitch, yaw])\n', (4927, 4941), False, 'import torch\n'), ((1944, 1973), 'os.path.join', 'os.path.join', (['self.root', 'face'], {}), '(self.root, face)\n', (1956, 1973), False, 'import os\n'), ((2400, 2431), 'numpy.digitize', 'np.digitize', (['[pitch, yaw]', 'bins'], {}), '([pitch, yaw], bins)\n', (2411, 2431), True, 'import numpy as np\n'), ((4438, 4467), 'os.path.join', 'os.path.join', (['self.root', 'face'], {}), '(self.root, face)\n', (4450, 4467), False, 'import os\n'), ((4827, 4858), 'numpy.digitize', 'np.digitize', (['[pitch, yaw]', 'bins'], {}), '([pitch, yaw], bins)\n', (4838, 4858), True, 'import numpy as np\n'), ((1790, 1813), 'torch.from_numpy', 'torch.from_numpy', (['label'], {}), '(label)\n', (1806, 1813), False, 'import torch\n'), ((4294, 4317), 'torch.from_numpy', 'torch.from_numpy', (['label'], {}), '(label)\n', (4310, 4317), False, 'import torch\n')]
# MIT License # # Copyright (c) 2019 <NAME>, <NAME>, <NAME>, <NAME>, <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import numpy as np from dpemu.nodes import Array from dpemu.filters.time_series import Gap, SensorDrift def test_seed_determines_result_for_gap_filter(): a = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]) x_node = Array() x_node.addfilter(Gap("prob_break", "prob_recover", "missing_value")) params = {"prob_break": 0.1, "prob_recover": 0.1, "missing_value": 1337} out1 = x_node.generate_error(a, params, np.random.RandomState(seed=42)) out2 = x_node.generate_error(a, params, np.random.RandomState(seed=42)) assert np.array_equal(out1, out2) def test_sensor_drift(): drift = SensorDrift("magnitude") params = {"magnitude": 2} drift.set_params(params) y = np.full((100), 1) drift.apply(y, np.random.RandomState(), named_dims={}) increases = np.arange(1, 101) assert len(y) == len(increases) for i, val in enumerate(y): assert val == increases[i]*2 + 1 def test_one_gap(): gap = Gap("prob_break", "prob_recover", "missing") y = np.arange(10000.0) params = {"prob_break": 0.0, "prob_recover": 1, "missing": np.nan} gap.set_params(params) gap.apply(y, np.random.RandomState(), named_dims={}) for _, val in enumerate(y): assert not np.isnan(val) def test_two_gap(): gap = Gap("prob_break", "prob_recover", "missing") params = {"prob_break": 1.0, "prob_recover": 0.0, "missing": np.nan} y = np.arange(10000.0) gap.set_params(params) gap.apply(y, np.random.RandomState(), named_dims={}) for _, val in enumerate(y): assert np.isnan(val)
[ "numpy.full", "dpemu.nodes.Array", "dpemu.filters.time_series.SensorDrift", "numpy.random.RandomState", "numpy.isnan", "numpy.array", "numpy.arange", "dpemu.filters.time_series.Gap", "numpy.array_equal" ]
[((1298, 1366), 'numpy.array', 'np.array', (['[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]'], {}), '([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16])\n', (1306, 1366), True, 'import numpy as np\n'), ((1380, 1387), 'dpemu.nodes.Array', 'Array', ([], {}), '()\n', (1385, 1387), False, 'from dpemu.nodes import Array\n'), ((1701, 1727), 'numpy.array_equal', 'np.array_equal', (['out1', 'out2'], {}), '(out1, out2)\n', (1715, 1727), True, 'import numpy as np\n'), ((1767, 1791), 'dpemu.filters.time_series.SensorDrift', 'SensorDrift', (['"""magnitude"""'], {}), "('magnitude')\n", (1778, 1791), False, 'from dpemu.filters.time_series import Gap, SensorDrift\n'), ((1859, 1874), 'numpy.full', 'np.full', (['(100)', '(1)'], {}), '(100, 1)\n', (1866, 1874), True, 'import numpy as np\n'), ((1953, 1970), 'numpy.arange', 'np.arange', (['(1)', '(101)'], {}), '(1, 101)\n', (1962, 1970), True, 'import numpy as np\n'), ((2113, 2157), 'dpemu.filters.time_series.Gap', 'Gap', (['"""prob_break"""', '"""prob_recover"""', '"""missing"""'], {}), "('prob_break', 'prob_recover', 'missing')\n", (2116, 2157), False, 'from dpemu.filters.time_series import Gap, SensorDrift\n'), ((2166, 2184), 'numpy.arange', 'np.arange', (['(10000.0)'], {}), '(10000.0)\n', (2175, 2184), True, 'import numpy as np\n'), ((2438, 2482), 'dpemu.filters.time_series.Gap', 'Gap', (['"""prob_break"""', '"""prob_recover"""', '"""missing"""'], {}), "('prob_break', 'prob_recover', 'missing')\n", (2441, 2482), False, 'from dpemu.filters.time_series import Gap, SensorDrift\n'), ((2564, 2582), 'numpy.arange', 'np.arange', (['(10000.0)'], {}), '(10000.0)\n', (2573, 2582), True, 'import numpy as np\n'), ((1409, 1459), 'dpemu.filters.time_series.Gap', 'Gap', (['"""prob_break"""', '"""prob_recover"""', '"""missing_value"""'], {}), "('prob_break', 'prob_recover', 'missing_value')\n", (1412, 1459), False, 'from dpemu.filters.time_series import Gap, SensorDrift\n'), ((1582, 1612), 'numpy.random.RandomState', 'np.random.RandomState', ([], {'seed': '(42)'}), '(seed=42)\n', (1603, 1612), True, 'import numpy as np\n'), ((1658, 1688), 'numpy.random.RandomState', 'np.random.RandomState', ([], {'seed': '(42)'}), '(seed=42)\n', (1679, 1688), True, 'import numpy as np\n'), ((1896, 1919), 'numpy.random.RandomState', 'np.random.RandomState', ([], {}), '()\n', (1917, 1919), True, 'import numpy as np\n'), ((2300, 2323), 'numpy.random.RandomState', 'np.random.RandomState', ([], {}), '()\n', (2321, 2323), True, 'import numpy as np\n'), ((2627, 2650), 'numpy.random.RandomState', 'np.random.RandomState', ([], {}), '()\n', (2648, 2650), True, 'import numpy as np\n'), ((2715, 2728), 'numpy.isnan', 'np.isnan', (['val'], {}), '(val)\n', (2723, 2728), True, 'import numpy as np\n'), ((2392, 2405), 'numpy.isnan', 'np.isnan', (['val'], {}), '(val)\n', (2400, 2405), True, 'import numpy as np\n')]
import python2latex as p2l import sys, os sys.path.append(os.getcwd()) from datetime import datetime import csv import numpy as np from experiments.datasets.datasets import dataset_list from partitioning_machines import func_to_cmd class MeanWithStd(float, p2l.TexObject): def __new__(cls, array): mean = array.mean() instance = super().__new__(cls, mean) instance.mean = mean instance.std = array.std() return instance def __format__(self, format_spec): if np.isnan(self.mean): return 'N/A' return f'${format(self.mean, format_spec)} \pm {format(self.std, format_spec)}$' def build_table(dataset, exp_name): dataset = dataset.load() dataset_name = dataset.name model_names = [ 'original', 'cart', 'm-cart', 'ours', ] if isinstance(exp_name, str): exp_names = [exp_name]*4 else: exp_names = exp_name table = p2l.Table((7, 5), float_format='.3f') table.body.insert(0, '\\small') table[0,1:] = ['Original', 'CART', 'M-CART', 'Ours'] table[0,1:].add_rule() table[1:,0] = ['Train acc.', 'Test acc.', 'Leaves', 'Height', 'Time $[s]$', 'Bound'] for i, (model, exp) in enumerate(zip(model_names, exp_names)): tr_acc = [] ts_acc = [] leaves = [] height = [] bound = [] time = [] path = './experiments/results/' + dataset_name + '/' + exp + '/' + model + '.csv' try: with open(path, 'r', newline='') as file: reader = csv.reader(file) header = next(reader) for row in reader: tr_acc.append(row[2]) ts_acc.append(row[3]) leaves.append(row[4]) height.append(row[5]) try: time.append(row[7]) except: time.append(np.nan) if i == 3: bound.append(row[6]) else: bound.append(np.nan) tr_acc = np.array(tr_acc, dtype=float) ts_acc = np.array(ts_acc, dtype=float) leaves = np.array(leaves, dtype=float) height = np.array(height, dtype=float) time = np.array(time, dtype=float) bound = np.array(bound, dtype=float) table[0+1, i+1] = MeanWithStd(tr_acc) table[1+1, i+1] = MeanWithStd(ts_acc) table[2+1, i+1] = MeanWithStd(leaves) table[3+1, i+1] = MeanWithStd(height) table[4+1, i+1] = MeanWithStd(time) table[5+1, i+1] = MeanWithStd(bound) except FileNotFoundError: print(f"Could not find file '{path}'") dataset_name = dataset_name.replace('_', ' ').title() dataset_citation = '' if dataset.bibtex_label is None else f'\\citep{{{dataset.bibtex_label}}}' table.caption = f'{dataset_name} Dataset {dataset_citation} ({dataset.n_examples} examples, {dataset.n_features} features, {dataset.n_classes} classes)' table[2,1:].highlight_best(highlight=lambda content: '$\\mathbf{' + content[1:-1] + '}$', atol=.0025, rtol=0) table[3:,1:].change_format('.1f') return table @func_to_cmd def process_results(exp_name='first_exp'): """ Produces Tables 2 to 20 from the paper (Appendix E). Will try to call pdflatex if installed. Args: exp_name (str): Name of the experiment used when the experiments were run. If no experiments by that name are found, entries are set to 'nan'. Prints in the console some compiled statistics used in the paper and the tex string used to produce the tables, and will compile it if possible. """ doc = p2l.Document(exp_name + '_results_by_dataset', '.') doc.add_package('natbib') tables = [build_table(dataset, exp_name) for dataset in dataset_list] # Other stats print('Some compiled statistics used in the paper:\n') times_leaves_cart = [table[3,4].data[0][0] / table[3,2].data[0][0] for table in tables] print('CART tree has', sum(times_leaves_cart)/len(times_leaves_cart), 'times less leaves than our model.') acc_gain_vs_cart = [table[2,4].data[0][0] - table[2,2].data[0][0] for table in tables] print('Our model has a mean accuracy gain of', sum(acc_gain_vs_cart)/len(acc_gain_vs_cart), 'over the CART algorithm.') time_ours_vs_cart = [table[5,2].data[0][0] / table[5,4].data[0][0] for table in tables] print('It took in average', sum(time_ours_vs_cart)/len(time_ours_vs_cart), 'less time to prune the tree with our model than with the CART algorithm.') times_leaves_mcart = [table[3,3].data[0][0] / table[3,2].data[0][0] for table in tables] print('CART tree has', sum(times_leaves_mcart)/len(times_leaves_mcart), 'times less leaves than the modified CART algorithm.') acc_gain_vs_mcart = [table[2,3].data[0][0] - table[2,2].data[0][0] for table in tables] print('The modified CART algorithm has a mean accuracy gain of', sum(acc_gain_vs_mcart)/len(acc_gain_vs_mcart), 'over the CART algorithm.') print('\n') doc.body.extend(tables) print(doc.build(save_to_disk=False)) try: doc.build() except: pass if __name__ == "__main__": process_results()
[ "csv.reader", "os.getcwd", "python2latex.Document", "python2latex.Table", "numpy.isnan", "numpy.array" ]
[((58, 69), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (67, 69), False, 'import sys, os\n'), ((977, 1014), 'python2latex.Table', 'p2l.Table', (['(7, 5)'], {'float_format': '""".3f"""'}), "((7, 5), float_format='.3f')\n", (986, 1014), True, 'import python2latex as p2l\n'), ((3813, 3864), 'python2latex.Document', 'p2l.Document', (["(exp_name + '_results_by_dataset')", '"""."""'], {}), "(exp_name + '_results_by_dataset', '.')\n", (3825, 3864), True, 'import python2latex as p2l\n'), ((519, 538), 'numpy.isnan', 'np.isnan', (['self.mean'], {}), '(self.mean)\n', (527, 538), True, 'import numpy as np\n'), ((2159, 2188), 'numpy.array', 'np.array', (['tr_acc'], {'dtype': 'float'}), '(tr_acc, dtype=float)\n', (2167, 2188), True, 'import numpy as np\n'), ((2210, 2239), 'numpy.array', 'np.array', (['ts_acc'], {'dtype': 'float'}), '(ts_acc, dtype=float)\n', (2218, 2239), True, 'import numpy as np\n'), ((2261, 2290), 'numpy.array', 'np.array', (['leaves'], {'dtype': 'float'}), '(leaves, dtype=float)\n', (2269, 2290), True, 'import numpy as np\n'), ((2312, 2341), 'numpy.array', 'np.array', (['height'], {'dtype': 'float'}), '(height, dtype=float)\n', (2320, 2341), True, 'import numpy as np\n'), ((2361, 2388), 'numpy.array', 'np.array', (['time'], {'dtype': 'float'}), '(time, dtype=float)\n', (2369, 2388), True, 'import numpy as np\n'), ((2409, 2437), 'numpy.array', 'np.array', (['bound'], {'dtype': 'float'}), '(bound, dtype=float)\n', (2417, 2437), True, 'import numpy as np\n'), ((1591, 1607), 'csv.reader', 'csv.reader', (['file'], {}), '(file)\n', (1601, 1607), False, 'import csv\n')]
# Clean and Plot Linked URLS # Import Modules import os import pandas as pd import numpy as np import csv from tqdm import tqdm import matplotlib.pyplot as plt from matplotlib.ticker import PercentFormatter linked_url = pd.read_csv('Outputs/CS_FULL/LinkedURLs_CS.csv') linked_url = linked_url.sort_values(by=['Times_Linked'],ascending=False) linked_url.reset_index(drop=True, inplace=True) top20 = linked_url[:19] url = top20['URL'] num_links = top20['Times_Linked'] max_links = top20['Times_Linked'][0] spacing=1000 ytickvals = np.arange(0,max_links+spacing,spacing) fig, ax = plt.subplots() ax.text(0.9, 0.95, 'A', transform=ax.transAxes,fontsize=18, fontweight='bold', va='top') plt.bar(url,num_links,edgecolor='black',color='papayawhip') plt.xticks(rotation='vertical',fontsize=12) plt.ylabel('Frequency',fontsize=18) plt.yticks(ytickvals) plt.ylim(0,(max_links+(spacing/2))) fig.tight_layout() # Now for /r/climate linked_url2 = pd.read_csv('Outputs/CLIM_FULL/LinkedURLs_CLIM.csv') linked_url2 = linked_url2.sort_values(by=['Times_Linked'],ascending=False) linked_url2.reset_index(drop=True, inplace=True) top20_2 = linked_url2[:19] url2 = top20_2['URL'] num_links2 = top20_2['Times_Linked'] max_links = top20_2['Times_Linked'][0] spacing=1000 ytickvals = np.arange(0,max_links+spacing,spacing) fig , ax2 = plt.subplots() ax2.text(0.9, 0.95, 'B', transform=ax2.transAxes,fontsize=18, fontweight='bold', va='top') plt.bar(url2,num_links2,edgecolor='black',color='#afeeee') plt.xticks(rotation='vertical',fontsize=12) plt.ylabel('Frequency',fontsize=18) plt.yticks(ytickvals) plt.ylim(0,(max_links+(spacing/2))) fig.tight_layout() plt.show()
[ "matplotlib.pyplot.show", "matplotlib.pyplot.ylim", "pandas.read_csv", "matplotlib.pyplot.bar", "matplotlib.pyplot.yticks", "numpy.arange", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xticks", "matplotlib.pyplot.subplots" ]
[((222, 270), 'pandas.read_csv', 'pd.read_csv', (['"""Outputs/CS_FULL/LinkedURLs_CS.csv"""'], {}), "('Outputs/CS_FULL/LinkedURLs_CS.csv')\n", (233, 270), True, 'import pandas as pd\n'), ((535, 577), 'numpy.arange', 'np.arange', (['(0)', '(max_links + spacing)', 'spacing'], {}), '(0, max_links + spacing, spacing)\n', (544, 577), True, 'import numpy as np\n'), ((585, 599), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (597, 599), True, 'import matplotlib.pyplot as plt\n'), ((689, 751), 'matplotlib.pyplot.bar', 'plt.bar', (['url', 'num_links'], {'edgecolor': '"""black"""', 'color': '"""papayawhip"""'}), "(url, num_links, edgecolor='black', color='papayawhip')\n", (696, 751), True, 'import matplotlib.pyplot as plt\n'), ((749, 793), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'rotation': '"""vertical"""', 'fontsize': '(12)'}), "(rotation='vertical', fontsize=12)\n", (759, 793), True, 'import matplotlib.pyplot as plt\n'), ((793, 829), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Frequency"""'], {'fontsize': '(18)'}), "('Frequency', fontsize=18)\n", (803, 829), True, 'import matplotlib.pyplot as plt\n'), ((829, 850), 'matplotlib.pyplot.yticks', 'plt.yticks', (['ytickvals'], {}), '(ytickvals)\n', (839, 850), True, 'import matplotlib.pyplot as plt\n'), ((851, 887), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0)', '(max_links + spacing / 2)'], {}), '(0, max_links + spacing / 2)\n', (859, 887), True, 'import matplotlib.pyplot as plt\n'), ((942, 994), 'pandas.read_csv', 'pd.read_csv', (['"""Outputs/CLIM_FULL/LinkedURLs_CLIM.csv"""'], {}), "('Outputs/CLIM_FULL/LinkedURLs_CLIM.csv')\n", (953, 994), True, 'import pandas as pd\n'), ((1273, 1315), 'numpy.arange', 'np.arange', (['(0)', '(max_links + spacing)', 'spacing'], {}), '(0, max_links + spacing, spacing)\n', (1282, 1315), True, 'import numpy as np\n'), ((1325, 1339), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (1337, 1339), True, 'import matplotlib.pyplot as plt\n'), ((1431, 1492), 'matplotlib.pyplot.bar', 'plt.bar', (['url2', 'num_links2'], {'edgecolor': '"""black"""', 'color': '"""#afeeee"""'}), "(url2, num_links2, edgecolor='black', color='#afeeee')\n", (1438, 1492), True, 'import matplotlib.pyplot as plt\n'), ((1490, 1534), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'rotation': '"""vertical"""', 'fontsize': '(12)'}), "(rotation='vertical', fontsize=12)\n", (1500, 1534), True, 'import matplotlib.pyplot as plt\n'), ((1534, 1570), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Frequency"""'], {'fontsize': '(18)'}), "('Frequency', fontsize=18)\n", (1544, 1570), True, 'import matplotlib.pyplot as plt\n'), ((1570, 1591), 'matplotlib.pyplot.yticks', 'plt.yticks', (['ytickvals'], {}), '(ytickvals)\n', (1580, 1591), True, 'import matplotlib.pyplot as plt\n'), ((1592, 1628), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0)', '(max_links + spacing / 2)'], {}), '(0, max_links + spacing / 2)\n', (1600, 1628), True, 'import matplotlib.pyplot as plt\n'), ((1647, 1657), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1655, 1657), True, 'import matplotlib.pyplot as plt\n')]
from models import MVDNet as MVDNet import argparse import time import csv import numpy as np import torch from torch.autograd import Variable import torch.backends.cudnn as cudnn import torch.optim import torch.nn as nn import torch.nn.functional as F import torch.utils.data import custom_transforms from utils import tensor2array, save_checkpoint, save_path_formatter, adjust_learning_rate from loss_functions import compute_errors_train, compute_errors_test, compute_angles from inverse_warp_ import check_depth from logger import TermLogger, AverageMeter from itertools import chain from tensorboardX import SummaryWriter from data_loader import SequenceFolder import matplotlib.pyplot as plt from scipy.misc import imsave from path import Path import os from inverse_warp import inverse_warp #from sync_batchnorm import convert_model parser = argparse.ArgumentParser(description='Structure from Motion Learner training on KITTI and CityScapes Dataset', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('data', metavar='DIR', help='path to dataset') parser.add_argument('--dataset', dest='dataset', default='dataset', metavar='PATH', help='dataset') parser.add_argument('--dataset-format', default='sequential', metavar='STR', help='dataset format, stacked: stacked frames (from original TensorFlow code) \ sequential: sequential folders (easier to convert to with a non KITTI/Cityscape dataset') parser.add_argument('-j', '--workers', default=4, type=int, metavar='N', help='number of data loading workers') parser.add_argument('--epochs', default=20, type=int, metavar='N', help='number of total epochs to run') parser.add_argument('--epoch-size', default=0, type=int, metavar='N', help='manual epoch size (will match dataset size if not set)') parser.add_argument('-b', '--batch-size', default=16, type=int, metavar='N', help='mini-batch size') parser.add_argument('--lr', '--learning-rate', default=2e-4, type=float, metavar='LR', help='initial learning rate') parser.add_argument('--momentum', default=0.9, type=float, metavar='M', help='momentum for sgd, alpha parameter for adam') parser.add_argument('--beta', default=0.999, type=float, metavar='M', help='beta parameters for adam') parser.add_argument('--weight-decay', '--wd', default=0, type=float, metavar='W', help='weight decay') parser.add_argument('--print-freq', default=10, type=int, metavar='N', help='print frequency') parser.add_argument('-e', '--evaluate', dest='evaluate', action='store_true', help='evaluate model on validation set') parser.add_argument('--p-dps', dest='pretrained_dps', action='store_true', help='finetune on pretrained_dps') parser.add_argument('--pretrained-mvdn', dest='pretrained_mvdn', default=None, metavar='PATH', help='path to pre-trained mvdnet model') parser.add_argument('--seed', default=0, type=int, help='seed for random functions, and network initialization') parser.add_argument('--log-summary', default='progress_log_summary.csv', metavar='PATH', help='csv where to save per-epoch train and valid stats') parser.add_argument('--log-full', default='progress_log_full.csv', metavar='PATH', help='csv where to save per-gradient descent train stats') parser.add_argument('--log-output', action='store_true', help='will log dispnet outputs and warped imgs at validation step') parser.add_argument('--ttype', default='train.txt', type=str, help='Text file indicates input data') parser.add_argument('--ttype2', default='test.txt', type=str, help='Text file indicates input data') parser.add_argument('-f', '--training-output-freq', type=int, help='frequence for outputting dispnet outputs and warped imgs at training for all scales if 0 will not output', metavar='N', default=100) parser.add_argument('--nlabel', type=int ,default=64, help='number of label') parser.add_argument('--mindepth', type=float ,default=0.5, help='minimum depth') parser.add_argument('--exp', default='default', type=str, help='Experiment name') parser.add_argument('-sv', dest='skip_v', action='store_true', help='Skip validation') parser.add_argument('-nw','--n-weight', type=float ,default=1, help='weight of nmap loss') parser.add_argument('-dw','--d-weight', type=float ,default=1, help='weight of depth loss') parser.add_argument('-np', dest='no_pool', action='store_true', help='Use less pool layers in nnet') parser.add_argument('--index', type=int, default=0, help='') parser.add_argument('--output-dir', default='test_result', type=str, help='Output directory for saving predictions in a big 3D numpy file') parser.add_argument('--output-print', action='store_true', help='print output depth') parser.add_argument('--scale', type=float ,default=1, help='scale sceneflow') parser.add_argument('--crop-h', type=int ,default=240, help='crop h sceneflow') parser.add_argument('--crop-w', type=int ,default=320, help='crop w sceneflow') n_iter = 0 def main(): global n_iter args = parser.parse_args() output_dir = Path(args.output_dir) save_path = save_path_formatter(args, parser) args.save_path = 'checkpoints'/(args.exp+'_'+save_path) print('=> will save everything to {}'.format(args.save_path)) args.save_path.makedirs_p() torch.manual_seed(args.seed) training_writer = SummaryWriter(args.save_path) output_writers = [] for i in range(3): output_writers.append(SummaryWriter(args.save_path/'valid'/str(i))) # Data loading code normalize = custom_transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) if args.dataset == 'sceneflow': train_transform = custom_transforms.Compose([ custom_transforms.RandomCrop(scale = args.scale, h = args.crop_h, w = args.crop_w), custom_transforms.ArrayToTensor(), normalize ]) else: train_transform = custom_transforms.Compose([ custom_transforms.RandomScaleCrop(), custom_transforms.ArrayToTensor(), normalize ]) valid_transform = custom_transforms.Compose([custom_transforms.ArrayToTensor(), normalize]) print("=> fetching scenes in '{}'".format(args.data)) val_set = SequenceFolder( args.data, transform=valid_transform, seed=args.seed, ttype=args.ttype2, dataset = args.dataset, index = args.index ) train_set = SequenceFolder( args.data, transform=train_transform, seed=args.seed, ttype=args.ttype, dataset = args.dataset ) train_set.samples = train_set.samples[:len(train_set) - len(train_set)%args.batch_size] print('{} samples found in {} train scenes'.format(len(train_set), len(train_set.scenes))) print('{} samples found in {} valid scenes'.format(len(val_set), len(val_set.scenes))) train_loader = torch.utils.data.DataLoader( train_set, batch_size=args.batch_size, shuffle=True, num_workers=args.workers, pin_memory=True) val_loader = torch.utils.data.DataLoader( val_set, batch_size=1, shuffle=False, num_workers=args.workers, pin_memory=True) if args.epoch_size == 0: args.epoch_size = len(train_loader) # create model print("=> creating model") if args.dataset == 'sceneflow': args.mindepth = 5.45 mvdnet = MVDNet(args.nlabel, args.mindepth) #mvdnet = convert_model(mvdnet) if args.pretrained_mvdn: print("=> using pre-trained weights for MVDNet") weights = torch.load(args.pretrained_mvdn) mvdnet.init_weights() mvdnet.load_state_dict(weights['state_dict']) elif args.pretrained_dps: print("=> using pre-trained DPS weights for MVDNet") weights = torch.load('pretrained/dpsnet_updated.pth.tar') mvdnet.init_weights() mvdnet.load_state_dict(weights['state_dict'], strict = False) else: mvdnet.init_weights() print('=> setting adam solver') optimizer = torch.optim.Adam(mvdnet.parameters(), args.lr, betas=(args.momentum, args.beta), weight_decay=args.weight_decay) cudnn.benchmark = True mvdnet = torch.nn.DataParallel(mvdnet) mvdnet = mvdnet.cuda() print(' ==> setting log files') with open(args.save_path/args.log_summary, 'w') as csvfile: writer = csv.writer(csvfile, delimiter='\t') writer.writerow(['train_loss', 'validation_abs_rel', 'validation_abs_diff','validation_sq_rel', 'validation_a1', 'validation_a2', 'validation_a3', 'mean_angle_error']) with open(args.save_path/args.log_full, 'w') as csvfile: writer = csv.writer(csvfile, delimiter='\t') writer.writerow(['train_loss']) print(' ==> main Loop') for epoch in range(args.epochs): adjust_learning_rate(args, optimizer, epoch) # train for one epoch if args.evaluate: train_loss = 0 else: train_loss = train(args, train_loader, mvdnet, optimizer, args.epoch_size, training_writer, epoch) if not args.evaluate and (args.skip_v or (epoch+1)%3 != 0): error_names = ['abs_rel', 'abs_diff', 'sq_rel', 'a1', 'a2', 'a3', 'angle'] errors = [0]*7 else: errors, error_names = validate_with_gt(args, val_loader, mvdnet, epoch, output_writers) error_string = ', '.join('{} : {:.3f}'.format(name, error) for name, error in zip(error_names, errors)) for error, name in zip(errors, error_names): training_writer.add_scalar(name, error, epoch) # Up to you to chose the most relevant error to measure your model's performance, careful some measures are to maximize (such as a1,a2,a3) decisive_error = errors[0] with open(args.save_path/args.log_summary, 'a') as csvfile: writer = csv.writer(csvfile, delimiter='\t') writer.writerow([train_loss, decisive_error, errors[1], errors[2], errors[3], errors[4], errors[5], errors[6]]) if args.evaluate: break save_checkpoint( args.save_path, { 'epoch': epoch + 1, 'state_dict': mvdnet.module.state_dict() }, epoch, file_prefixes = ['mvdnet']) def train(args, train_loader, mvdnet, optimizer, epoch_size, train_writer, epoch): global n_iter batch_time = AverageMeter() data_time = AverageMeter() losses = AverageMeter(precision=4) d_losses = AverageMeter(precision=4) nmap_losses = AverageMeter(precision=4) # switch to training mode mvdnet.train() print("Training") end = time.time() for i, (tgt_img, ref_imgs, gt_nmap, ref_poses, intrinsics, intrinsics_inv, tgt_depth) in enumerate(train_loader): # measure data loading time data_time.update(time.time() - end) tgt_img_var = Variable(tgt_img.cuda()) ref_imgs_var = [Variable(img.cuda()) for img in ref_imgs] gt_nmap_var = Variable(gt_nmap.cuda()) ref_poses_var = [Variable(pose.cuda()) for pose in ref_poses] intrinsics_var = Variable(intrinsics.cuda()) intrinsics_inv_var = Variable(intrinsics_inv.cuda()) tgt_depth_var = Variable(tgt_depth.cuda()).cuda() # compute output pose = torch.cat(ref_poses_var,1) if args.dataset == 'sceneflow': factor = (1.0/args.scale)*intrinsics_var[:,0,0]/1050.0 factor = factor.view(-1,1,1) else: factor = torch.ones((tgt_depth_var.size(0),1,1)).type_as(tgt_depth_var) # get mask mask = (tgt_depth_var <= args.nlabel*args.mindepth*factor*3) & (tgt_depth_var >= args.mindepth*factor) & (tgt_depth_var == tgt_depth_var) mask.detach_() if mask.any() == 0: continue targetimg = inverse_warp(ref_imgs_var[0], tgt_depth_var.unsqueeze(1), pose[:,0], intrinsics_var, intrinsics_inv_var)#[B,CH,D,H,W,1] outputs = mvdnet(tgt_img_var, ref_imgs_var, pose, intrinsics_var, intrinsics_inv_var, factor = factor.unsqueeze(1)) nmap = outputs[2].permute(0,3,1,2) depths = outputs[0:2] disps = [args.mindepth*args.nlabel/(depth) for depth in depths] # correct disps if args.dataset == 'sceneflow': disps = [(args.mindepth*args.nlabel)*3/(depth) for depth in depths] # correct disps depths = [(args.mindepth*factor)*(args.nlabel*3)/disp for disp in disps] loss = 0. d_loss = 0. nmap_loss = 0. if args.dataset == 'sceneflow': tgt_disp_var = ((1.0/args.scale)*intrinsics_var[:,0,0].view(-1,1,1)/tgt_depth_var) for l, disp in enumerate(disps): output = torch.squeeze(disp,1) d_loss = d_loss + F.smooth_l1_loss(output[mask], tgt_disp_var[mask]) * pow(0.7, len(disps)-l-1) else: for l, depth in enumerate(depths): output = torch.squeeze(depth,1) d_loss = d_loss + F.smooth_l1_loss(output[mask], tgt_depth_var[mask]) * pow(0.7, len(depths)-l-1) n_mask = mask.unsqueeze(1).expand(-1,3,-1,-1) nmap_loss = nmap_loss + F.smooth_l1_loss(nmap[n_mask], gt_nmap_var[n_mask]) loss = loss + args.d_weight*d_loss + args.n_weight*nmap_loss if i > 0 and n_iter % args.print_freq == 0: train_writer.add_scalar('total_loss', loss.item(), n_iter) # record loss and EPE losses.update(loss.item(), args.batch_size) d_losses.update(d_loss.item(), args.batch_size) nmap_losses.update(nmap_loss.item(), args.batch_size) # compute gradient and do Adam step optimizer.zero_grad() loss.backward() optimizer.step() # measure elapsed time batch_time.update(time.time() - end) end = time.time() with open(args.save_path/args.log_full, 'a') as csvfile: writer = csv.writer(csvfile, delimiter='\t') writer.writerow([loss.item()]) if i % args.print_freq == 0: print('Train: Time {} Data {} Loss {} NmapLoss {} DLoss {} Iter {}/{} Epoch {}/{}'.format(batch_time, data_time, losses, nmap_losses, d_losses, i, len(train_loader), epoch, args.epochs)) if i >= epoch_size - 1: break n_iter += 1 return losses.avg[0] def validate_with_gt(args, val_loader, mvdnet, epoch, output_writers=[]): batch_time = AverageMeter() error_names = ['abs_rel', 'abs_diff', 'sq_rel', 'a1', 'a2', 'a3', 'mean_angle'] test_error_names = ['abs_rel','abs_diff','sq_rel','rms','log_rms','a1','a2','a3', 'mean_angle'] errors = AverageMeter(i=len(error_names)) test_errors = AverageMeter(i=len(test_error_names)) log_outputs = len(output_writers) > 0 output_dir= Path(args.output_dir) if not os.path.isdir(output_dir): os.mkdir(output_dir) # switch to evaluate mode mvdnet.eval() end = time.time() with torch.no_grad(): for i, (tgt_img, ref_imgs, gt_nmap, ref_poses, intrinsics, intrinsics_inv, tgt_depth) in enumerate(val_loader): tgt_img_var = Variable(tgt_img.cuda()) ref_imgs_var = [Variable(img.cuda()) for img in ref_imgs] gt_nmap_var = Variable(gt_nmap.cuda()) ref_poses_var = [Variable(pose.cuda()) for pose in ref_poses] intrinsics_var = Variable(intrinsics.cuda()) intrinsics_inv_var = Variable(intrinsics_inv.cuda()) tgt_depth_var = Variable(tgt_depth.cuda()) pose = torch.cat(ref_poses_var,1) if (pose != pose).any(): continue if args.dataset == 'sceneflow': factor = (1.0/args.scale)*intrinsics_var[:,0,0]/1050.0 factor = factor.view(-1,1,1) else: factor = torch.ones((tgt_depth_var.size(0),1,1)).type_as(tgt_depth_var) # get mask mask = (tgt_depth_var <= args.nlabel*args.mindepth*factor*3) & (tgt_depth_var >= args.mindepth*factor) & (tgt_depth_var == tgt_depth_var) if not mask.any(): continue output_depth, nmap = mvdnet(tgt_img_var, ref_imgs_var, pose, intrinsics_var, intrinsics_inv_var, factor = factor.unsqueeze(1)) output_disp = args.nlabel*args.mindepth/(output_depth) if args.dataset == 'sceneflow': output_disp = (args.nlabel*args.mindepth)*3/(output_depth) output_depth = (args.nlabel*3)*(args.mindepth*factor)/output_disp tgt_disp_var = ((1.0/args.scale)*intrinsics_var[:,0,0].view(-1,1,1)/tgt_depth_var) if args.dataset == 'sceneflow': output = torch.squeeze(output_disp.data.cpu(),1) errors_ = compute_errors_train(tgt_disp_var.cpu(), output, mask) test_errors_ = list(compute_errors_test(tgt_disp_var.cpu()[mask], output[mask])) else: output = torch.squeeze(output_depth.data.cpu(),1) errors_ = compute_errors_train(tgt_depth, output, mask) test_errors_ = list(compute_errors_test(tgt_depth[mask], output[mask])) n_mask = (gt_nmap_var.permute(0,2,3,1)[0,:,:] != 0) n_mask = n_mask[:,:,0] | n_mask[:,:,1] | n_mask[:,:,2] total_angles_m = compute_angles(gt_nmap_var.permute(0,2,3,1)[0], nmap[0]) mask_angles = total_angles_m[n_mask] total_angles_m[~ n_mask] = 0 errors_.append(torch.mean(mask_angles).item())#/mask_angles.size(0)#[torch.sum(mask_angles).item(), (mask_angles.size(0)), torch.sum(mask_angles < 7.5).item(), torch.sum(mask_angles < 15).item(), torch.sum(mask_angles < 30).item(), torch.sum(mask_angles < 45).item()] test_errors_.append(torch.mean(mask_angles).item()) errors.update(errors_) test_errors.update(test_errors_) # measure elapsed time batch_time.update(time.time() - end) end = time.time() if args.output_print: np.save(output_dir/'{:04d}{}'.format(i,'_depth.npy'), output.numpy()[0]) plt.imsave(output_dir/'{:04d}_gt{}'.format(i,'.png'), tgt_depth.numpy()[0], cmap='rainbow') imsave(output_dir/'{:04d}_aimage{}'.format(i,'.png'), np.transpose(tgt_img.numpy()[0],(1,2,0))) np.save(output_dir/'{:04d}_cam{}'.format(i,'.npy'),intrinsics_var.cpu().numpy()[0]) np.save(output_dir/'{:04d}{}'.format(i,'_normal.npy'), nmap.cpu().numpy()[0]) if i % args.print_freq == 0: print('valid: Time {} Abs Error {:.4f} ({:.4f}) Abs angle Error {:.4f} ({:.4f}) Iter {}/{}'.format(batch_time, test_errors.val[0], test_errors.avg[0], test_errors.val[-1], test_errors.avg[-1], i, len(val_loader))) if args.output_print: np.savetxt(output_dir/args.ttype+'errors.csv', test_errors.avg, fmt='%1.4f', delimiter=',') np.savetxt(output_dir/args.ttype+'angle_errors.csv', test_errors.avg, fmt='%1.4f', delimiter=',') return errors.avg, error_names if __name__ == '__main__': main()
[ "os.mkdir", "argparse.ArgumentParser", "utils.adjust_learning_rate", "custom_transforms.Normalize", "torch.cat", "custom_transforms.ArrayToTensor", "torch.no_grad", "utils.save_path_formatter", "torch.utils.data.DataLoader", "torch.load", "numpy.savetxt", "torch.squeeze", "path.Path", "cus...
[((885, 1059), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Structure from Motion Learner training on KITTI and CityScapes Dataset"""', 'formatter_class': 'argparse.ArgumentDefaultsHelpFormatter'}), "(description=\n 'Structure from Motion Learner training on KITTI and CityScapes Dataset',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n", (908, 1059), False, 'import argparse\n'), ((5507, 5528), 'path.Path', 'Path', (['args.output_dir'], {}), '(args.output_dir)\n', (5511, 5528), False, 'from path import Path\n'), ((5546, 5579), 'utils.save_path_formatter', 'save_path_formatter', (['args', 'parser'], {}), '(args, parser)\n', (5565, 5579), False, 'from utils import tensor2array, save_checkpoint, save_path_formatter, adjust_learning_rate\n'), ((5746, 5774), 'torch.manual_seed', 'torch.manual_seed', (['args.seed'], {}), '(args.seed)\n', (5763, 5774), False, 'import torch\n'), ((5800, 5829), 'tensorboardX.SummaryWriter', 'SummaryWriter', (['args.save_path'], {}), '(args.save_path)\n', (5813, 5829), False, 'from tensorboardX import SummaryWriter\n'), ((6000, 6070), 'custom_transforms.Normalize', 'custom_transforms.Normalize', ([], {'mean': '[0.5, 0.5, 0.5]', 'std': '[0.5, 0.5, 0.5]'}), '(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])\n', (6027, 6070), False, 'import custom_transforms\n'), ((6768, 6900), 'data_loader.SequenceFolder', 'SequenceFolder', (['args.data'], {'transform': 'valid_transform', 'seed': 'args.seed', 'ttype': 'args.ttype2', 'dataset': 'args.dataset', 'index': 'args.index'}), '(args.data, transform=valid_transform, seed=args.seed, ttype=\n args.ttype2, dataset=args.dataset, index=args.index)\n', (6782, 6900), False, 'from data_loader import SequenceFolder\n'), ((6977, 7090), 'data_loader.SequenceFolder', 'SequenceFolder', (['args.data'], {'transform': 'train_transform', 'seed': 'args.seed', 'ttype': 'args.ttype', 'dataset': 'args.dataset'}), '(args.data, transform=train_transform, seed=args.seed, ttype=\n args.ttype, dataset=args.dataset)\n', (6991, 7090), False, 'from data_loader import SequenceFolder\n'), ((7451, 7579), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['train_set'], {'batch_size': 'args.batch_size', 'shuffle': '(True)', 'num_workers': 'args.workers', 'pin_memory': '(True)'}), '(train_set, batch_size=args.batch_size, shuffle=\n True, num_workers=args.workers, pin_memory=True)\n', (7478, 7579), False, 'import torch\n'), ((7612, 7724), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['val_set'], {'batch_size': '(1)', 'shuffle': '(False)', 'num_workers': 'args.workers', 'pin_memory': '(True)'}), '(val_set, batch_size=1, shuffle=False,\n num_workers=args.workers, pin_memory=True)\n', (7639, 7724), False, 'import torch\n'), ((7954, 7988), 'models.MVDNet', 'MVDNet', (['args.nlabel', 'args.mindepth'], {}), '(args.nlabel, args.mindepth)\n', (7960, 7988), True, 'from models import MVDNet as MVDNet\n'), ((8855, 8884), 'torch.nn.DataParallel', 'torch.nn.DataParallel', (['mvdnet'], {}), '(mvdnet)\n', (8876, 8884), False, 'import torch\n'), ((11120, 11134), 'logger.AverageMeter', 'AverageMeter', ([], {}), '()\n', (11132, 11134), False, 'from logger import TermLogger, AverageMeter\n'), ((11152, 11166), 'logger.AverageMeter', 'AverageMeter', ([], {}), '()\n', (11164, 11166), False, 'from logger import TermLogger, AverageMeter\n'), ((11181, 11206), 'logger.AverageMeter', 'AverageMeter', ([], {'precision': '(4)'}), '(precision=4)\n', (11193, 11206), False, 'from logger import TermLogger, AverageMeter\n'), ((11223, 11248), 'logger.AverageMeter', 'AverageMeter', ([], {'precision': '(4)'}), '(precision=4)\n', (11235, 11248), False, 'from logger import TermLogger, AverageMeter\n'), ((11268, 11293), 'logger.AverageMeter', 'AverageMeter', ([], {'precision': '(4)'}), '(precision=4)\n', (11280, 11293), False, 'from logger import TermLogger, AverageMeter\n'), ((11383, 11394), 'time.time', 'time.time', ([], {}), '()\n', (11392, 11394), False, 'import time\n'), ((15285, 15299), 'logger.AverageMeter', 'AverageMeter', ([], {}), '()\n', (15297, 15299), False, 'from logger import TermLogger, AverageMeter\n'), ((15652, 15673), 'path.Path', 'Path', (['args.output_dir'], {}), '(args.output_dir)\n', (15656, 15673), False, 'from path import Path\n'), ((15808, 15819), 'time.time', 'time.time', ([], {}), '()\n', (15817, 15819), False, 'import time\n'), ((8139, 8171), 'torch.load', 'torch.load', (['args.pretrained_mvdn'], {}), '(args.pretrained_mvdn)\n', (8149, 8171), False, 'import torch\n'), ((9035, 9070), 'csv.writer', 'csv.writer', (['csvfile'], {'delimiter': '"""\t"""'}), "(csvfile, delimiter='\\t')\n", (9045, 9070), False, 'import csv\n'), ((9330, 9365), 'csv.writer', 'csv.writer', (['csvfile'], {'delimiter': '"""\t"""'}), "(csvfile, delimiter='\\t')\n", (9340, 9365), False, 'import csv\n'), ((9493, 9537), 'utils.adjust_learning_rate', 'adjust_learning_rate', (['args', 'optimizer', 'epoch'], {}), '(args, optimizer, epoch)\n', (9513, 9537), False, 'from utils import tensor2array, save_checkpoint, save_path_formatter, adjust_learning_rate\n'), ((12049, 12076), 'torch.cat', 'torch.cat', (['ref_poses_var', '(1)'], {}), '(ref_poses_var, 1)\n', (12058, 12076), False, 'import torch\n'), ((14665, 14676), 'time.time', 'time.time', ([], {}), '()\n', (14674, 14676), False, 'import time\n'), ((15686, 15711), 'os.path.isdir', 'os.path.isdir', (['output_dir'], {}), '(output_dir)\n', (15699, 15711), False, 'import os\n'), ((15722, 15742), 'os.mkdir', 'os.mkdir', (['output_dir'], {}), '(output_dir)\n', (15730, 15742), False, 'import os\n'), ((15830, 15845), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (15843, 15845), False, 'import torch\n'), ((19848, 19948), 'numpy.savetxt', 'np.savetxt', (["(output_dir / args.ttype + 'errors.csv')", 'test_errors.avg'], {'fmt': '"""%1.4f"""', 'delimiter': '""","""'}), "(output_dir / args.ttype + 'errors.csv', test_errors.avg, fmt=\n '%1.4f', delimiter=',')\n", (19858, 19948), True, 'import numpy as np\n'), ((19949, 20054), 'numpy.savetxt', 'np.savetxt', (["(output_dir / args.ttype + 'angle_errors.csv')", 'test_errors.avg'], {'fmt': '"""%1.4f"""', 'delimiter': '""","""'}), "(output_dir / args.ttype + 'angle_errors.csv', test_errors.avg,\n fmt='%1.4f', delimiter=',')\n", (19959, 20054), True, 'import numpy as np\n'), ((6639, 6672), 'custom_transforms.ArrayToTensor', 'custom_transforms.ArrayToTensor', ([], {}), '()\n', (6670, 6672), False, 'import custom_transforms\n'), ((8373, 8420), 'torch.load', 'torch.load', (['"""pretrained/dpsnet_updated.pth.tar"""'], {}), "('pretrained/dpsnet_updated.pth.tar')\n", (8383, 8420), False, 'import torch\n'), ((10562, 10597), 'csv.writer', 'csv.writer', (['csvfile'], {'delimiter': '"""\t"""'}), "(csvfile, delimiter='\\t')\n", (10572, 10597), False, 'import csv\n'), ((13978, 14029), 'torch.nn.functional.smooth_l1_loss', 'F.smooth_l1_loss', (['nmap[n_mask]', 'gt_nmap_var[n_mask]'], {}), '(nmap[n_mask], gt_nmap_var[n_mask])\n', (13994, 14029), True, 'import torch.nn.functional as F\n'), ((14767, 14802), 'csv.writer', 'csv.writer', (['csvfile'], {'delimiter': '"""\t"""'}), "(csvfile, delimiter='\\t')\n", (14777, 14802), False, 'import csv\n'), ((16420, 16447), 'torch.cat', 'torch.cat', (['ref_poses_var', '(1)'], {}), '(ref_poses_var, 1)\n', (16429, 16447), False, 'import torch\n'), ((18982, 18993), 'time.time', 'time.time', ([], {}), '()\n', (18991, 18993), False, 'import time\n'), ((6221, 6297), 'custom_transforms.RandomCrop', 'custom_transforms.RandomCrop', ([], {'scale': 'args.scale', 'h': 'args.crop_h', 'w': 'args.crop_w'}), '(scale=args.scale, h=args.crop_h, w=args.crop_w)\n', (6249, 6297), False, 'import custom_transforms\n'), ((6318, 6351), 'custom_transforms.ArrayToTensor', 'custom_transforms.ArrayToTensor', ([], {}), '()\n', (6349, 6351), False, 'import custom_transforms\n'), ((6467, 6502), 'custom_transforms.RandomScaleCrop', 'custom_transforms.RandomScaleCrop', ([], {}), '()\n', (6500, 6502), False, 'import custom_transforms\n'), ((6517, 6550), 'custom_transforms.ArrayToTensor', 'custom_transforms.ArrayToTensor', ([], {}), '()\n', (6548, 6550), False, 'import custom_transforms\n'), ((11577, 11588), 'time.time', 'time.time', ([], {}), '()\n', (11586, 11588), False, 'import time\n'), ((13518, 13540), 'torch.squeeze', 'torch.squeeze', (['disp', '(1)'], {}), '(disp, 1)\n', (13531, 13540), False, 'import torch\n'), ((13742, 13765), 'torch.squeeze', 'torch.squeeze', (['depth', '(1)'], {}), '(depth, 1)\n', (13755, 13765), False, 'import torch\n'), ((14631, 14642), 'time.time', 'time.time', ([], {}), '()\n', (14640, 14642), False, 'import time\n'), ((17985, 18030), 'loss_functions.compute_errors_train', 'compute_errors_train', (['tgt_depth', 'output', 'mask'], {}), '(tgt_depth, output, mask)\n', (18005, 18030), False, 'from loss_functions import compute_errors_train, compute_errors_test, compute_angles\n'), ((18068, 18118), 'loss_functions.compute_errors_test', 'compute_errors_test', (['tgt_depth[mask]', 'output[mask]'], {}), '(tgt_depth[mask], output[mask])\n', (18087, 18118), False, 'from loss_functions import compute_errors_train, compute_errors_test, compute_angles\n'), ((18944, 18955), 'time.time', 'time.time', ([], {}), '()\n', (18953, 18955), False, 'import time\n'), ((13575, 13625), 'torch.nn.functional.smooth_l1_loss', 'F.smooth_l1_loss', (['output[mask]', 'tgt_disp_var[mask]'], {}), '(output[mask], tgt_disp_var[mask])\n', (13591, 13625), True, 'import torch.nn.functional as F\n'), ((13800, 13851), 'torch.nn.functional.smooth_l1_loss', 'F.smooth_l1_loss', (['output[mask]', 'tgt_depth_var[mask]'], {}), '(output[mask], tgt_depth_var[mask])\n', (13816, 13851), True, 'import torch.nn.functional as F\n'), ((18476, 18499), 'torch.mean', 'torch.mean', (['mask_angles'], {}), '(mask_angles)\n', (18486, 18499), False, 'import torch\n'), ((18763, 18786), 'torch.mean', 'torch.mean', (['mask_angles'], {}), '(mask_angles)\n', (18773, 18786), False, 'import torch\n')]
import os import numpy as np import tensorflow as tf import tqdm class Callback: """Callback object for customizing trainer. """ def __init__(self): pass def interval(self): """Callback interval, -1 for epochs, positives for steps """ raise NotImplementedError('Callback.interval is not implemented') def __call__(self, model, steps, epochs): """Call methods for manipulating models. Args: model: tf.keras.Model, model. steps: int, current steps. epochs: int, current epochs. """ raise NotImplementedError('Callback.__call__ is not implemented') class Trainer: """ALAE trainer. """ def __init__(self, summary_path, ckpt_path, ckpt_interval=None, callback=None): """Initializer. Args: summary_path: str, path to the summary. ckpt_path: str, path to the checkpoint. ckpt_interval: int, write checkpoints in given steps. callback: Callback, callback object for customizing. """ train_path = os.path.join(summary_path, 'train') test_path = os.path.join(summary_path, 'test') self.train_summary = tf.summary.create_file_writer(train_path) self.test_summary = tf.summary.create_file_writer(test_path) self.ckpt_path = ckpt_path self.ckpt_interval = ckpt_interval self.callback = callback def train(self, model, epochs, trainset, testset, trainlen=None): """Train ALAE model with given datasets. Args: model: ALAE, tf.keras.Model, ALAE model. epochs: int, the number of the epochs. trainset: tf.data.Dataset, training dataset. testset: tf.data.Dataset, test dataset. trainlen: int, length of the trainset. """ step = 0 cb_intval = self.callback.interval() \ if self.callback is not None else None for epoch in tqdm.tqdm(range(epochs)): if cb_intval == -1: # run callback in epoch order self.callback(model, step, epoch) # training phase with tqdm.tqdm(total=trainlen, leave=False) as pbar: for datum in trainset: if cb_intval is not None and \ cb_intval > 0 and step % cb_intval == 0: # run callback in step order self.callback(model, step, epoch) losses = model.trainstep(datum, epoch, step) self.write_summary(losses, step) if self.ckpt_interval is not None and \ step % self.ckpt_interval == 0: # if training set is too large _, flat = model(datum) self.write_image(datum, flat, step, train=False) self.write_checkpoint(model, step) step += 1 pbar.update() pbar.set_postfix({k: v.item() for k, v in losses.items()}) _, flat = model(datum) self.write_image(datum, flat, step) # test phase metrics = [] for datum in testset: metrics.append(model.losses(datum, epoch, step)) self.write_summary(self.mean_metric(metrics), step, train=False) _, flat = model(datum) self.write_image(datum, flat, step, train=False) # write checkpoint self.write_checkpoint(model, step) def write_summary(self, metrics, step, train=True): """Write tensorboard summary. Args: metrics: Dict[str, np.array], metrics. step: int, current step. train: bool, whether in training phase or test phase. """ summary = self.train_summary if train else self.test_summary with summary.as_default(): for key, value in metrics.items(): tf.summary.scalar(key, value, step=step) def write_image(self, datum, flat, step, train=True, name='image'): """Write image to the tensorboard summary. Args: flat: tf.Tensor, [B, ...], autoencoded image. step: int, current step. train: bool, whether in training phase or test phase. name: str, image name for tensorboard. """ # random index idx = np.random.randint(flat.shape[0]) summary = self.train_summary if train else self.test_summary with summary.as_default(): # write tensorboard summary tf.summary.image(name, flat[idx:idx + 1], step=step) # tf.summary.image(name + '_gt', datum[idx:idx + 1], step=step) def write_checkpoint(self, model, step): """Write checkpoints. Args: model: tf.keras.Model, model. step: int, current steps. """ path = os.path.join(self.ckpt_path, 'step{}.ckpt'.format(step)) model.write_ckpt(path) def mean_metric(self, metrics): """Compute mean of the metrics. Args: List[Dict[str, np.array]], metrics. Returns: Dict[str, np.array], mean metrics. """ size = 0 avgs = {} for metric in metrics: size += 1 for key, value in metric.items(): if key not in avgs: avgs[key] = 0 avgs[key] += value for key in avgs.keys(): avgs[key] /= size return avgs
[ "tqdm.tqdm", "tensorflow.summary.image", "tensorflow.summary.scalar", "numpy.random.randint", "tensorflow.summary.create_file_writer", "os.path.join" ]
[((1175, 1210), 'os.path.join', 'os.path.join', (['summary_path', '"""train"""'], {}), "(summary_path, 'train')\n", (1187, 1210), False, 'import os\n'), ((1231, 1265), 'os.path.join', 'os.path.join', (['summary_path', '"""test"""'], {}), "(summary_path, 'test')\n", (1243, 1265), False, 'import os\n'), ((1295, 1336), 'tensorflow.summary.create_file_writer', 'tf.summary.create_file_writer', (['train_path'], {}), '(train_path)\n', (1324, 1336), True, 'import tensorflow as tf\n'), ((1365, 1405), 'tensorflow.summary.create_file_writer', 'tf.summary.create_file_writer', (['test_path'], {}), '(test_path)\n', (1394, 1405), True, 'import tensorflow as tf\n'), ((4570, 4602), 'numpy.random.randint', 'np.random.randint', (['flat.shape[0]'], {}), '(flat.shape[0])\n', (4587, 4602), True, 'import numpy as np\n'), ((4759, 4811), 'tensorflow.summary.image', 'tf.summary.image', (['name', 'flat[idx:idx + 1]'], {'step': 'step'}), '(name, flat[idx:idx + 1], step=step)\n', (4775, 4811), True, 'import tensorflow as tf\n'), ((2264, 2302), 'tqdm.tqdm', 'tqdm.tqdm', ([], {'total': 'trainlen', 'leave': '(False)'}), '(total=trainlen, leave=False)\n', (2273, 2302), False, 'import tqdm\n'), ((4130, 4170), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['key', 'value'], {'step': 'step'}), '(key, value, step=step)\n', (4147, 4170), True, 'import tensorflow as tf\n')]
import argparse import os import numpy as np from Models import HIV4O_c as model # pylint: disable=no-name-in-module from Structures import ModelGeometry, PairMat, CompilerParameters, NNModel, TrainingParameters # pylint: disable=import-error from datetime import datetime # First we define an argument parser so we can use this as the command line utility parser = argparse.ArgumentParser(description='Accepts paths to validation and training data') # The first argument of the argparser should be a path to the validation data parser.add_argument('--test', required=True, dest='testing_list') # Accept a list of training files parser.add_argument('--train', required=True, nargs='+', dest='training_list') # Specify the choice of ordering to apply parser.add_argument('--ordering', required=True, dest='ordering', choices=['OLO', 'HC', 'None']) # Now parse the args into the namespace args = parser.parse_args() print(args) datums = [PairMat(data, method=args.ordering) for data in args.training_list] # Import the training data nSamples = datums[0].pairwise_mats.shape[1] test_data = PairMat(args.testing_list, method=args.ordering) # Import the test data geo = ModelGeometry(datums[0]) # pass in a # Print these to console for logging purposes print('dimension: ', geo.dimensions) print('output: ', geo.output) print('input: ', geo.input) print('Begin making models') compiler_params = CompilerParameters(loss='categorical_crossentropy', metrics=['acc', 'categorical_crossentropy']) # we might not want the default options models = [model(model_geometry=geo, compiler_parameters=compiler_params) for data in datums] models[0].NN.summary() # initialize models with correct geometry # Set training parameters training_parameters = TrainingParameters(epoch=50, batch_size=32) print('Reach end of setup and allocations. Proceeding to train models') the_time = datetime.now() dt_string = the_time.strftime("%d-%m-%Y--%H-%M-%S") print(dt_string) for index in range(len(args.training_list)): models[index].train(pair_mat=datums[index], training_parameters=training_parameters, test_pair_mat=test_data) print(f'completed training model from: {index}') model_dir_name = f'User_models/Model-{nSamples}/{args.ordering}' # save directory hard-coded here model_dir = os.path.abspath(os.sep) + os.path.realpath(os.path.dirname(__file__) + '/../Trained_models/' + model_dir_name + '/') try: os.makedirs(model_dir) except OSError: # dir already exists - notify user and continue print(model_dir) print('Caught OSError, dir already exists') filename = '/P-' + str(index) + '-time-' + dt_string print(filename) # The actual model file name # "Models_tmp" is the default save directory for trained models models[index].save_model(filename, prefix=f'../Trained_models/{model_dir_name}/Order-{args.ordering}-{nSamples}/') # Let's run out some per-label statistics pred_vector = models[index].predict(x=test_data.pairwise_mats) pred_vals = np.argmax(pred_vector, axis=1) for label in range(np.amax(test_data.train.labels) - 1): # use a boolean mask to find the index of images with the desired labels inds = np.where(np.argmax(test_data.train.categorical_labels, axis=1) == label, True, False) print(f'The selected index shape for label {label} is {inds.shape}') print('The predictions matrix has shape:', pred_vals.shape) acc = np.sum(pred_vals[inds] == np.argmax(test_data.train.categorical_labels, axis=1)[inds]) print(f'Label: {label} \tAccuracy: {acc}') print('Model training and analysis complete. Exiting script.')
[ "os.path.abspath", "argparse.ArgumentParser", "Models.HIV4O_c", "numpy.argmax", "os.makedirs", "os.path.dirname", "Structures.TrainingParameters", "Structures.ModelGeometry", "numpy.amax", "Structures.PairMat", "datetime.datetime.now", "Structures.CompilerParameters" ]
[((369, 458), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Accepts paths to validation and training data"""'}), "(description=\n 'Accepts paths to validation and training data')\n", (392, 458), False, 'import argparse\n'), ((1095, 1143), 'Structures.PairMat', 'PairMat', (['args.testing_list'], {'method': 'args.ordering'}), '(args.testing_list, method=args.ordering)\n', (1102, 1143), False, 'from Structures import ModelGeometry, PairMat, CompilerParameters, NNModel, TrainingParameters\n'), ((1174, 1198), 'Structures.ModelGeometry', 'ModelGeometry', (['datums[0]'], {}), '(datums[0])\n', (1187, 1198), False, 'from Structures import ModelGeometry, PairMat, CompilerParameters, NNModel, TrainingParameters\n'), ((1400, 1500), 'Structures.CompilerParameters', 'CompilerParameters', ([], {'loss': '"""categorical_crossentropy"""', 'metrics': "['acc', 'categorical_crossentropy']"}), "(loss='categorical_crossentropy', metrics=['acc',\n 'categorical_crossentropy'])\n", (1418, 1500), False, 'from Structures import ModelGeometry, PairMat, CompilerParameters, NNModel, TrainingParameters\n'), ((1783, 1826), 'Structures.TrainingParameters', 'TrainingParameters', ([], {'epoch': '(50)', 'batch_size': '(32)'}), '(epoch=50, batch_size=32)\n', (1801, 1826), False, 'from Structures import ModelGeometry, PairMat, CompilerParameters, NNModel, TrainingParameters\n'), ((1911, 1925), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (1923, 1925), False, 'from datetime import datetime\n'), ((943, 978), 'Structures.PairMat', 'PairMat', (['data'], {'method': 'args.ordering'}), '(data, method=args.ordering)\n', (950, 978), False, 'from Structures import ModelGeometry, PairMat, CompilerParameters, NNModel, TrainingParameters\n'), ((1586, 1648), 'Models.HIV4O_c', 'model', ([], {'model_geometry': 'geo', 'compiler_parameters': 'compiler_params'}), '(model_geometry=geo, compiler_parameters=compiler_params)\n', (1591, 1648), True, 'from Models import HIV4O_c as model\n'), ((3104, 3134), 'numpy.argmax', 'np.argmax', (['pred_vector'], {'axis': '(1)'}), '(pred_vector, axis=1)\n', (3113, 3134), True, 'import numpy as np\n'), ((2375, 2398), 'os.path.abspath', 'os.path.abspath', (['os.sep'], {}), '(os.sep)\n', (2390, 2398), False, 'import os\n'), ((2509, 2531), 'os.makedirs', 'os.makedirs', (['model_dir'], {}), '(model_dir)\n', (2520, 2531), False, 'import os\n'), ((3158, 3189), 'numpy.amax', 'np.amax', (['test_data.train.labels'], {}), '(test_data.train.labels)\n', (3165, 3189), True, 'import numpy as np\n'), ((3301, 3354), 'numpy.argmax', 'np.argmax', (['test_data.train.categorical_labels'], {'axis': '(1)'}), '(test_data.train.categorical_labels, axis=1)\n', (3310, 3354), True, 'import numpy as np\n'), ((3563, 3616), 'numpy.argmax', 'np.argmax', (['test_data.train.categorical_labels'], {'axis': '(1)'}), '(test_data.train.categorical_labels, axis=1)\n', (3572, 3616), True, 'import numpy as np\n'), ((2418, 2443), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (2433, 2443), False, 'import os\n')]
import numpy as np import pytest from astropy import units as u from astropy.io import fits from astropy.nddata import NDData from astropy.table import Table from astropy.utils.exceptions import AstropyDeprecationWarning from ginga.ColorDist import ColorDistBase from ..core import ImageWidget, ALLOWED_CURSOR_LOCATIONS def test_load_fits(): image = ImageWidget() data = np.random.random([100, 100]) hdu = fits.PrimaryHDU(data=data) image.load_fits(hdu) def test_load_nddata(): image = ImageWidget() data = np.random.random([100, 100]) nddata = NDData(data) image.load_nddata(nddata) def test_load_array(): image = ImageWidget() data = np.random.random([100, 100]) image.load_array(data) def test_center_on(): image = ImageWidget() x = 10 y = 10 image.center_on((x, y)) def test_offset_to(): image = ImageWidget() dx = 10 dy = 10 with pytest.warns(AstropyDeprecationWarning): image.offset_to(dx, dy) def test_offset_by(): image = ImageWidget() # Pixels image.offset_by(10, 10) image.offset_by(10 * u.pix, 10 * u.dimensionless_unscaled) image.offset_by(10, 10 * u.pix) # Sky image.offset_by(1 * u.arcsec, 0.001 * u.deg) with pytest.raises(u.UnitConversionError): image.offset_by(1 * u.arcsec, 1 * u.AA) with pytest.raises(ValueError, match='but dy is of type'): image.offset_by(1 * u.arcsec, 1) def test_zoom_level(): image = ImageWidget() image.zoom_level = 5 assert image.zoom_level == 5 def test_zoom(): image = ImageWidget() image.zoom_level = 3 val = 2 image.zoom(val) assert image.zoom_level == 6 @pytest.mark.xfail(reason='Not implemented yet') def test_select_points(): image = ImageWidget() image.select_points() def test_get_selection(): image = ImageWidget() marks = image.get_markers() assert isinstance(marks, Table) or marks is None def test_stop_marking(): image = ImageWidget() # This is not much of a test... image.stop_marking(clear_markers=True) assert image.get_markers() is None assert image.is_marking is False def test_is_marking(): image = ImageWidget() assert image.is_marking in [True, False] with pytest.raises(AttributeError): image.is_marking = True def test_start_marking(): image = ImageWidget() # Setting these to check that start_marking affects them. image.click_center = True assert image.click_center image.scroll_pan = False assert not image.scroll_pan marker_style = {'color': 'yellow', 'radius': 10, 'type': 'cross'} image.start_marking(marker_name='something', marker=marker_style) assert image.is_marking assert image.marker == marker_style assert not image.click_center assert not image.click_drag # scroll_pan better activate when marking otherwise there is # no way to pan while interactively marking assert image.scroll_pan # Make sure that when we stop_marking we get our old # controls back. image.stop_marking() assert image.click_center assert not image.scroll_pan # Make sure that click_drag is restored as expected image.click_drag = True image.start_marking() assert not image.click_drag image.stop_marking() assert image.click_drag def test_add_markers(): image = ImageWidget() table = Table(data=np.random.randint(0, 100, [5, 2]), names=['x', 'y'], dtype=('int', 'int')) image.add_markers(table, x_colname='x', y_colname='y', skycoord_colname='coord') def test_set_markers(): image = ImageWidget() image.marker = {'color': 'yellow', 'radius': 10, 'type': 'cross'} assert 'cross' in str(image.marker) assert 'yellow' in str(image.marker) assert '10' in str(image.marker) def test_reset_markers(): image = ImageWidget() # First test: this shouldn't raise any errors # (it also doesn't *do* anything...) image.reset_markers() assert image.get_markers() is None table = Table(data=np.random.randint(0, 100, [5, 2]), names=['x', 'y'], dtype=('int', 'int')) image.add_markers(table, x_colname='x', y_colname='y', skycoord_colname='coord', marker_name='test') image.add_markers(table, x_colname='x', y_colname='y', skycoord_colname='coord', marker_name='test2') image.reset_markers() with pytest.raises(ValueError): image.get_markers(marker_name='test') with pytest.raises(ValueError): image.get_markers(marker_name='test2') def test_remove_markers(): image = ImageWidget() # Add a tag name... image._marktags.add(image._default_mark_tag_name) with pytest.raises(ValueError) as e: image.remove_markers('arf') assert 'arf' in str(e.value) def test_stretch(): image = ImageWidget() with pytest.raises(ValueError) as e: image.stretch = 'not a valid value' assert 'must be one of' in str(e.value) image.stretch = 'log' assert isinstance(image.stretch, (ColorDistBase)) def test_cuts(): image = ImageWidget() # An invalid string should raise an error with pytest.raises(ValueError) as e: image.cuts = 'not a valid value' assert 'must be one of' in str(e.value) # Setting cuts to something with incorrect length # should raise an error. with pytest.raises(ValueError) as e: image.cuts = (1, 10, 100) assert 'length 2' in str(e.value) # These ought to succeed image.cuts = 'histogram' assert image.cuts == (0.0, 0.0) image.cuts = [10, 100] assert image.cuts == (10, 100) def test_colormap(): image = ImageWidget() cmap_desired = 'gray' cmap_list = image.colormap_options assert len(cmap_list) > 0 and cmap_desired in cmap_list image.set_colormap(cmap_desired) def test_cursor(): image = ImageWidget() assert image.cursor in ALLOWED_CURSOR_LOCATIONS with pytest.raises(ValueError): image.cursor = 'not a valid option' image.cursor = 'bottom' assert image.cursor == 'bottom' def test_click_drag(): image = ImageWidget() # Set this to ensure that click_drag turns it off image._click_center = True # Make sure that setting click_drag to False does not turn off # click_center. image.click_drag = False assert image.click_center image.click_drag = True assert not image.click_center # If is_marking is true then trying to click_drag # should fail. image._is_marking = True with pytest.raises(ValueError) as e: image.click_drag = True assert 'Interactive marking' in str(e.value) def test_click_center(): image = ImageWidget() assert (image.click_center is True) or (image.click_center is False) # Set click_drag True and check that click_center affects it appropriately image.click_drag = True image.click_center = False assert image.click_drag image.click_center = True assert not image.click_drag image.start_marking() # If marking is in progress then setting click center should fail with pytest.raises(ValueError) as e: image.click_center = True assert 'Cannot set' in str(e.value) # setting to False is fine though so no error is expected here image.click_center = False def test_scroll_pan(): image = ImageWidget() # Make sure scroll_pan is actually settable for val in [True, False]: image.scroll_pan = val assert image.scroll_pan is val def test_save(tmp_path): image = ImageWidget() filename = 'woot.png' image.save(tmp_path / filename) def test_width_height(): image = ImageWidget(image_width=250, image_height=100) assert image.image_width == 250 assert image.image_height == 100
[ "pytest.warns", "astropy.nddata.NDData", "astropy.io.fits.PrimaryHDU", "pytest.raises", "numpy.random.random", "numpy.random.randint", "pytest.mark.xfail" ]
[((1697, 1744), 'pytest.mark.xfail', 'pytest.mark.xfail', ([], {'reason': '"""Not implemented yet"""'}), "(reason='Not implemented yet')\n", (1714, 1744), False, 'import pytest\n'), ((385, 413), 'numpy.random.random', 'np.random.random', (['[100, 100]'], {}), '([100, 100])\n', (401, 413), True, 'import numpy as np\n'), ((424, 450), 'astropy.io.fits.PrimaryHDU', 'fits.PrimaryHDU', ([], {'data': 'data'}), '(data=data)\n', (439, 450), False, 'from astropy.io import fits\n'), ((539, 567), 'numpy.random.random', 'np.random.random', (['[100, 100]'], {}), '([100, 100])\n', (555, 567), True, 'import numpy as np\n'), ((581, 593), 'astropy.nddata.NDData', 'NDData', (['data'], {}), '(data)\n', (587, 593), False, 'from astropy.nddata import NDData\n'), ((686, 714), 'numpy.random.random', 'np.random.random', (['[100, 100]'], {}), '([100, 100])\n', (702, 714), True, 'import numpy as np\n'), ((925, 964), 'pytest.warns', 'pytest.warns', (['AstropyDeprecationWarning'], {}), '(AstropyDeprecationWarning)\n', (937, 964), False, 'import pytest\n'), ((1259, 1295), 'pytest.raises', 'pytest.raises', (['u.UnitConversionError'], {}), '(u.UnitConversionError)\n', (1272, 1295), False, 'import pytest\n'), ((1355, 1407), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': '"""but dy is of type"""'}), "(ValueError, match='but dy is of type')\n", (1368, 1407), False, 'import pytest\n'), ((2275, 2304), 'pytest.raises', 'pytest.raises', (['AttributeError'], {}), '(AttributeError)\n', (2288, 2304), False, 'import pytest\n'), ((4510, 4535), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (4523, 4535), False, 'import pytest\n'), ((4592, 4617), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (4605, 4617), False, 'import pytest\n'), ((4808, 4833), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (4821, 4833), False, 'import pytest\n'), ((4966, 4991), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (4979, 4991), False, 'import pytest\n'), ((5268, 5293), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (5281, 5293), False, 'import pytest\n'), ((5478, 5503), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (5491, 5503), False, 'import pytest\n'), ((6061, 6086), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (6074, 6086), False, 'import pytest\n'), ((6656, 6681), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (6669, 6681), False, 'import pytest\n'), ((7232, 7257), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (7245, 7257), False, 'import pytest\n'), ((3454, 3487), 'numpy.random.randint', 'np.random.randint', (['(0)', '(100)', '[5, 2]'], {}), '(0, 100, [5, 2])\n', (3471, 3487), True, 'import numpy as np\n'), ((4127, 4160), 'numpy.random.randint', 'np.random.randint', (['(0)', '(100)', '[5, 2]'], {}), '(0, 100, [5, 2])\n', (4144, 4160), True, 'import numpy as np\n')]
""" Some codes from https://github.com/Newmu/dcgan_code """ from __future__ import division import math import json import random import pprint import scipy.misc import os import numpy as np from time import gmtime, strftime from six.moves import xrange from glob import glob import tensorflow as tf import tensorflow.contrib.slim as slim pp = pprint.PrettyPrinter() get_stddev = lambda x, k_h, k_w: 1/math.sqrt(k_w*k_h*x.get_shape()[-1]) def show_all_variables(): model_vars = tf.trainable_variables() slim.model_analyzer.analyze_vars(model_vars, print_info=True) def get_image(image_path, input_height, input_width, resize_height=64, resize_width=64, crop=True, grayscale=False): image = imread(image_path, grayscale) return transform(image, input_height, input_width, resize_height, resize_width, crop) def save_images(images, size, image_path): return imsave(inverse_transform(images), size, image_path) def imread(path, grayscale = False): if (grayscale): return scipy.misc.imread(path, flatten = True).astype(np.float) else: return scipy.misc.imread(path).astype(np.float) def merge_images(images, size): return inverse_transform(images) def merge(images, size): h, w = images.shape[1], images.shape[2] if (images.shape[3] in (3,4)): c = images.shape[3] img = np.zeros((h * size[0], w * size[1], c)) for idx, image in enumerate(images): i = idx % size[1] j = idx // size[1] img[j * h:j * h + h, i * w:i * w + w, :] = image return img elif images.shape[3]==1: img = np.zeros((h * size[0], w * size[1])) for idx, image in enumerate(images): i = idx % size[1] j = idx // size[1] img[j * h:j * h + h, i * w:i * w + w] = image[:,:,0] return img else: raise ValueError('in merge(images,size) images parameter ' 'must have dimensions: HxW or HxWx3 or HxWx4') def imsave(images, size, path): image = np.squeeze(merge(images, size)) return scipy.misc.imsave(path, image) def center_crop(x, crop_h, crop_w, resize_h=64, resize_w=64): if crop_w is None: crop_w = crop_h h, w = x.shape[:2] j = int(round((h - crop_h)/2.)) i = int(round((w - crop_w)/2.)) return scipy.misc.imresize( x[j:j+crop_h, i:i+crop_w], [resize_h, resize_w]) def transform(image, input_height, input_width, resize_height=64, resize_width=64, crop=True): if crop: cropped_image = center_crop( image, input_height, input_width, resize_height, resize_width) else: cropped_image = scipy.misc.imresize(image, [resize_height, resize_width]) return np.array(cropped_image)/127.5 - 1. def inverse_transform(images): return (images+1.)/2. def to_json(output_path, *layers): with open(output_path, "w") as layer_f: lines = "" for w, b, bn in layers: layer_idx = w.name.split('/')[0].split('h')[1] B = b.eval() if "lin/" in w.name: W = w.eval() depth = W.shape[1] else: W = np.rollaxis(w.eval(), 2, 0) depth = W.shape[0] biases = {"sy": 1, "sx": 1, "depth": depth, "w": ['%.2f' % elem for elem in list(B)]} if bn != None: gamma = bn.gamma.eval() beta = bn.beta.eval() gamma = {"sy": 1, "sx": 1, "depth": depth, "w": ['%.2f' % elem for elem in list(gamma)]} beta = {"sy": 1, "sx": 1, "depth": depth, "w": ['%.2f' % elem for elem in list(beta)]} else: gamma = {"sy": 1, "sx": 1, "depth": 0, "w": []} beta = {"sy": 1, "sx": 1, "depth": 0, "w": []} if "lin/" in w.name: fs = [] for w in W.T: fs.append({"sy": 1, "sx": 1, "depth": W.shape[0], "w": ['%.2f' % elem for elem in list(w)]}) lines += """ var layer_%s = { "layer_type": "fc", "sy": 1, "sx": 1, "out_sx": 1, "out_sy": 1, "stride": 1, "pad": 0, "out_depth": %s, "in_depth": %s, "biases": %s, "gamma": %s, "beta": %s, "filters": %s };""" % (layer_idx.split('_')[0], W.shape[1], W.shape[0], biases, gamma, beta, fs) else: fs = [] for w_ in W: fs.append({"sy": 5, "sx": 5, "depth": W.shape[3], "w": ['%.2f' % elem for elem in list(w_.flatten())]}) lines += """ var layer_%s = { "layer_type": "deconv", "sy": 5, "sx": 5, "out_sx": %s, "out_sy": %s, "stride": 2, "pad": 1, "out_depth": %s, "in_depth": %s, "biases": %s, "gamma": %s, "beta": %s, "filters": %s };""" % (layer_idx, 2**(int(layer_idx)+2), 2**(int(layer_idx)+2), W.shape[0], W.shape[3], biases, gamma, beta, fs) layer_f.write(" ".join(lines.replace("'","").split())) def make_gif(images, fname, duration=2, true_image=False): import moviepy.editor as mpy def make_frame(t): try: x = images[int(len(images)/duration*t)] except: x = images[-1] if true_image: return x.astype(np.uint8) else: return ((x+1)/2*255).astype(np.uint8) clip = mpy.VideoClip(make_frame, duration=duration) clip.write_gif(fname, fps = len(images) / duration) def visualize(sess, dcgan, config, option): image_frame_dim = int(math.ceil(config.batch_size**.5)) if option == 0: z_sample = np.random.uniform(-0.5, 0.5, size=(config.batch_size, dcgan.z_dim)) samples = sess.run(dcgan.sampler, feed_dict={dcgan.z: z_sample}) save_images(samples, [image_frame_dim, image_frame_dim], './samples/test_%s.png' % strftime("%Y-%m-%d-%H-%M-%S", gmtime())) elif option == 1: values = np.arange(0, 1, 1./config.batch_size) for idx in xrange(dcgan.z_dim): print(" [*] %d" % idx) z_sample = np.random.uniform(-1, 1, size=(config.batch_size , dcgan.z_dim)) for kdx, z in enumerate(z_sample): z[idx] = values[kdx] if config.dataset == "mnist": y = np.random.choice(10, config.batch_size) y_one_hot = np.zeros((config.batch_size, 10)) y_one_hot[np.arange(config.batch_size), y] = 1 samples = sess.run(dcgan.sampler, feed_dict={dcgan.z: z_sample, dcgan.y: y_one_hot}) else: samples = sess.run(dcgan.sampler, feed_dict={dcgan.z: z_sample}) save_images(samples, [image_frame_dim, image_frame_dim], './samples/test_arange_%s.png' % (idx)) elif option == 2: values = np.arange(0, 1, 1./config.batch_size) for idx in [random.randint(0, dcgan.z_dim - 1) for _ in xrange(dcgan.z_dim)]: print(" [*] %d" % idx) z = np.random.uniform(-0.2, 0.2, size=(dcgan.z_dim)) z_sample = np.tile(z, (config.batch_size, 1)) #z_sample = np.zeros([config.batch_size, dcgan.z_dim]) for kdx, z in enumerate(z_sample): z[idx] = values[kdx] if config.dataset == "mnist": y = np.random.choice(10, config.batch_size) y_one_hot = np.zeros((config.batch_size, 10)) y_one_hot[np.arange(config.batch_size), y] = 1 samples = sess.run(dcgan.sampler, feed_dict={dcgan.z: z_sample, dcgan.y: y_one_hot}) else: samples = sess.run(dcgan.sampler, feed_dict={dcgan.z: z_sample}) try: make_gif(samples, './samples/test_gif_%s.gif' % (idx)) except: save_images(samples, [image_frame_dim, image_frame_dim], './samples/test_%s.png' % strftime("%Y-%m-%d-%H-%M-%S", gmtime())) elif option == 3: values = np.arange(0, 1, 1./config.batch_size) for idx in xrange(dcgan.z_dim): print(" [*] %d" % idx) z_sample = np.zeros([config.batch_size, dcgan.z_dim]) for kdx, z in enumerate(z_sample): z[idx] = values[kdx] samples = sess.run(dcgan.sampler, feed_dict={dcgan.z: z_sample}) make_gif(samples, './samples/test_gif_%s.gif' % (idx)) elif option == 4: image_set = [] values = np.arange(0, 1, 1./config.batch_size) for idx in xrange(dcgan.z_dim): print(" [*] %d" % idx) z_sample = np.zeros([config.batch_size, dcgan.z_dim]) for kdx, z in enumerate(z_sample): z[idx] = values[kdx] image_set.append(sess.run(dcgan.sampler, feed_dict={dcgan.z: z_sample})) make_gif(image_set[-1], './samples/test_gif_%s.gif' % (idx)) new_image_set = [merge(np.array([images[idx] for images in image_set]), [10, 10]) \ for idx in range(64) + range(63, -1, -1)] make_gif(new_image_set, './samples/test_gif_merged.gif', duration=8) elif option == 6: #Original together with inpainting, coloured. #Prints: Half original + generated upper half # and full generated next to full original batch_size = config.batch_size for idx in xrange(min(8,int(np.floor(1000/batch_size)))): print(" [*] %d" % idx) sample_inputs, sample_img, sample_labels = get_img(dcgan, idx*batch_size, batch_size, config.dataset, test=True) sample_z = np.random.uniform(-1, 1, size=(batch_size , dcgan.z_dim)) if config.dataset == 'mnist' and config.use_labels: samples = sess.run(dcgan.sampler, feed_dict={dcgan.z: sample_z, dcgan.img: sample_img, dcgan.y: sample_labels}) else: samples = sess.run(dcgan.sampler, feed_dict={dcgan.z: sample_z, dcgan.img: sample_img }) col_img = colour_samples(samples, config.dataset, dcgan.img_height) col_input = colour_originals(sample_inputs, config.dataset) merged = np.concatenate((samples[:,:(dcgan.output_height-dcgan.img_height),:,:], \ sample_inputs[:,(dcgan.output_height-dcgan.img_height):,:,:]),1) col_merged = colour_samples(merged, config.dataset, dcgan.img_height) if config.dataset == 'mnist': save_both(col_img, col_input, image_frame_dim, ('test_v6_compare_%s' % (idx))) save_images(col_merged, [image_frame_dim, image_frame_dim, 3], './samples/test_v6_merged_samples_%s.png' % (idx)) else: save_both(samples, sample_inputs, image_frame_dim, ('test_v6_compare_%s' % (idx))) save_images(merged, [image_frame_dim, image_frame_dim, 3], './samples/test_v6_merged_samples_%s.png' % (idx)) elif option == 7: #Save 4x4(6x6) image of merged samples (not coloured). batch_size = config.batch_size for idx in xrange(min(8,int(np.floor(1000/batch_size)))): print(" [*] %d" % idx) sample_inputs, sample_img, sample_labels = get_img(dcgan, idx*batch_size, batch_size, config.dataset, test=True) sample_z = np.random.uniform(-1, 1, size=(batch_size , dcgan.z_dim)) if config.dataset == 'mnist' and config.use_labels: samples = sess.run(dcgan.sampler, feed_dict={dcgan.z: sample_z, dcgan.img: sample_img, dcgan.y: sample_labels}) else: samples = sess.run(dcgan.sampler, feed_dict={dcgan.z: sample_z, dcgan.img: sample_img }) merged = np.concatenate((samples[:,:(dcgan.output_height-dcgan.img_height),:,:], \ sample_inputs[:,(dcgan.output_height-dcgan.img_height):,:,:]),1) if config.dataset == 'mnist': merged_subset = merged[0:36] save_images(merged_subset, [6, 6, 3], './samples/test_v7_merged_samples_%s.png' % (idx)) else: merged_subset = merged[0:16] save_images(merged_subset, [4, 4, 3], './samples/test_v7_merged_samples_%s.png' % (idx)) elif option == 8: #different values of z. Version to avoid batch normalization effect if this causes troubles" batch_size = config.batch_size length = int(np.sqrt(config.batch_size)) sample_inputs0, sample_img0, sample_labels0 = get_img(dcgan, 0, batch_size, config.dataset, test=True) class_z = np.random.randint(2, size=dcgan.z_dim) values = np.linspace(-1., 1., num=length) z_values = np.empty((0,dcgan.z_dim)) for i in range(length): #create z for j in range(length): z_values = np.append(z_values, [class_z * values[i] + (1-class_z) * values[j]], axis=0) shuff = np.zeros((0,batch_size)) #2nd column: permutations of 0:63 for i in xrange(batch_size): x = np.arange(batch_size) random.shuffle(x) shuff = np.append(shuff, [x], axis=0).astype(int) all_samples = np.empty((batch_size,batch_size,dcgan.output_height,dcgan.output_width,dcgan.c_dim)) for idx in xrange(batch_size): #over all noice variations. print(" [*] %d" % idx) sample_inputs = sample_inputs0 sample_labels = sample_labels0 sample_img = sample_img0 sample_z = np.zeros((batch_size,dcgan.z_dim)) for i in range(batch_size): z = z_values[shuff[i,idx]] sample_z[i,:] = z if config.dataset == "mnist" and config.use_labels: samples = sess.run(dcgan.sampler, feed_dict={dcgan.z: sample_z, dcgan.img: sample_img, dcgan.y: sample_labels}) else: samples = sess.run(dcgan.sampler, feed_dict={dcgan.z: sample_z, dcgan.img: sample_img }) for i in range(batch_size): all_samples[i,shuff[i,idx],:,:,:] = np.copy(samples[i]) for idx in range(batch_size): samples = all_samples[idx,:,:,:,:] col_img = colour_samples(samples, config.dataset, dcgan.img_height) save_images(col_img, [image_frame_dim, image_frame_dim, 3], './samples/test_v8_diffz_%s.png' % (idx)) elif option == 9: #different values of z. batch_size = config.batch_size length = int(np.sqrt(config.batch_size)) sample_inputs0, sample_img0, sample_labels0 = get_img(dcgan, 0, batch_size, config.dataset, test=True) class_z = np.random.randint(2, size=dcgan.z_dim) values = np.linspace(-1., 1., num=length) z_values = np.empty((0,dcgan.z_dim)) for i in range(length): #create z for j in range(length): z_values = np.append(z_values, [class_z * values[i] + (1-class_z) * values[j]], axis=0) for idx in range(64): print(" [*] %d" % idx) sample_inputs = np.repeat([sample_inputs0[idx]], batch_size, axis=0) if config.dataset == 'mnist': sample_labels = np.repeat([sample_labels0[idx]], batch_size, axis=0) else: sample_labels = None sample_img = np.repeat([sample_img0[idx]], batch_size, axis=0) if config.dataset == "mnist" and config.use_labels: samples = sess.run(dcgan.sampler, feed_dict={dcgan.z: z_values, dcgan.img: sample_img, dcgan.y: sample_labels}) else: samples = sess.run(dcgan.sampler, feed_dict={dcgan.z: z_values, dcgan.img: sample_img }) col_img = colour_samples(samples, config.dataset, dcgan.img_height) save_images(col_img, [image_frame_dim, image_frame_dim, 3], './samples/test_v9_diffz_%s.png' % (idx)) elif option == 10: #Take pictures from samples_progress and put them into one file. for i in range(8): prog_pics_base = glob(os.path.join('./samples_progress','part{:1d}'.format(i+1), '*.jpg')) #prog_pics_base = glob(os.path.join('./samples_progress', '*.jpg')) imreadImg = imread(prog_pics_base[0]) prog_pics = [ get_image(prog_pic, input_height=dcgan.output_height, input_width=dcgan.output_height, resize_height=dcgan.output_height, resize_width=dcgan.output_width, crop=dcgan.crop, grayscale=dcgan.grayscale) for prog_pic in prog_pics_base] prog_pics_conv = np.array(prog_pics).astype(np.float32) print(prog_pics_conv.shape) out_pics = np.reshape(prog_pics_conv, (64,prog_pics_conv.shape[1],prog_pics_conv.shape[2],-1)) print(out_pics.shape) save_images(out_pics, [image_frame_dim, image_frame_dim], './samples_progress/progress{:1d}.png'.format(i+1)) elif option == 11: #Save pictures centered and aligned in ./data_aligned if True: #training data if not os.path.exists('data_aligned'): os.makedirs('data_aligned') nr_samples = len(dcgan.data) batch_size = config.batch_size print(nr_samples) print(batch_size) batch_idxs = nr_samples // batch_size for idx in range(batch_idxs): sample_inputs, _, _ = get_img(dcgan, idx*batch_size, batch_size, config.dataset, test=False) for i in range(batch_size): pic_idx = idx*batch_size + i save_images(sample_inputs[i:i+1:], [1,1], './data_aligned/al{:06d}.jpg'.format(pic_idx+1)) print("Done [%s] out of [%s]" % (idx,batch_idxs)) if True: #test data if not os.path.exists('data_test_aligned'): os.makedirs('data_test_aligned') nr_samples = 1000 sample_inputs, _, _ = get_img(dcgan, 0, nr_samples, config.dataset, test=True) for pic_idx in range(nr_samples): save_images(sample_inputs[pic_idx:pic_idx+1:], [1,1], './data_test_aligned/aligned{:03d}.jpg'.format(pic_idx+1)) def get_img(dcgan, start_idx, batch_size, dataset, test=True, type=''): if dataset == 'mnist': if test: sample_inputs = dcgan.data_X_test[start_idx:(start_idx+batch_size)] sample_labels = dcgan.data_y_test[start_idx:(start_idx+batch_size)] else: if type == 'gen': sample_inputs = dcgan.data_X_gen[start_idx:(start_idx+batch_size)] sample_labels = dcgan.data_y_gen[start_idx:(start_idx+batch_size)] elif type == 'dis': sample_inputs = dcgan.data_X_dis[start_idx:(start_idx+batch_size)] sample_labels = dcgan.data_y_dis[start_idx:(start_idx+batch_size)] else: sample_inputs = dcgan.data_X[start_idx:(start_idx+batch_size)] sample_labels = dcgan.data_y[start_idx:(start_idx+batch_size)] else: sample_labels = None if test: sample_files = dcgan.data_test[start_idx:(start_idx+batch_size)] else: if type == 'gen': sample_files = dcgan.data_gen[start_idx:(start_idx+batch_size)] elif type == 'dis': sample_files = dcgan.data_dis[start_idx:(start_idx+batch_size)] else: sample_files = dcgan.data[start_idx:(start_idx+batch_size)] sample = [ get_image(sample_file, input_height=dcgan.input_height, input_width=dcgan.input_width, resize_height=dcgan.output_height, resize_width=dcgan.output_width, crop=dcgan.crop, grayscale=dcgan.grayscale) for sample_file in sample_files] if (dcgan.grayscale): sample_inputs = np.array(sample).astype(np.float32)[:, :, :, None] else: sample_inputs = np.array(sample).astype(np.float32) sample_half_images = sample_inputs[:,(dcgan.output_height-dcgan.img_height):,:,:] sample_img = np.reshape(sample_half_images, (batch_size , dcgan.img_dim)) return sample_inputs, sample_img, sample_labels def colour_samples(samples, dataset, height): if dataset == "mnist": input_half = samples[:,(samples.shape[1]-height):,:,0] input_half_zeros = np.zeros_like(input_half) input_half_col = np.stack((input_half_zeros,input_half_zeros,input_half), -1) generated_half = samples[:,:(samples.shape[1]-height),:,0] #generated_half_zeros = np.zeros_like(generated_half) generated_half_col = np.stack((generated_half,generated_half,generated_half), -1) else: input_half = samples[:,(samples.shape[1]-height):,:,:] input_half_col = input_half * 0.5 generated_half = samples[:,:(samples.shape[1]-height),:,:] generated_half_col = generated_half col_img = np.concatenate((generated_half_col,input_half_col),1) return col_img def colour_originals(originals, dataset): if dataset == "mnist": originals_zeros = np.zeros_like(originals[:,:,:,0]) col_input = np.stack((originals_zeros,originals[:,:,:,0],originals_zeros), -1) else: col_input = originals return col_input def save_both(col_img, col_input, image_frame_dim, name): batch_size = col_img.shape[0] output = np.empty_like(col_img) output[::2] = col_img[:int(batch_size / 2):] output[1::2] = col_input[:int(batch_size / 2):] save_images(output, [image_frame_dim, image_frame_dim], './samples/' + name + 'a.png' ) #3? output[::2] = col_img[int(batch_size / 2)::] output[1::2] = col_input[int(batch_size / 2)::] save_images(output, [image_frame_dim, image_frame_dim, 3], './samples/' + name + 'b.png' ) def image_manifold_size(num_images): manifold_h = int(np.floor(np.sqrt(num_images))) manifold_w = int(np.ceil(np.sqrt(num_images))) assert manifold_h * manifold_w == num_images return manifold_h, manifold_w
[ "tensorflow.trainable_variables", "numpy.empty", "numpy.floor", "random.shuffle", "numpy.random.randint", "numpy.arange", "numpy.tile", "numpy.zeros_like", "random.randint", "numpy.copy", "numpy.empty_like", "os.path.exists", "numpy.append", "numpy.reshape", "numpy.linspace", "numpy.ra...
[((364, 386), 'pprint.PrettyPrinter', 'pprint.PrettyPrinter', ([], {}), '()\n', (384, 386), False, 'import pprint\n'), ((507, 531), 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), '()\n', (529, 531), True, 'import tensorflow as tf\n'), ((535, 596), 'tensorflow.contrib.slim.model_analyzer.analyze_vars', 'slim.model_analyzer.analyze_vars', (['model_vars'], {'print_info': '(True)'}), '(model_vars, print_info=True)\n', (567, 596), True, 'import tensorflow.contrib.slim as slim\n'), ((5382, 5426), 'moviepy.editor.VideoClip', 'mpy.VideoClip', (['make_frame'], {'duration': 'duration'}), '(make_frame, duration=duration)\n', (5395, 5426), True, 'import moviepy.editor as mpy\n'), ((19599, 19658), 'numpy.reshape', 'np.reshape', (['sample_half_images', '(batch_size, dcgan.img_dim)'], {}), '(sample_half_images, (batch_size, dcgan.img_dim))\n', (19609, 19658), True, 'import numpy as np\n'), ((20452, 20507), 'numpy.concatenate', 'np.concatenate', (['(generated_half_col, input_half_col)', '(1)'], {}), '((generated_half_col, input_half_col), 1)\n', (20466, 20507), True, 'import numpy as np\n'), ((20910, 20932), 'numpy.empty_like', 'np.empty_like', (['col_img'], {}), '(col_img)\n', (20923, 20932), True, 'import numpy as np\n'), ((1407, 1446), 'numpy.zeros', 'np.zeros', (['(h * size[0], w * size[1], c)'], {}), '((h * size[0], w * size[1], c))\n', (1415, 1446), True, 'import numpy as np\n'), ((5554, 5589), 'math.ceil', 'math.ceil', (['(config.batch_size ** 0.5)'], {}), '(config.batch_size ** 0.5)\n', (5563, 5589), False, 'import math\n'), ((5623, 5690), 'numpy.random.uniform', 'np.random.uniform', (['(-0.5)', '(0.5)'], {'size': '(config.batch_size, dcgan.z_dim)'}), '(-0.5, 0.5, size=(config.batch_size, dcgan.z_dim))\n', (5640, 5690), True, 'import numpy as np\n'), ((19888, 19913), 'numpy.zeros_like', 'np.zeros_like', (['input_half'], {}), '(input_half)\n', (19901, 19913), True, 'import numpy as np\n'), ((19936, 19998), 'numpy.stack', 'np.stack', (['(input_half_zeros, input_half_zeros, input_half)', '(-1)'], {}), '((input_half_zeros, input_half_zeros, input_half), -1)\n', (19944, 19998), True, 'import numpy as np\n'), ((20152, 20214), 'numpy.stack', 'np.stack', (['(generated_half, generated_half, generated_half)', '(-1)'], {}), '((generated_half, generated_half, generated_half), -1)\n', (20160, 20214), True, 'import numpy as np\n'), ((20624, 20660), 'numpy.zeros_like', 'np.zeros_like', (['originals[:, :, :, 0]'], {}), '(originals[:, :, :, 0])\n', (20637, 20660), True, 'import numpy as np\n'), ((20675, 20746), 'numpy.stack', 'np.stack', (['(originals_zeros, originals[:, :, :, 0], originals_zeros)', '(-1)'], {}), '((originals_zeros, originals[:, :, :, 0], originals_zeros), -1)\n', (20683, 20746), True, 'import numpy as np\n'), ((1651, 1687), 'numpy.zeros', 'np.zeros', (['(h * size[0], w * size[1])'], {}), '((h * size[0], w * size[1]))\n', (1659, 1687), True, 'import numpy as np\n'), ((2758, 2781), 'numpy.array', 'np.array', (['cropped_image'], {}), '(cropped_image)\n', (2766, 2781), True, 'import numpy as np\n'), ((5925, 5965), 'numpy.arange', 'np.arange', (['(0)', '(1)', '(1.0 / config.batch_size)'], {}), '(0, 1, 1.0 / config.batch_size)\n', (5934, 5965), True, 'import numpy as np\n'), ((5979, 5998), 'six.moves.xrange', 'xrange', (['dcgan.z_dim'], {}), '(dcgan.z_dim)\n', (5985, 5998), False, 'from six.moves import xrange\n'), ((21405, 21424), 'numpy.sqrt', 'np.sqrt', (['num_images'], {}), '(num_images)\n', (21412, 21424), True, 'import numpy as np\n'), ((21455, 21474), 'numpy.sqrt', 'np.sqrt', (['num_images'], {}), '(num_images)\n', (21462, 21474), True, 'import numpy as np\n'), ((6048, 6111), 'numpy.random.uniform', 'np.random.uniform', (['(-1)', '(1)'], {'size': '(config.batch_size, dcgan.z_dim)'}), '(-1, 1, size=(config.batch_size, dcgan.z_dim))\n', (6065, 6111), True, 'import numpy as np\n'), ((6712, 6752), 'numpy.arange', 'np.arange', (['(0)', '(1)', '(1.0 / config.batch_size)'], {}), '(0, 1, 1.0 / config.batch_size)\n', (6721, 6752), True, 'import numpy as np\n'), ((5879, 5887), 'time.gmtime', 'gmtime', ([], {}), '()\n', (5885, 5887), False, 'from time import gmtime, strftime\n'), ((6237, 6276), 'numpy.random.choice', 'np.random.choice', (['(10)', 'config.batch_size'], {}), '(10, config.batch_size)\n', (6253, 6276), True, 'import numpy as np\n'), ((6298, 6331), 'numpy.zeros', 'np.zeros', (['(config.batch_size, 10)'], {}), '((config.batch_size, 10))\n', (6306, 6331), True, 'import numpy as np\n'), ((6767, 6801), 'random.randint', 'random.randint', (['(0)', '(dcgan.z_dim - 1)'], {}), '(0, dcgan.z_dim - 1)\n', (6781, 6801), False, 'import random\n'), ((6874, 6920), 'numpy.random.uniform', 'np.random.uniform', (['(-0.2)', '(0.2)'], {'size': 'dcgan.z_dim'}), '(-0.2, 0.2, size=dcgan.z_dim)\n', (6891, 6920), True, 'import numpy as np\n'), ((6941, 6975), 'numpy.tile', 'np.tile', (['z', '(config.batch_size, 1)'], {}), '(z, (config.batch_size, 1))\n', (6948, 6975), True, 'import numpy as np\n'), ((7757, 7797), 'numpy.arange', 'np.arange', (['(0)', '(1)', '(1.0 / config.batch_size)'], {}), '(0, 1, 1.0 / config.batch_size)\n', (7766, 7797), True, 'import numpy as np\n'), ((7811, 7830), 'six.moves.xrange', 'xrange', (['dcgan.z_dim'], {}), '(dcgan.z_dim)\n', (7817, 7830), False, 'from six.moves import xrange\n'), ((19450, 19466), 'numpy.array', 'np.array', (['sample'], {}), '(sample)\n', (19458, 19466), True, 'import numpy as np\n'), ((6811, 6830), 'six.moves.xrange', 'xrange', (['dcgan.z_dim'], {}), '(dcgan.z_dim)\n', (6817, 6830), False, 'from six.moves import xrange\n'), ((7162, 7201), 'numpy.random.choice', 'np.random.choice', (['(10)', 'config.batch_size'], {}), '(10, config.batch_size)\n', (7178, 7201), True, 'import numpy as np\n'), ((7223, 7256), 'numpy.zeros', 'np.zeros', (['(config.batch_size, 10)'], {}), '((config.batch_size, 10))\n', (7231, 7256), True, 'import numpy as np\n'), ((7880, 7922), 'numpy.zeros', 'np.zeros', (['[config.batch_size, dcgan.z_dim]'], {}), '([config.batch_size, dcgan.z_dim])\n', (7888, 7922), True, 'import numpy as np\n'), ((8186, 8226), 'numpy.arange', 'np.arange', (['(0)', '(1)', '(1.0 / config.batch_size)'], {}), '(0, 1, 1.0 / config.batch_size)\n', (8195, 8226), True, 'import numpy as np\n'), ((8242, 8261), 'six.moves.xrange', 'xrange', (['dcgan.z_dim'], {}), '(dcgan.z_dim)\n', (8248, 8261), False, 'from six.moves import xrange\n'), ((19361, 19377), 'numpy.array', 'np.array', (['sample'], {}), '(sample)\n', (19369, 19377), True, 'import numpy as np\n'), ((6351, 6379), 'numpy.arange', 'np.arange', (['config.batch_size'], {}), '(config.batch_size)\n', (6360, 6379), True, 'import numpy as np\n'), ((8311, 8353), 'numpy.zeros', 'np.zeros', (['[config.batch_size, dcgan.z_dim]'], {}), '([config.batch_size, dcgan.z_dim])\n', (8319, 8353), True, 'import numpy as np\n'), ((7276, 7304), 'numpy.arange', 'np.arange', (['config.batch_size'], {}), '(config.batch_size)\n', (7285, 7304), True, 'import numpy as np\n'), ((8597, 8644), 'numpy.array', 'np.array', (['[images[idx] for images in image_set]'], {}), '([images[idx] for images in image_set])\n', (8605, 8644), True, 'import numpy as np\n'), ((9236, 9292), 'numpy.random.uniform', 'np.random.uniform', (['(-1)', '(1)'], {'size': '(batch_size, dcgan.z_dim)'}), '(-1, 1, size=(batch_size, dcgan.z_dim))\n', (9253, 9292), True, 'import numpy as np\n'), ((9761, 9908), 'numpy.concatenate', 'np.concatenate', (['(samples[:, :dcgan.output_height - dcgan.img_height, :, :], sample_inputs[:,\n dcgan.output_height - dcgan.img_height:, :, :])', '(1)'], {}), '((samples[:, :dcgan.output_height - dcgan.img_height, :, :],\n sample_inputs[:, dcgan.output_height - dcgan.img_height:, :, :]), 1)\n', (9775, 9908), True, 'import numpy as np\n'), ((10856, 10912), 'numpy.random.uniform', 'np.random.uniform', (['(-1)', '(1)'], {'size': '(batch_size, dcgan.z_dim)'}), '(-1, 1, size=(batch_size, dcgan.z_dim))\n', (10873, 10912), True, 'import numpy as np\n'), ((11231, 11378), 'numpy.concatenate', 'np.concatenate', (['(samples[:, :dcgan.output_height - dcgan.img_height, :, :], sample_inputs[:,\n dcgan.output_height - dcgan.img_height:, :, :])', '(1)'], {}), '((samples[:, :dcgan.output_height - dcgan.img_height, :, :],\n sample_inputs[:, dcgan.output_height - dcgan.img_height:, :, :]), 1)\n', (11245, 11378), True, 'import numpy as np\n'), ((12092, 12130), 'numpy.random.randint', 'np.random.randint', (['(2)'], {'size': 'dcgan.z_dim'}), '(2, size=dcgan.z_dim)\n', (12109, 12130), True, 'import numpy as np\n'), ((12145, 12179), 'numpy.linspace', 'np.linspace', (['(-1.0)', '(1.0)'], {'num': 'length'}), '(-1.0, 1.0, num=length)\n', (12156, 12179), True, 'import numpy as np\n'), ((12194, 12220), 'numpy.empty', 'np.empty', (['(0, dcgan.z_dim)'], {}), '((0, dcgan.z_dim))\n', (12202, 12220), True, 'import numpy as np\n'), ((12414, 12439), 'numpy.zeros', 'np.zeros', (['(0, batch_size)'], {}), '((0, batch_size))\n', (12422, 12439), True, 'import numpy as np\n'), ((12487, 12505), 'six.moves.xrange', 'xrange', (['batch_size'], {}), '(batch_size)\n', (12493, 12505), False, 'from six.moves import xrange\n'), ((12647, 12739), 'numpy.empty', 'np.empty', (['(batch_size, batch_size, dcgan.output_height, dcgan.output_width, dcgan.c_dim)'], {}), '((batch_size, batch_size, dcgan.output_height, dcgan.output_width,\n dcgan.c_dim))\n', (12655, 12739), True, 'import numpy as np\n'), ((12754, 12772), 'six.moves.xrange', 'xrange', (['batch_size'], {}), '(batch_size)\n', (12760, 12772), False, 'from six.moves import xrange\n'), ((7711, 7719), 'time.gmtime', 'gmtime', ([], {}), '()\n', (7717, 7719), False, 'from time import gmtime, strftime\n'), ((9028, 9055), 'numpy.floor', 'np.floor', (['(1000 / batch_size)'], {}), '(1000 / batch_size)\n', (9036, 9055), True, 'import numpy as np\n'), ((11929, 11955), 'numpy.sqrt', 'np.sqrt', (['config.batch_size'], {}), '(config.batch_size)\n', (11936, 11955), True, 'import numpy as np\n'), ((12518, 12539), 'numpy.arange', 'np.arange', (['batch_size'], {}), '(batch_size)\n', (12527, 12539), True, 'import numpy as np\n'), ((12547, 12564), 'random.shuffle', 'random.shuffle', (['x'], {}), '(x)\n', (12561, 12564), False, 'import random\n'), ((12979, 13014), 'numpy.zeros', 'np.zeros', (['(batch_size, dcgan.z_dim)'], {}), '((batch_size, dcgan.z_dim))\n', (12987, 13014), True, 'import numpy as np\n'), ((14104, 14142), 'numpy.random.randint', 'np.random.randint', (['(2)'], {'size': 'dcgan.z_dim'}), '(2, size=dcgan.z_dim)\n', (14121, 14142), True, 'import numpy as np\n'), ((14157, 14191), 'numpy.linspace', 'np.linspace', (['(-1.0)', '(1.0)'], {'num': 'length'}), '(-1.0, 1.0, num=length)\n', (14168, 14191), True, 'import numpy as np\n'), ((14206, 14232), 'numpy.empty', 'np.empty', (['(0, dcgan.z_dim)'], {}), '((0, dcgan.z_dim))\n', (14214, 14232), True, 'import numpy as np\n'), ((10648, 10675), 'numpy.floor', 'np.floor', (['(1000 / batch_size)'], {}), '(1000 / batch_size)\n', (10656, 10675), True, 'import numpy as np\n'), ((12318, 12396), 'numpy.append', 'np.append', (['z_values', '[class_z * values[i] + (1 - class_z) * values[j]]'], {'axis': '(0)'}), '(z_values, [class_z * values[i] + (1 - class_z) * values[j]], axis=0)\n', (12327, 12396), True, 'import numpy as np\n'), ((13525, 13544), 'numpy.copy', 'np.copy', (['samples[i]'], {}), '(samples[i])\n', (13532, 13544), True, 'import numpy as np\n'), ((13941, 13967), 'numpy.sqrt', 'np.sqrt', (['config.batch_size'], {}), '(config.batch_size)\n', (13948, 13967), True, 'import numpy as np\n'), ((14499, 14551), 'numpy.repeat', 'np.repeat', (['[sample_inputs0[idx]]', 'batch_size'], {'axis': '(0)'}), '([sample_inputs0[idx]], batch_size, axis=0)\n', (14508, 14551), True, 'import numpy as np\n'), ((14730, 14779), 'numpy.repeat', 'np.repeat', (['[sample_img0[idx]]', 'batch_size'], {'axis': '(0)'}), '([sample_img0[idx]], batch_size, axis=0)\n', (14739, 14779), True, 'import numpy as np\n'), ((12580, 12609), 'numpy.append', 'np.append', (['shuff', '[x]'], {'axis': '(0)'}), '(shuff, [x], axis=0)\n', (12589, 12609), True, 'import numpy as np\n'), ((14330, 14408), 'numpy.append', 'np.append', (['z_values', '[class_z * values[i] + (1 - class_z) * values[j]]'], {'axis': '(0)'}), '(z_values, [class_z * values[i] + (1 - class_z) * values[j]], axis=0)\n', (14339, 14408), True, 'import numpy as np\n'), ((14614, 14666), 'numpy.repeat', 'np.repeat', (['[sample_labels0[idx]]', 'batch_size'], {'axis': '(0)'}), '([sample_labels0[idx]], batch_size, axis=0)\n', (14623, 14666), True, 'import numpy as np\n'), ((16178, 16269), 'numpy.reshape', 'np.reshape', (['prog_pics_conv', '(64, prog_pics_conv.shape[1], prog_pics_conv.shape[2], -1)'], {}), '(prog_pics_conv, (64, prog_pics_conv.shape[1], prog_pics_conv.\n shape[2], -1))\n', (16188, 16269), True, 'import numpy as np\n'), ((16067, 16086), 'numpy.array', 'np.array', (['prog_pics'], {}), '(prog_pics)\n', (16075, 16086), True, 'import numpy as np\n'), ((16557, 16587), 'os.path.exists', 'os.path.exists', (['"""data_aligned"""'], {}), "('data_aligned')\n", (16571, 16587), False, 'import os\n'), ((16598, 16625), 'os.makedirs', 'os.makedirs', (['"""data_aligned"""'], {}), "('data_aligned')\n", (16609, 16625), False, 'import os\n'), ((17267, 17302), 'os.path.exists', 'os.path.exists', (['"""data_test_aligned"""'], {}), "('data_test_aligned')\n", (17281, 17302), False, 'import os\n'), ((17313, 17345), 'os.makedirs', 'os.makedirs', (['"""data_test_aligned"""'], {}), "('data_test_aligned')\n", (17324, 17345), False, 'import os\n')]
#!/usr/bin/env python # written by <NAME>, last edited 1/9/2021 # supervised by Prof. <NAME> # inspiration from M Del Ben et al., Physical Review B 99, 125128 (2019) # this program takes an inverse epsilon matrix, .h5 format, and writes an inverse epsilon matrix # simplified by the static subspace approximation (SSA) in the same plane wave basis as the original import numpy as np import h5py def matx_truncate(matx, qpt, N_g, vcoul, eig_thresh=0.0, nfreq=1): # does SSA on a rank 3 matrix for a specific q-point with a given eigenvalue threshhold. # matx is the N_qpt x N_freq x N_G x N_G matrix from epsmat.h5 of eps^-1_GG' for all qpoints sampled # qpt is the index of the qpt in question # N_g comes from f['eps_header']['gspace']['nmtx'] # vcoul comes from f['eps_header']['gspace']['vcoul'] # eig_thresh is the eigenvalue threshhold for SSA (if negative, it is the frac. of eigenvalues to keep) # nfreq is the number of frequencies to do SSA on for each qpoint; defaults to all of them # eventual output, eps_inv is a list of length n_freq of N_G x N_G matrices for the qpoint in question # eps_inv[n] is the N_G x N_G matrix for the nth frequency at qpoint qpt eps_inv = [] # helpful later v_G = np.diag(vcoul[qpt, :N_g]) v_G_inv = np.diag(1. / vcoul[qpt, :N_g]) v_G_sqrt = np.diag(np.sqrt(vcoul[qpt, :N_g])) v_G_sqrt_inv = np.diag(1. / np.sqrt(vcoul[qpt, :N_g])) # calculate chi0 from eps, from Del Ben equation 5 # 0 in matx[i,0] is the ID of the relevant frequency # we transpose matx[i,0] because del Ben and BGW use different conventions chi0_GG = v_G_inv @ (-np.linalg.inv(matx[qpt,0][:N_g,:N_g].conj().T) + np.identity(N_g)) ############################# # working with symmetrized matrix now # we now calculate the symmetrized matrix form of v*chi, chi0_bar, which has same eigfuncs. as epsilon. # Del Ben equation 9 chi0_bar = v_G_sqrt @ chi0_GG @ v_G_sqrt # decompose this symmetrized v*chi: these are the eigenvals used to truncate basis # argsort used to sort eigvals by size, making it easy to truncate them: Del Ben eqn 10 lambda_q, C_q = np.linalg.eigh(-chi0_bar) idx = lambda_q.argsort()[::-1] lambda_q = lambda_q[idx] C_q = C_q[:,idx] # get truncated eigenbasis for eps (since -vX0 has same eigvals as eps and eps^-1) if eig_thresh > lambda_q[-1]: trunc_num = np.argmax(lambda_q < eig_thresh) print(f'keeping largest {trunc_num} of {len(C_q)} eigenvectors') Cs_q = C_q[:,:np.argmax(lambda_q < eig_thresh)] # if eig_thresh negative, truncate by fraction of eigenvectors to keep rather than threshhold elif 0 > eig_thresh >= -1: trunc_num = int(-eig_thresh*len(C_q)) print(f'keeping the {trunc_num} of {len(C_q)} eigenvectors with eigvals. > {lambda_q[trunc_num]:.2}') Cs_q = C_q[:,:trunc_num] else: # if eig_thresh is 0 or otherwise smaller than smallest eigenvalue of vX0, don't truncate print(f'keeping all {len(C_q)} of {len(C_q)} eigenvectors') Cs_q = C_q # remember N_g = mat_size, this is size of the subspace N_b = len(Cs_q[0]) # we've constructed the subspace with frequency omega = 0 # now we project matrices for all the frequencies, 0 included, onto the subspace for freq in range(nfreq): if freq != 0: # combination of Del Ben eqns.5 and 9 chi0_bar = v_G_sqrt_inv @ (-np.linalg.inv(matx[qpt,freq][:N_g,:N_g].conj().T) + np.identity(N_g)) @ v_G_sqrt # projecting chi onto truncated basis: Del Ben eqns 11 and 12 chi0s_bar = Cs_q.conj().T @ chi0_bar @ Cs_q # now obtain eps_s_bar in static eigenvector basis, in text of Del Ben after eqn 12 eps_s_bar = np.identity(N_b) - chi0s_bar eps_inv_s_bar = np.linalg.inv(eps_s_bar) # invert eps_s numerically, transform back to plane wave basis eps_inv_s = Cs_q @ (eps_inv_s_bar - np.identity(N_b)) @ Cs_q.conj().T + np.identity(N_g) # finally, eps_inv unsymmetrized is obtained # Del Ben in text after equation 12 # (note that eps_inv is transposed back now) eps_inv.append((v_G_sqrt @ eps_inv_s @ v_G_sqrt_inv).conj().T) return eps_inv if __name__=='__main__': import sys if len(sys.argv) != 3: print("Usage: trunc-eigs.py filename.h5 eig_thresh") print("eig_thresh between 0 and -1 interpreted as fraction of eigenvectors to retain") sys.exit() eig_thresh = float(sys.argv[2]) if eig_thresh > 0: print("interpreting eig_thresh as a threshhold") print(f"writing to log file trunc-eigs-{eig_thresh}.out") log_file = open(f"trunc-eigs-{eig_thresh}.out","w") elif eig_thresh == 0.00: print("not truncating: will return an output identical to the input") print(f"writing to log file trunc-eigs-{eig_thresh}.out") log_file = open(f"trunc-eigs-{eig_thresh}.out","w") elif eig_thresh > -1: print("interpreting eig_thresh as a fraction of eigenvalues to keep") print(f"writing to log file trunc-eigs-frac-{-eig_thresh}.out") log_file = open(f"trunc-eigs-frac-{-eig_thresh}.out","w") else: print("unacceptable eig_thresh:") print("eigh_thresh > 0 interpreted as threshhold, -1 < eig_thresh < 0 interpreted as fraction") sys.exit() old_stdout = sys.stdout sys.stdout = log_file # Open old aqnd new epsmat files and copy header info print(f"opening {sys.argv[1]}...\n") f_in = sys.argv[1] f = h5py.File(f_in , 'r') print(f"there are {f['eps_header/qpoints/nq'][()]} q-points with matrices for {f['eps_header/freqs/nfreq'][()]} frequencies each") # qpts: list of qpts stored in f['mats']['matrix'] qpts = f['eps_header']['qpoints']['qpts'] # matx: allows GG' matrix for qpoint qpt_id to be called as matx[qpt_id, freq] matx = f['mats']['matrix'][:,0,:,:,:,0] # handling complex matrix type: if f['eps_header/flavor'][()] == 2: matx = matx + 1j*f['mats']['matrix'][:,0,:,:,:,1] # mat_size: mat_size[qpt_id] gives size of matx[qpt_id], as all eps^-1_GG'(q) # have the same shape (n x n), but some have empty rows at the end mat_sizes = f['eps_header']['gspace']['nmtx'] # vcoul: vcoul[qpt_id, i] is an array corresponding to v(qpt_id + component[i]), or v(q+G) vcoul = f['eps_header']['gspace']['vcoul'] ########################### # creating and naming the output .h5 file if eig_thresh >= 0: eps_new = h5py.File(f'{f_in[:-3]}_trunc-{eig_thresh}.h5','w') else: eps_new = h5py.File(f'{f_in[:-3]}_trunc-frac-{-eig_thresh}.h5','w') eps_new.copy(f['eps_header'],'eps_header') eps_new.copy(f['mf_header'],'mf_header') eps_new.copy(f['mats'],'mats') # loop over the q-points and write new truncated eps^-1 with matx_truncate print("calculating eps^-1 in truncated basis...\n") for i, qpt in enumerate(qpts): print(f"working on q-point #{i+1}, {qpt}") N_g = mat_sizes[i] N_freq = f['eps_header/freqs/nfreq'][()] eps_q = matx_truncate(matx, i, N_g, vcoul, eig_thresh, N_freq) diag = np.diagonal(eps_q[0]) eps_new['mats/matrix-diagonal'][i,:N_g,0] = diag.real #this should be almost identically zero: eps_new['mats/matrix-diagonal'][i,:N_g,1] = diag.imag # this is a loop over the frequencies associated w that kpoint inside eps_q for freq in range(N_freq): eps_new['mats/matrix'][i,0,freq,:N_g,:N_g,0] = eps_q[freq].real if f['eps_header/flavor'][()] == 2: eps_new['mats/matrix'][i,0,freq,:N_g,:N_g,1] = eps_q[freq].imag print() eps_new.close() print("=="*10 + "\njob done") sys.stdout = old_stdout log_file.close() print("truncation finished") print()
[ "h5py.File", "numpy.argmax", "numpy.identity", "numpy.linalg.eigh", "numpy.diagonal", "numpy.linalg.inv", "numpy.diag", "sys.exit", "numpy.sqrt" ]
[((1290, 1315), 'numpy.diag', 'np.diag', (['vcoul[qpt, :N_g]'], {}), '(vcoul[qpt, :N_g])\n', (1297, 1315), True, 'import numpy as np\n'), ((1331, 1362), 'numpy.diag', 'np.diag', (['(1.0 / vcoul[qpt, :N_g])'], {}), '(1.0 / vcoul[qpt, :N_g])\n', (1338, 1362), True, 'import numpy as np\n'), ((2228, 2253), 'numpy.linalg.eigh', 'np.linalg.eigh', (['(-chi0_bar)'], {}), '(-chi0_bar)\n', (2242, 2253), True, 'import numpy as np\n'), ((5788, 5808), 'h5py.File', 'h5py.File', (['f_in', '"""r"""'], {}), "(f_in, 'r')\n", (5797, 5808), False, 'import h5py\n'), ((1386, 1411), 'numpy.sqrt', 'np.sqrt', (['vcoul[qpt, :N_g]'], {}), '(vcoul[qpt, :N_g])\n', (1393, 1411), True, 'import numpy as np\n'), ((2488, 2520), 'numpy.argmax', 'np.argmax', (['(lambda_q < eig_thresh)'], {}), '(lambda_q < eig_thresh)\n', (2497, 2520), True, 'import numpy as np\n'), ((3947, 3971), 'numpy.linalg.inv', 'np.linalg.inv', (['eps_s_bar'], {}), '(eps_s_bar)\n', (3960, 3971), True, 'import numpy as np\n'), ((4642, 4652), 'sys.exit', 'sys.exit', ([], {}), '()\n', (4650, 4652), False, 'import sys\n'), ((6809, 6861), 'h5py.File', 'h5py.File', (['f"""{f_in[:-3]}_trunc-{eig_thresh}.h5"""', '"""w"""'], {}), "(f'{f_in[:-3]}_trunc-{eig_thresh}.h5', 'w')\n", (6818, 6861), False, 'import h5py\n'), ((6891, 6949), 'h5py.File', 'h5py.File', (['f"""{f_in[:-3]}_trunc-frac-{-eig_thresh}.h5"""', '"""w"""'], {}), "(f'{f_in[:-3]}_trunc-frac-{-eig_thresh}.h5', 'w')\n", (6900, 6949), False, 'import h5py\n'), ((7474, 7495), 'numpy.diagonal', 'np.diagonal', (['eps_q[0]'], {}), '(eps_q[0])\n', (7485, 7495), True, 'import numpy as np\n'), ((1446, 1471), 'numpy.sqrt', 'np.sqrt', (['vcoul[qpt, :N_g]'], {}), '(vcoul[qpt, :N_g])\n', (1453, 1471), True, 'import numpy as np\n'), ((1745, 1761), 'numpy.identity', 'np.identity', (['N_g'], {}), '(N_g)\n', (1756, 1761), True, 'import numpy as np\n'), ((3893, 3909), 'numpy.identity', 'np.identity', (['N_b'], {}), '(N_b)\n', (3904, 3909), True, 'import numpy as np\n'), ((4125, 4141), 'numpy.identity', 'np.identity', (['N_g'], {}), '(N_g)\n', (4136, 4141), True, 'import numpy as np\n'), ((5579, 5589), 'sys.exit', 'sys.exit', ([], {}), '()\n', (5587, 5589), False, 'import sys\n'), ((2618, 2650), 'numpy.argmax', 'np.argmax', (['(lambda_q < eig_thresh)'], {}), '(lambda_q < eig_thresh)\n', (2627, 2650), True, 'import numpy as np\n'), ((3610, 3626), 'numpy.identity', 'np.identity', (['N_g'], {}), '(N_g)\n', (3621, 3626), True, 'import numpy as np\n'), ((4089, 4105), 'numpy.identity', 'np.identity', (['N_b'], {}), '(N_b)\n', (4100, 4105), True, 'import numpy as np\n')]
from __future__ import (absolute_import, division, print_function, unicode_literals) import numpy as np import pandas as pd from nose.tools import assert_true from ggplot import * from ggplot.components.colors import assign_continuous_colors, \ assign_discrete_colors from ggplot.tests import cleanup @cleanup def test_assign_colors(): """ Test how colors are assigned to different column types. """ df = pd.DataFrame({"values": np.arange(10), "int_col": np.arange(10), "num_col": np.arange(10) / 2, "bool_col": np.random.randn(10) > 0, "char_col": ["a", "b"] * 5}) color_mapping_col = ':::color_mapping:::' fill_mapping_col = ':::fill_mapping:::' # test integer column color_col = "int_col" gg_int = ggplot(df, aes(x="values", y="values", color="int_col")) gg_int += geom_point() gg_int.draw() new_data, _ = assign_continuous_colors(df, gg_int, 'color', color_col) expected_cols = new_data[color_mapping_col] actual_cols = gg_int.data[color_mapping_col] assert_true((actual_cols == expected_cols).all()) # test numeric column color_col = "num_col" gg_num = ggplot(df, aes(x="values", y="values", color="num_col")) gg_num += geom_point() gg_num.draw() new_data, _ = assign_continuous_colors(df, gg_int, 'color', color_col) expected_cols = new_data[color_mapping_col] actual_cols = gg_num.data[color_mapping_col] assert_true((actual_cols == expected_cols).all()) # test bool column color_col = "bool_col" gg_bool = ggplot(df, aes(x="values", y="values", color="bool_col")) gg_bool += geom_point() gg_bool.draw() new_data, _ = assign_discrete_colors(df, gg_bool, 'color', color_col) expected_cols = new_data[color_mapping_col] actual_cols = gg_bool.data[color_mapping_col] assert_true((actual_cols == expected_cols).all()) # test char column color_col = "char_col" gg_char = ggplot(df, aes(x="values", y="values", color="char_col")) gg_char += geom_point() gg_char.draw() new_data, _ = assign_discrete_colors(df, gg_bool, 'color', color_col) expected_cols = new_data[color_mapping_col] actual_cols = gg_char.data[color_mapping_col] assert_true((actual_cols == expected_cols).all()) # Fill mapping # test integer column fill_col = "int_col" gg_int = ggplot(df, aes(x="values", y="values", fill="int_col")) gg_int += geom_point() gg_int.draw() new_data, _ = assign_continuous_colors(df, gg_int, 'fill', fill_col) expected_cols = new_data[fill_mapping_col] actual_cols = gg_int.data[fill_mapping_col] assert_true((actual_cols == expected_cols).all()) # test numeric column fill_col = "num_col" gg_num = ggplot(df, aes(x="values", y="values", fill="num_col")) gg_num += geom_point() gg_num.draw() new_data, _ = assign_continuous_colors(df, gg_int, 'fill', fill_col) expected_cols = new_data[fill_mapping_col] actual_cols = gg_num.data[fill_mapping_col] assert_true((actual_cols == expected_cols).all()) # test bool column fill_col = "bool_col" gg_bool = ggplot(df, aes(x="values", y="values", fill="bool_col")) gg_bool += geom_point() gg_bool.draw() new_data, _ = assign_discrete_colors(df, gg_bool, 'fill', fill_col) expected_cols = new_data[fill_mapping_col] actual_cols = gg_bool.data[fill_mapping_col] assert_true((actual_cols == expected_cols).all()) # test char column fill_col = "char_col" gg_char = ggplot(df, aes(x="values", y="values", fill="char_col")) gg_char += geom_point() gg_char.draw() new_data, _ = assign_discrete_colors(df, gg_bool, 'fill', fill_col) expected_cols = new_data[fill_mapping_col] actual_cols = gg_char.data[fill_mapping_col] assert_true((actual_cols == expected_cols).all())
[ "ggplot.components.colors.assign_continuous_colors", "numpy.random.randn", "numpy.arange", "ggplot.components.colors.assign_discrete_colors" ]
[((1019, 1075), 'ggplot.components.colors.assign_continuous_colors', 'assign_continuous_colors', (['df', 'gg_int', '"""color"""', 'color_col'], {}), "(df, gg_int, 'color', color_col)\n", (1043, 1075), False, 'from ggplot.components.colors import assign_continuous_colors, assign_discrete_colors\n'), ((1425, 1481), 'ggplot.components.colors.assign_continuous_colors', 'assign_continuous_colors', (['df', 'gg_int', '"""color"""', 'color_col'], {}), "(df, gg_int, 'color', color_col)\n", (1449, 1481), False, 'from ggplot.components.colors import assign_continuous_colors, assign_discrete_colors\n'), ((1833, 1888), 'ggplot.components.colors.assign_discrete_colors', 'assign_discrete_colors', (['df', 'gg_bool', '"""color"""', 'color_col'], {}), "(df, gg_bool, 'color', color_col)\n", (1855, 1888), False, 'from ggplot.components.colors import assign_continuous_colors, assign_discrete_colors\n'), ((2241, 2296), 'ggplot.components.colors.assign_discrete_colors', 'assign_discrete_colors', (['df', 'gg_bool', '"""color"""', 'color_col'], {}), "(df, gg_bool, 'color', color_col)\n", (2263, 2296), False, 'from ggplot.components.colors import assign_continuous_colors, assign_discrete_colors\n'), ((2667, 2721), 'ggplot.components.colors.assign_continuous_colors', 'assign_continuous_colors', (['df', 'gg_int', '"""fill"""', 'fill_col'], {}), "(df, gg_int, 'fill', fill_col)\n", (2691, 2721), False, 'from ggplot.components.colors import assign_continuous_colors, assign_discrete_colors\n'), ((3067, 3121), 'ggplot.components.colors.assign_continuous_colors', 'assign_continuous_colors', (['df', 'gg_int', '"""fill"""', 'fill_col'], {}), "(df, gg_int, 'fill', fill_col)\n", (3091, 3121), False, 'from ggplot.components.colors import assign_continuous_colors, assign_discrete_colors\n'), ((3469, 3522), 'ggplot.components.colors.assign_discrete_colors', 'assign_discrete_colors', (['df', 'gg_bool', '"""fill"""', 'fill_col'], {}), "(df, gg_bool, 'fill', fill_col)\n", (3491, 3522), False, 'from ggplot.components.colors import assign_continuous_colors, assign_discrete_colors\n'), ((3871, 3924), 'ggplot.components.colors.assign_discrete_colors', 'assign_discrete_colors', (['df', 'gg_bool', '"""fill"""', 'fill_col'], {}), "(df, gg_bool, 'fill', fill_col)\n", (3893, 3924), False, 'from ggplot.components.colors import assign_continuous_colors, assign_discrete_colors\n'), ((497, 510), 'numpy.arange', 'np.arange', (['(10)'], {}), '(10)\n', (506, 510), True, 'import numpy as np\n'), ((547, 560), 'numpy.arange', 'np.arange', (['(10)'], {}), '(10)\n', (556, 560), True, 'import numpy as np\n'), ((597, 610), 'numpy.arange', 'np.arange', (['(10)'], {}), '(10)\n', (606, 610), True, 'import numpy as np\n'), ((652, 671), 'numpy.random.randn', 'np.random.randn', (['(10)'], {}), '(10)\n', (667, 671), True, 'import numpy as np\n')]
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the VQE program.""" from test import QiskitNatureTestCase import unittest import warnings from ddt import ddt, data import numpy as np from qiskit.providers.basicaer import QasmSimulatorPy from qiskit.algorithms import VQEResult from qiskit.algorithms.optimizers import SPSA from qiskit.circuit.library import RealAmplitudes from qiskit.opflow import I, Z from qiskit_nature.algorithms.ground_state_solvers import GroundStateEigensolver from qiskit_nature.converters.second_quantization import QubitConverter from qiskit_nature.mappers.second_quantization import JordanWignerMapper from qiskit_nature.runtime import VQEClient, VQEProgram, VQERuntimeResult, VQEProgramResult from .fake_vqeruntime import FakeRuntimeProvider @ddt class TestVQEClient(QiskitNatureTestCase): """Test the VQE program.""" def get_standard_program(self, use_deprecated=False): """Get a standard VQEClient and operator to find the ground state of.""" circuit = RealAmplitudes(3) operator = Z ^ I ^ Z initial_point = np.random.random(circuit.num_parameters) backend = QasmSimulatorPy() if use_deprecated: vqe_cls = VQEProgram provider = FakeRuntimeProvider(use_deprecated=True) warnings.filterwarnings("ignore", category=DeprecationWarning) else: provider = FakeRuntimeProvider(use_deprecated=False) vqe_cls = VQEClient vqe = vqe_cls( ansatz=circuit, optimizer=SPSA(), initial_point=initial_point, backend=backend, provider=provider, ) if use_deprecated: warnings.filterwarnings("always", category=DeprecationWarning) return vqe, operator @data({"name": "SPSA", "maxiter": 100}, SPSA(maxiter=100)) def test_standard_case(self, optimizer): """Test a standard use case.""" for use_deprecated in [False, True]: vqe, operator = self.get_standard_program(use_deprecated=use_deprecated) vqe.optimizer = optimizer result = vqe.compute_minimum_eigenvalue(operator) self.assertIsInstance(result, VQEResult) self.assertIsInstance(result, VQEProgramResult if use_deprecated else VQERuntimeResult) def test_supports_aux_ops(self): """Test the VQEClient says it supports aux operators.""" for use_deprecated in [False, True]: vqe, _ = self.get_standard_program(use_deprecated=use_deprecated) self.assertTrue(vqe.supports_aux_operators) def test_return_groundstate(self): """Test the VQEClient yields a ground state solver that returns the ground state.""" for use_deprecated in [False, True]: vqe, _ = self.get_standard_program(use_deprecated=use_deprecated) qubit_converter = QubitConverter(JordanWignerMapper()) gss = GroundStateEigensolver(qubit_converter, vqe) self.assertTrue(gss.returns_groundstate) if __name__ == "__main__": unittest.main()
[ "unittest.main", "qiskit.algorithms.optimizers.SPSA", "qiskit.providers.basicaer.QasmSimulatorPy", "warnings.filterwarnings", "numpy.random.random", "qiskit_nature.algorithms.ground_state_solvers.GroundStateEigensolver", "qiskit.circuit.library.RealAmplitudes", "qiskit_nature.mappers.second_quantizati...
[((3525, 3540), 'unittest.main', 'unittest.main', ([], {}), '()\n', (3538, 3540), False, 'import unittest\n'), ((1453, 1470), 'qiskit.circuit.library.RealAmplitudes', 'RealAmplitudes', (['(3)'], {}), '(3)\n', (1467, 1470), False, 'from qiskit.circuit.library import RealAmplitudes\n'), ((1524, 1564), 'numpy.random.random', 'np.random.random', (['circuit.num_parameters'], {}), '(circuit.num_parameters)\n', (1540, 1564), True, 'import numpy as np\n'), ((1583, 1600), 'qiskit.providers.basicaer.QasmSimulatorPy', 'QasmSimulatorPy', ([], {}), '()\n', (1598, 1600), False, 'from qiskit.providers.basicaer import QasmSimulatorPy\n'), ((2283, 2300), 'qiskit.algorithms.optimizers.SPSA', 'SPSA', ([], {'maxiter': '(100)'}), '(maxiter=100)\n', (2287, 2300), False, 'from qiskit.algorithms.optimizers import SPSA\n'), ((1738, 1800), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'category': 'DeprecationWarning'}), "('ignore', category=DeprecationWarning)\n", (1761, 1800), False, 'import warnings\n'), ((2145, 2207), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""always"""'], {'category': 'DeprecationWarning'}), "('always', category=DeprecationWarning)\n", (2168, 2207), False, 'import warnings\n'), ((3394, 3438), 'qiskit_nature.algorithms.ground_state_solvers.GroundStateEigensolver', 'GroundStateEigensolver', (['qubit_converter', 'vqe'], {}), '(qubit_converter, vqe)\n', (3416, 3438), False, 'from qiskit_nature.algorithms.ground_state_solvers import GroundStateEigensolver\n'), ((1986, 1992), 'qiskit.algorithms.optimizers.SPSA', 'SPSA', ([], {}), '()\n', (1990, 1992), False, 'from qiskit.algorithms.optimizers import SPSA\n'), ((3354, 3374), 'qiskit_nature.mappers.second_quantization.JordanWignerMapper', 'JordanWignerMapper', ([], {}), '()\n', (3372, 3374), False, 'from qiskit_nature.mappers.second_quantization import JordanWignerMapper\n')]
from typing import Any, List, Union, Optional, cast from warnings import warn import numpy as np import pandas as pd from numpy.fft import rfftfreq from scipy.interpolate import interp1d import base64 def find_nearest_val(array: Union[List[float], np.ndarray], value: float) -> float: """ Find the nearest value in an array. Helpful for indexing spectra at a specific wavelength. :param Union[List[float],np.ndarray] array: list or array of floats to search :param float value: value that you wish to find :return float: entry in array that is nearest to value """ if not isinstance(array, (np.ndarray, list)): raise TypeError("array must be a np.ndarray or list") if isinstance(array, list): array = np.asarray(array) array = cast(np.ndarray, array) idx = (np.abs(array - value)).argmin() return float(array[idx]) def find_nearest_idx(array: Union[List[float], np.ndarray], value: float) -> int: """ Find the index of the nearest value in an array. Helpful for indexing spectra at a specific wavelength. :param Union[List[float], np.ndarray] array: list or array of floats to search :param float value: value that you wish to find :return int: index of entry in array that is nearest to value """ if not isinstance(array, (np.ndarray, list)): raise TypeError("array must be a np.ndarray or list") if isinstance(array, list): array = np.asarray(array) array = cast(np.ndarray, array) idx = int((np.abs(array - value)).argmin()) return idx def generate_wavelength_template( start_wavelength: float, end_wavelength: float, resolution: float, res_sampling: float, truncate: bool = False, ) -> np.ndarray: """ Generate wavelength array with fixed resolution and wavelength sampling. :param float start_wavelength: minimum wavelength of spectra to include :param float end_wavelength: maximum wavelength of spectra to include :param float resolution: resolving power of instrument (R = lambda / delta lambda) :param float res_sampling: pixels per resolution element :param bool truncate: If true, drop final pixel for which lambda > end_wavelength :return np.ndarray: wavelength grid of given resolution between start and end wavelengths """ # ToDo: Incorporate wavelength dependent sampling/resolution if not all( isinstance(i, (int, float)) for i in [start_wavelength, end_wavelength, resolution, res_sampling] ): raise TypeError("Input quantities must be int or float") if not all( i > 0 for i in [start_wavelength, end_wavelength, resolution, res_sampling] ): raise ValueError("Input quantities must be > 0") if start_wavelength > end_wavelength: raise ValueError("start_wavelength greater than end_wavelength") wavelength_tmp = [start_wavelength] wavelength_now = start_wavelength while wavelength_now < end_wavelength: wavelength_now += wavelength_now / (resolution * res_sampling) wavelength_tmp.append(wavelength_now) wavelength_template = np.array(wavelength_tmp) if truncate: wavelength_template = wavelength_template[:-1] return wavelength_template def doppler_shift( wave: np.ndarray, spec: np.ndarray, rv: float, bounds_warning: bool = True ) -> Union[np.ndarray, Any]: """ Apply doppler shift to spectra and resample onto original wavelength grid Warning: This function does not gracefully handle spectral regions with rest-frame wavelengths outside of the wavelength range. Presently, these are set to np.nan. :param np.ndarray wave: input wavelength array :param np.ndarray spec: input spectra array :param float rv: Radial Velocity (km/s) :param bool bounds_warning: warn about boundary issues? :return Union[np.ndarray,Any]: Doppler shifted spectra array """ if not all(isinstance(i, np.ndarray) for i in [wave, spec]): raise TypeError("wave and spec must be np.ndarray") if not isinstance(rv, (int, float)): raise TypeError("rv must be an int or float") if not np.all(np.diff(wave) > 0): raise ValueError("wave must be sorted") if rv < 0: raise ValueError("rv must be > 0") c = 2.99792458e5 # km/s doppler_factor = np.sqrt((1 - rv / c) / (1 + rv / c)) new_wavelength = wave * doppler_factor shifted_spec = np.interp(new_wavelength, wave, spec) shifted_spec[(wave < new_wavelength.min()) | (wave > new_wavelength.max())] = np.nan if bounds_warning: if rv > 0: warn( f"Spectra for wavelengths below {new_wavelength.min()} are undefined; set to np.nan", UserWarning, ) if rv < 0: warn( f"Spectra for wavelengths above {new_wavelength.max()} are undefined; set to np.nan", UserWarning, ) return shifted_spec def convolve_spec( wave: np.ndarray, spec: np.ndarray, resolution: float, outwave: np.ndarray, res_in: Optional[float] = None, ) -> Union[np.ndarray, Any]: """ Convolves spectrum to lower resolution and samples onto a new wavelength grid :param np.ndarray wave: input wavelength array :param np.ndarray spec: input spectra array (may be 1 or 2 dimensional) :param float resolution: Resolving power to convolve down to (R = lambda / delta lambda) :param np.ndarray outwave: wavelength grid to sample onto :param Optional[float] res_in: Resolving power of input spectra :return Union[np.ndarray,Any]: convolved spectra array """ # ToDo: Enable convolution with Gaussian LSF with wavelength-dependent width. # ToDo: Enable convolution with arbitrary LSF if not all(isinstance(i, np.ndarray) for i in [wave, spec, outwave]): raise TypeError("wave, spec, and outwave must be np.ndarray") if not isinstance(resolution, (int, float)): raise TypeError("resolution must be an int or float") if spec.ndim == 1: if spec.shape[0] != wave.shape[0]: raise ValueError("spec and wave must be the same length") elif spec.ndim == 2: if spec.shape[1] != wave.shape[0]: raise ValueError("spec and wave must be the same length") if not (wave.min() < outwave.min() and wave.max() > outwave.max()): warn( f"outwave ({outwave.min(), outwave.max()}) extends beyond input wave ({wave.min(), wave.max()})", UserWarning, ) if not np.all(np.diff(wave) > 0): raise ValueError("wave must be sorted") if not np.all(np.diff(outwave) > 0): raise ValueError("outwave must be sorted") sigma_to_fwhm = 2.355 width = resolution * sigma_to_fwhm sigma_out = (resolution * sigma_to_fwhm) ** -1 if res_in is None: sigma_in = 0.0 else: if not isinstance(res_in, (int, float)): raise TypeError("res_in must be an int or float") if res_in < resolution: raise ValueError("Cannot convolve to a higher resolution") sigma_in = (res_in * sigma_to_fwhm) ** -1 # Trim Wavelength Range nsigma_pad = 20.0 wlim = np.array([outwave.min(), outwave.max()]) wlim *= 1 + nsigma_pad / width * np.array([-1, 1]) mask = (wave > wlim[0]) & (wave < wlim[1]) wave = wave[mask] if spec.ndim == 1: spec = spec[mask] elif spec.ndim == 2: spec = spec[:, mask] else: raise ValueError("spec cannot have more than 2 dimensions") # Make Convolution Grid wmin, wmax = wave.min(), wave.max() nwave = wave.shape[0] nwave_new = int(2 ** (np.ceil(np.log2(nwave)))) lnwave_new = np.linspace(np.log(wmin), np.log(wmax), nwave_new) wave_new = np.exp(lnwave_new) fspec = interp1d(wave, spec, bounds_error=False, fill_value="extrapolate") spec = fspec(wave_new) wave = wave_new # Convolve via FFT sigma = np.sqrt(sigma_out ** 2 - sigma_in ** 2) invres_grid = np.diff(np.log(wave)) dx = np.median(invres_grid) ss = rfftfreq(nwave_new, d=dx) taper = np.exp(-2 * (np.pi ** 2) * (sigma ** 2) * (ss ** 2)) spec_ff = np.fft.rfft(spec) ff_tapered = spec_ff * taper spec_conv = np.fft.irfft(ff_tapered) # Interpolate onto outwave fspec = interp1d(wave, spec_conv, bounds_error=False, fill_value="extrapolate") return fspec(outwave) def calc_gradient( spectra: np.ndarray, labels: pd.DataFrame, symmetric: bool = True, ref_included: bool = True, ) -> pd.DataFrame: """ Calculates partial derivatives of spectra with respect to each label :param np.ndarray spectra: input spectra array :param pd.DataFrame labels: input label array :param bool symmetric: If true, calculates symmetric gradient about reference :param bool ref_included: Is spectra[0] the reference spectrum? :return pd.DataFrame: Partial derivatives of spectra wrt each label """ # ToDo: Add option to automatically determine structure of the spectrum dataframe from the label dataframe. if not isinstance(spectra, np.ndarray): raise TypeError("spectra must be np.ndarray") if not isinstance(labels, pd.DataFrame): raise TypeError("labels must be pd.DataFrame") nspectra = spectra.shape[0] nlabels = labels.shape[0] if ref_included: skip = 1 else: skip = 0 if symmetric: if nspectra - skip != 2 * nlabels: raise ValueError( f"nspectra({nspectra-skip}) != 2*nlabel({2*nlabels})" + "\nCannot perform symmetric gradient calculation" ) dx = np.diag( labels.iloc[:, skip::2].values - labels.iloc[:, (skip + 1) :: 2].values ).copy() grad = spectra[skip::2] - spectra[(skip + 1) :: 2] else: if not ref_included: raise ValueError( f"Reference Spectra must be included at index 0 " + "to calculate asymmetric gradients" ) if nspectra - 1 == nlabels: dx = np.diag(labels.iloc[:, 0].values - labels.iloc[:, 1:].values).copy() grad = spectra[0] - spectra[1:] elif nspectra - 1 == 2 * nlabels: dx = np.diag(labels.iloc[:, 0].values - labels.iloc[:, 1::2].values).copy() grad = spectra[0] - spectra[1::2] else: raise ValueError( f"nspectra({nspectra - 1}) != nlabel({nlabels}) " + f"or 2*nlabel({2 * nlabels})" + "\nCannot perform asymmetric gradient calculation" ) dx[labels.index == "Teff"] /= 100 # Scaling dX_Teff dx[labels.index == "rv"] /= 10 dx[dx == 0] = -np.inf return pd.DataFrame(grad / dx[:, np.newaxis], index=labels.index) def kpc_to_mu( d: Union[float, List[float], np.ndarray] ) -> Union[np.float64, np.ndarray, Any]: """ Converts kpc to distance modulus :param Union[float,List[float],np.ndarray] d: distance in kpc :return Union[np.float64, np.ndarray, Any]: distance modulus """ if not isinstance(d, (int, float, np.ndarray, list)): raise TypeError("d must be int, float, or np.ndarray/list of floats") if isinstance(d, list): d = np.array(d) d = cast(np.ndarray, d) if np.any(d <= 0): raise ValueError("d must be > 0") return 5 * np.log10(d * 1e3 / 10) def mu_to_kpc( mu: Union[float, List[float], np.ndarray] ) -> Union[float, np.float64, np.ndarray]: """ Converts distance modulus to kpc :param Union[float,List[float],np.ndarray] mu: distance modulus :return Union[float, np.float64, np.ndarray]: distance in kpc """ if not isinstance(mu, (int, float, np.ndarray, list)): raise TypeError("mu must be int, float, or np.ndarray/list of floats") if isinstance(mu, list): mu = np.array(mu) mu = cast(np.ndarray, mu) return 1 / (1e3 / 10) * 10 ** (mu / 5) def decode_base64_dict(data): """ Decode a base64 encoded array into a NumPy array. Lifted from bokeh.serialization :param dict data: encoded array data to decode. Data should have the format encoded by :func:`encode_base64_dict`. :return np.ndarray: decoded numpy array """ b64 = base64.b64decode(data["__ndarray__"]) array = np.copy(np.frombuffer(b64, dtype=data["dtype"])) if len(data["shape"]) > 1: array = array.reshape(data["shape"]) return array
[ "numpy.fft.rfft", "numpy.abs", "typing.cast", "base64.b64decode", "numpy.exp", "numpy.interp", "scipy.interpolate.interp1d", "numpy.diag", "pandas.DataFrame", "numpy.fft.irfft", "numpy.log10", "numpy.median", "numpy.frombuffer", "numpy.asarray", "numpy.log2", "numpy.fft.rfftfreq", "n...
[((3141, 3165), 'numpy.array', 'np.array', (['wavelength_tmp'], {}), '(wavelength_tmp)\n', (3149, 3165), True, 'import numpy as np\n'), ((4349, 4385), 'numpy.sqrt', 'np.sqrt', (['((1 - rv / c) / (1 + rv / c))'], {}), '((1 - rv / c) / (1 + rv / c))\n', (4356, 4385), True, 'import numpy as np\n'), ((4448, 4485), 'numpy.interp', 'np.interp', (['new_wavelength', 'wave', 'spec'], {}), '(new_wavelength, wave, spec)\n', (4457, 4485), True, 'import numpy as np\n'), ((7817, 7835), 'numpy.exp', 'np.exp', (['lnwave_new'], {}), '(lnwave_new)\n', (7823, 7835), True, 'import numpy as np\n'), ((7848, 7914), 'scipy.interpolate.interp1d', 'interp1d', (['wave', 'spec'], {'bounds_error': '(False)', 'fill_value': '"""extrapolate"""'}), "(wave, spec, bounds_error=False, fill_value='extrapolate')\n", (7856, 7914), False, 'from scipy.interpolate import interp1d\n'), ((7998, 8037), 'numpy.sqrt', 'np.sqrt', (['(sigma_out ** 2 - sigma_in ** 2)'], {}), '(sigma_out ** 2 - sigma_in ** 2)\n', (8005, 8037), True, 'import numpy as np\n'), ((8087, 8109), 'numpy.median', 'np.median', (['invres_grid'], {}), '(invres_grid)\n', (8096, 8109), True, 'import numpy as np\n'), ((8119, 8144), 'numpy.fft.rfftfreq', 'rfftfreq', (['nwave_new'], {'d': 'dx'}), '(nwave_new, d=dx)\n', (8127, 8144), False, 'from numpy.fft import rfftfreq\n'), ((8157, 8203), 'numpy.exp', 'np.exp', (['(-2 * np.pi ** 2 * sigma ** 2 * ss ** 2)'], {}), '(-2 * np.pi ** 2 * sigma ** 2 * ss ** 2)\n', (8163, 8203), True, 'import numpy as np\n'), ((8224, 8241), 'numpy.fft.rfft', 'np.fft.rfft', (['spec'], {}), '(spec)\n', (8235, 8241), True, 'import numpy as np\n'), ((8291, 8315), 'numpy.fft.irfft', 'np.fft.irfft', (['ff_tapered'], {}), '(ff_tapered)\n', (8303, 8315), True, 'import numpy as np\n'), ((8360, 8431), 'scipy.interpolate.interp1d', 'interp1d', (['wave', 'spec_conv'], {'bounds_error': '(False)', 'fill_value': '"""extrapolate"""'}), "(wave, spec_conv, bounds_error=False, fill_value='extrapolate')\n", (8368, 8431), False, 'from scipy.interpolate import interp1d\n'), ((10798, 10856), 'pandas.DataFrame', 'pd.DataFrame', (['(grad / dx[:, np.newaxis])'], {'index': 'labels.index'}), '(grad / dx[:, np.newaxis], index=labels.index)\n', (10810, 10856), True, 'import pandas as pd\n'), ((11372, 11386), 'numpy.any', 'np.any', (['(d <= 0)'], {}), '(d <= 0)\n', (11378, 11386), True, 'import numpy as np\n'), ((12340, 12377), 'base64.b64decode', 'base64.b64decode', (["data['__ndarray__']"], {}), "(data['__ndarray__'])\n", (12356, 12377), False, 'import base64\n'), ((752, 769), 'numpy.asarray', 'np.asarray', (['array'], {}), '(array)\n', (762, 769), True, 'import numpy as np\n'), ((786, 809), 'typing.cast', 'cast', (['np.ndarray', 'array'], {}), '(np.ndarray, array)\n', (790, 809), False, 'from typing import Any, List, Union, Optional, cast\n'), ((1452, 1469), 'numpy.asarray', 'np.asarray', (['array'], {}), '(array)\n', (1462, 1469), True, 'import numpy as np\n'), ((1486, 1509), 'typing.cast', 'cast', (['np.ndarray', 'array'], {}), '(np.ndarray, array)\n', (1490, 1509), False, 'from typing import Any, List, Union, Optional, cast\n'), ((7763, 7775), 'numpy.log', 'np.log', (['wmin'], {}), '(wmin)\n', (7769, 7775), True, 'import numpy as np\n'), ((7777, 7789), 'numpy.log', 'np.log', (['wmax'], {}), '(wmax)\n', (7783, 7789), True, 'import numpy as np\n'), ((8064, 8076), 'numpy.log', 'np.log', (['wave'], {}), '(wave)\n', (8070, 8076), True, 'import numpy as np\n'), ((11321, 11332), 'numpy.array', 'np.array', (['d'], {}), '(d)\n', (11329, 11332), True, 'import numpy as np\n'), ((11345, 11364), 'typing.cast', 'cast', (['np.ndarray', 'd'], {}), '(np.ndarray, d)\n', (11349, 11364), False, 'from typing import Any, List, Union, Optional, cast\n'), ((11445, 11470), 'numpy.log10', 'np.log10', (['(d * 1000.0 / 10)'], {}), '(d * 1000.0 / 10)\n', (11453, 11470), True, 'import numpy as np\n'), ((11942, 11954), 'numpy.array', 'np.array', (['mu'], {}), '(mu)\n', (11950, 11954), True, 'import numpy as np\n'), ((11968, 11988), 'typing.cast', 'cast', (['np.ndarray', 'mu'], {}), '(np.ndarray, mu)\n', (11972, 11988), False, 'from typing import Any, List, Union, Optional, cast\n'), ((12398, 12437), 'numpy.frombuffer', 'np.frombuffer', (['b64'], {'dtype': "data['dtype']"}), "(b64, dtype=data['dtype'])\n", (12411, 12437), True, 'import numpy as np\n'), ((821, 842), 'numpy.abs', 'np.abs', (['(array - value)'], {}), '(array - value)\n', (827, 842), True, 'import numpy as np\n'), ((7319, 7336), 'numpy.array', 'np.array', (['[-1, 1]'], {}), '([-1, 1])\n', (7327, 7336), True, 'import numpy as np\n'), ((1525, 1546), 'numpy.abs', 'np.abs', (['(array - value)'], {}), '(array - value)\n', (1531, 1546), True, 'import numpy as np\n'), ((4173, 4186), 'numpy.diff', 'np.diff', (['wave'], {}), '(wave)\n', (4180, 4186), True, 'import numpy as np\n'), ((6582, 6595), 'numpy.diff', 'np.diff', (['wave'], {}), '(wave)\n', (6589, 6595), True, 'import numpy as np\n'), ((6668, 6684), 'numpy.diff', 'np.diff', (['outwave'], {}), '(outwave)\n', (6675, 6684), True, 'import numpy as np\n'), ((7716, 7730), 'numpy.log2', 'np.log2', (['nwave'], {}), '(nwave)\n', (7723, 7730), True, 'import numpy as np\n'), ((9714, 9790), 'numpy.diag', 'np.diag', (['(labels.iloc[:, skip::2].values - labels.iloc[:, skip + 1::2].values)'], {}), '(labels.iloc[:, skip::2].values - labels.iloc[:, skip + 1::2].values)\n', (9721, 9790), True, 'import numpy as np\n'), ((10139, 10200), 'numpy.diag', 'np.diag', (['(labels.iloc[:, 0].values - labels.iloc[:, 1:].values)'], {}), '(labels.iloc[:, 0].values - labels.iloc[:, 1:].values)\n', (10146, 10200), True, 'import numpy as np\n'), ((10311, 10374), 'numpy.diag', 'np.diag', (['(labels.iloc[:, 0].values - labels.iloc[:, 1::2].values)'], {}), '(labels.iloc[:, 0].values - labels.iloc[:, 1::2].values)\n', (10318, 10374), True, 'import numpy as np\n')]
from .policies import hard_limit, greedy_epsilon, choose_randomly from .policies import _get_max_dict_val import operator from copy import deepcopy from gym.spaces.box import Box, Space import numpy as np import random from .discretizers import Discretizer, Box_Discretizer def policy_changed(dict1, dict2): ''' Compares to state-action dictionaries {state:{action:value estimate}} and returns True if the greedy policy is the same, that is, the same action will be returned based on the argmax of state-value estimates. Returns false if either dictionary is missing a state that exists in the other. Takes: dict1 and dict2, both {state:{action:estimate}} Returns: True/False''' if set(dict1.keys()) != set(dict2.keys()): return False else: for s in dict1.keys(): if _get_max_dict_val(dict1[s]) == _get_max_dict_val(dict2[s]): pass else: return False return True # define Python user-defined exceptions class Error(Exception): """Base class for other exceptions""" pass class PolicyConvergedError(Exception): '''Raised when a policy has converged, typically after some amount of patience''' pass class superAgent(): '''superAgent provides the basic methods and properties that all (or at least many) agents will require. All agents should be subclasses of the superAgent class. superAgent should not be used.''' def __init__(self): self.policy = None self.name = 'superclass' self.S_A_values = {} self.S_A_frequency = {} self.history = [] self.default_SA_estimate = 0 self.patience = None self.patience_counter = 0 self.policy_converged_flag = False self.past_S_A_values = deepcopy(self.S_A_values) self.discretizer = Discretizer() self.discrete = False self.actions = Space() self.seed = None def set_seed(self, seed): self.seed = seed random.seed(seed) np.random.seed(seed) def set_discretizer(self, discretizer): '''Set the discretizer used by the agent to convert a continuous state space intoo a discret state space.''' assert isinstance(discretizer, Discretizer) self.discrete = True self.discretizer = discretizer def discretize_space(self, space): '''Sends the space to the discretizer to be turned to discrete space. Takes: np.Array space object. Returns: np.Array of 'bin' in which conitniuous points fall..''' if not self.discrete: raise ValueError("The Agent is not expecting a discretized state space! Set a Discretizer.") return self.discretizer.discretize(space) def _follow_policy(self, state, actions, period, args={}): if self.policy is None: raise AssertionError("You must set a policy function before calling follow_policy.") if self.discrete: state = tuple(self.discretize_space(state)) return self.policy(state, actions, period, self.policy_args) def get_action(self, state, actions=None, period=0.25): ''' get_action is the base method agents use to take an action, given a state. This should probably be overridden by whatever the agent needs to do. Takes: a state space, an action space (NEEDS REMOVAL), and the length of the step in hours (NEEDS REMOVAL)''' return self._follow_policy(state, actions, period) def check_policy_convergence(self, increment_patience=True): '''Checks to see if the policy has converged, by comparing S_A_values and past_S_A_values. Raisies an assertion error if patience parameter hasn't been set. Raises a PolicyConvergedError if the policy has in fact converged for the patience set. Takes: Whether or not to increment hte policy convergence counter. Returns: None.''' # End early assert self.patience is not None if policy_changed(self.S_A_values, self.past_S_A_values): self.patience_counter += increment_patience else: self.patience_counter = int(increment_patience) if self.patience_counter > self.patience: raise PolicyConvergedError self.past_S_A_values = deepcopy(self.S_A_values) def set_greedy_policy(self, eta=0.2): '''Sets the greedy policy as the policy the agenet will follow, with epsilon given. ''' args = { 'eta': eta, 'state_action_values': self.S_A_values } self.set_policy(greedy_epsilon, args) def collect_reward(self, reward, state, action=None): # This takes a reward for a specific state or state-action pass def set_policy(self, policy, policy_args={}): self.policy = policy self.policy_args = policy_args def end_episode(self, reward=0): pass def observe_sars(self, state, action, reward, next_state): pass def initialize_state_actions(self, new_default=0, do_nothing_action=0, do_nothing_bonus=0): '''Initializes the S_A Tables for values and frequencies based on the states and actions known to the agent.''' if not isinstance(self.discretizer, Box_Discretizer): raise NotImplementedError("initializing state space is only set up for 1D Box state space") self.default_SA_estimate = new_default states = self.discretizer.list_all_states() np_actions = np.arange(self.actions.n) for s in states: s = tuple(s) for a in np_actions: self.S_A_values.setdefault(s, {})[a] = self.default_SA_estimate self.S_A_frequency.setdefault(s, {})[a] = 0 if do_nothing_action is not None and a == do_nothing_action: self.S_A_values[s][a] += do_nothing_bonus # Break ties in favor of do nothing class PrioritizedSweepingAgent(superAgent): def __init__(self, policy=choose_randomly, args={}, learning_rate = 0.1, patience=None, n_sweeps=5, sensitivity = 100): super().__init__() self.name = "Prioritized Sweeping Agent" self.set_policy(policy, args) self.learning_rate = learning_rate self.patience = patience self.P_queue = [] self.n_sweeps = n_sweeps self.sweep_depth = 150 self.sensitivity = sensitivity self.transition_table = np.array([]) self.reward_table = {} self.x_lookup = {} self.y_lookup = {} self.state_ix_lookup = {} self.state_list = [] def initialize_state_actions(self, default=0, do_nothing_action=0, do_nothing_bonus=0): '''Extends the base Agent classes initialize_state_actions to include details on the transition and reward model used by the algorithm''' super().initialize_state_actions(default, do_nothing_action, do_nothing_bonus) all_states = self.discretizer.list_all_states() all_states.append('terminal') self.state_list = all_states all_actions = np.arange(self.actions.n) all_sa = [(s, a) for a in all_actions for s in all_states] self.state_action_list = all_sa self.x_lookup = {(state, action): i for i, (state,action) in enumerate(all_sa)} self.y_lookup = {state: i for i, state in enumerate(all_states)} self.state_ix_lookup = {self.y_lookup[k]: k for k in self.y_lookup} self.sa_ix_lookup = {self.x_lookup[k]: k for k in self.x_lookup} self.transition_table = np.zeros((len(self.x_lookup), len(self.y_lookup))) self.reward_table = np.zeros(len(all_states)) def observe_sars(self, state, action, reward, next_state): def insert_p(P): if P > self.sensitivity: if self.P_queue == []: self.P_queue.append(((state, action), P)) else: for sa, P_sa in self.P_queue: if P > P_sa: self.P_queue.insert(self.P_queue.index((sa, P_sa)), ((state, action), P)) break # Discretize the space state = tuple(self.discretize_space(state)) if next_state == 'terminal': pass else: next_state = tuple(self.discretize_space(next_state)) # Update the state-action-state transition self.transition_table[self.x_lookup[(state, action)], self.y_lookup[next_state]] += 1 try: self.reward_table[(state, action, next_state)] += \ self.learning_rate * (reward - self.reward_table[state, action, next_state]) except KeyError: self.reward_table[(state, action, next_state)] = reward def get_greedy_value(state, default=np.nan): 'gets the greedy action value for the gien state' if state is not "terminal": greedy_next_action = _get_max_dict_val(self.S_A_values[state]) return self.S_A_values[state][greedy_next_action] else: return default # Get the change and priority of the change greedy_value = get_greedy_value(next_state, default=0) P = abs(reward + greedy_value - self.S_A_values[state][action]) insert_p(P) self.S_A_values[state][action] += \ self.learning_rate * (reward + greedy_value - self.S_A_values[state][action]) if abs(reward)>1000: print("end") # Do the planning step by emptying P_queue for i in range(self.n_sweeps): if self.P_queue == []: break (state, action), _ = self.P_queue.pop(0) #reward = self.reward_table[(state, action, ) STOPPED HERE, need to reconfigure so it correctly gets reward per hte new dict structure] reward = 0 p_sas = self.transition_table[self.x_lookup[(state, action)], :] # Choose randomly from the next states based on their probability of being visited but ignoring terminal p_sas = p_sas[:-1] / np.sum(p_sas[:-1]) greedy_value = np.sum([p_sas[ix] * get_greedy_value(self.state_ix_lookup[int(ix)]) for ix in np.nditer(np.nonzero(p_sas))]) if greedy_value != np.nan: self.S_A_values[state][action] += \ self.learning_rate * (reward + greedy_value - self.S_A_values[state][action]) lead_to_s = state greedy_next_action = _get_max_dict_val(self.S_A_values[lead_to_s]) # Next we choose N actions to chase back, to limit execution time, by choosing based on probability of ending up there likelihood = self.transition_table[:, self.y_lookup[lead_to_s]] \ / np.sum(self.transition_table[:, self.y_lookup[lead_to_s]]) nonzero = np.nonzero(self.transition_table[:, self.y_lookup[lead_to_s]])[0] if len(nonzero) <= self.sweep_depth: selection = nonzero else: selection = tuple(np.random.choice(np.arange(self.transition_table.shape[0]), size=self.sweep_depth, replace=False, p=likelihood)) for ix in selection: #sa_cnt = self.transition_table[ix, self.y_lookup[lead_to_s]] # Prioritize by taking top N only, randomply (state, action) = self.sa_ix_lookup[int(ix)] reward = self.reward_table[self.y_lookup[state]] P = abs(reward + self.S_A_values[lead_to_s][greedy_next_action] - self.S_A_values[state][action]) insert_p(P) def end_episode(self, reward=0): if self.patience is not None: try: super().check_policy_convergence() except PolicyConvergedError: self.policy_converged_flag = True class QAgent(superAgent): def __init__(self, policy=choose_randomly, args={}, epsilon = 0.1, alpha = 0.15, patience=None): super().__init__() self.name = "Q-Learning Agent" self.set_policy(policy, args) self.learning_rate = alpha self.patience=patience def get_action(self, state, actions, period): # This manages all aspects of the Q-learning algorithm including bootstrapping of the reward. # First, the last step is handled. # Then, the next action is selected. action = super()._follow_policy(state, actions, period) return action def end_episode(self, reward): # reset history self.history = [] # Check if the policy has converged if a patience has been set if self.patience is not None: super().check_policy_convergence() self.past_S_A_values = deepcopy(self.S_A_values.copy()) def observe_sars(self, state, action, reward, next_state): if (next_state == self.terminal_state).all(): greedy_action_estimate = 0 else: next_state = tuple(self.discretize_space(next_state)) greedy_action = _get_max_dict_val(self.S_A_values[next_state], self.default_SA_estimate) greedy_action_estimate = self.S_A_values[next_state][greedy_action] state = tuple(self.discretize_space(state)) self.S_A_values[state][action] += self.learning_rate*(reward + greedy_action_estimate - self.S_A_values[state][action]) self.history.append((state, action, reward)) class DynaQAgent(superAgent): def __init__(self, policy=choose_randomly, args={}, epsilon = 0.1, alpha = 0.15, patience=None, planning_steps=20): super().__init__() self.name = "DynaQ-Learning Agent" self.set_policy(policy, args) self.learning_rate = alpha self.patience=patience self.planning_steps = planning_steps self.transition_table = np.array([]) self.reward_table = {} self.x_lookup = {} self.y_lookup = {} self.state_ix_lookup = {} self.state_list = [] self.terminal_state = np.array([0,0,0,0]) print("remember to set self.actions = env.action_space!") def initialize_state_actions(self, new_default=0, do_nothing_action=0, do_nothing_bonus=0): '''Extends the base Agent classes initialize_state_actions to include details on the transition and reward model used by the algorithm''' super().initialize_state_actions(new_default, do_nothing_action, do_nothing_bonus) all_states = self.discretizer.list_all_states() all_states.append(self.terminal_state) all_states = [tuple(s) for s in all_states] self.state_list = all_states all_actions = np.arange(self.actions.n) all_sa = [(s, a) for a in all_actions for s in all_states] self.state_action_list = all_sa self.x_lookup = {(state, action): i for i, (state,action) in enumerate(all_sa)} self.y_lookup = {state: i for i, state in enumerate(all_states)} self.state_ix_lookup = {self.y_lookup[k]: k for k in self.y_lookup} self.sa_ix_lookup = {self.x_lookup[k]: k for k in self.x_lookup} self.transition_table = np.zeros((len(self.x_lookup), len(self.y_lookup))) self.reward_table = {} def get_action(self, state, actions, period): # This manages all aspects of the Q-learning algorithm including bootstrapping of the reward. # First, the last step is handled. # Then, the next action is selected. action = super()._follow_policy(state, actions, period) return action def end_episode(self, reward): # reset history self.history = [] # Check if the policy has converged if a patience has been set if self.patience is not None: super().check_policy_convergence() self.past_S_A_values = deepcopy(self.S_A_values.copy()) def observe_sars(self, state, action, reward, next_state): if (next_state == self.terminal_state).all(): greedy_action_estimate = 0 next_state = tuple(self.terminal_state) else: next_state = tuple(self.discretize_space(next_state)) greedy_action = _get_max_dict_val(self.S_A_values[next_state], self.default_SA_estimate) greedy_action_estimate = self.S_A_values[next_state][greedy_action] state = tuple(self.discretize_space(state)) self.S_A_values[state][action] += self.learning_rate*(reward + greedy_action_estimate - self.S_A_values[state][action]) self.history.append((state, action, reward)) # Update the Model # Update the state-action-state transition self.transition_table[self.x_lookup[(state, action)], self.y_lookup[next_state]] += 1 try: self.reward_table[(state, action, next_state)] += \ self.learning_rate * (reward - self.reward_table[state, action, next_state]) except KeyError: self.reward_table[(state, action, next_state)] = reward for sweeps in range(self.planning_steps): state = random.choice(list(self.S_A_values.keys())) action = random.choice(range(self.actions.n)) # Get next state predicted by the model: p_sas = self.transition_table[self.x_lookup[(state, action)], :] if np.sum(p_sas) == 0: continue # Choose randomly from the next states based on their probability of being visited but ignoring terminal p_sas = p_sas / np.sum(p_sas) try: next_state = self.state_ix_lookup[np.random.choice(range(p_sas.size), p=p_sas)] except ValueError: print("Skipping a sweep because of p_sas error!") print(p_sas) print("sum of p_sas={}".format(np.sum(p_sas))) print(self.transition_table[self.x_lookup[(state, action)], :]) continue if (next_state == self.terminal_state).all(): greedy_action_estimate = 0 else: greedy_action = _get_max_dict_val(self.S_A_values[next_state], self.default_SA_estimate) greedy_action_estimate = self.S_A_values[next_state][greedy_action] reward = self.reward_table[(state, action, next_state)] self.S_A_values[state][action] += self.learning_rate * (reward + greedy_action_estimate - self.S_A_values[state][action]) class ThresholdAgent(superAgent): def __init__(self, threshold): super().__init__() self.set_policy(hard_limit, {'target_demand': threshold}) self.name = 'ThresholdAgent' def get_action(self, state, actions, period): action = self._follow_policy(state, actions, period) return action class MonteCarloAgent(superAgent): def __init__(self, policy=choose_randomly, args={}): super().__init__() self.set_policy(policy, args) self.name = 'MonteCarloAgent' self.subtype = 'on-policy' self.C_S_A = {} self.learning_rate = args.get('learning_rate', None) self.terminal_state = np.array([0,0,0,0]) def get_action(self, state, actions, period): action = super()._follow_policy(state, actions, period) state = tuple(self.discretize_space(state)) return action def initialize_state_actions(self, new_default=0, do_nothing_action=None, do_nothing_bonus=1): self.default_SA_estimate = new_default super().initialize_state_actions(new_default, do_nothing_action, do_nothing_bonus) all_states = self.discretizer.list_all_states() all_states.append(self.terminal_state) self.state_list = all_states all_actions = np.arange(self.actions.n) all_sa = [(s, a) for a in all_actions for s in all_states] for s in all_states: s = tuple(s) for a in all_actions: self.S_A_values.setdefault(s, {})[a] = new_default self.C_S_A.setdefault(s, {})[a] = 0 self.S_A_frequency.setdefault(s, {})[a] = 0 if do_nothing_action is not None and a == do_nothing_action: self.S_A_values[s][a] += do_nothing_bonus # Break ties in favor of do nothing def observe_sars(self, state, action, reward, next_state): state = tuple(self.discretize_space(state)) self.history.append((state, action, reward)) self.S_A_frequency[state][action] += 1 def end_episode(self, reward): if self.subtype == 'on-policy': for s, a, r in list(set(self.history)): past_frequency = self.S_A_frequency.setdefault(s, {}).get(a, 0) past_value = self.S_A_values.setdefault(s, {}).get(a, reward) if self.learning_rate is None: self.S_A_values[s][a] = \ (self.S_A_values[s].get(a, 0)*past_frequency + reward) / (past_frequency + 1) else: self.S_A_values[s][a] = past_value + self.learning_rate * (reward - past_value) elif self.subtype == 'off-policy': G = 0 # assumes all reward at end of episode W = 1 for h in self.history[::-1]: s = h[0] a = h[1] r = h[2] G += r past_C = self.C_S_A.setdefault(s, {}).get(a, 0) self.C_S_A[s][a] += W past_value = self.S_A_values.setdefault(s, {}).get(a, self.default_SA_estimate) self.S_A_values[s][a] = past_value + W / self.C_S_A[s][a] * (G - past_value) if max(self.S_A_values[s].values()) != self.S_A_values[s][a]: print("breaking. Action {} not greedy at state {} given reward {}, S_A_values of {}".format(a, s, G, self.S_A_values[s])) break else: # We know we are taking the greedy action. so, we also know that probability b must be # 1-eta # We also know we are trying to determine the optimal policy so pi(At_St) = 1. eta = self.policy_args['eta'] b_S_A = 1-eta W *= 1 / b_S_A else: raise NotImplementedError("Only on-policy and off-policy subtypes are implemented.") if self.patience is not None: super().check_policy_convergence() self.past_S_A_values = deepcopy(self.S_A_values) self.history = []
[ "copy.deepcopy", "numpy.random.seed", "numpy.sum", "gym.spaces.box.Space", "numpy.nonzero", "random.seed", "numpy.arange", "numpy.array" ]
[((1792, 1817), 'copy.deepcopy', 'deepcopy', (['self.S_A_values'], {}), '(self.S_A_values)\n', (1800, 1817), False, 'from copy import deepcopy\n'), ((1912, 1919), 'gym.spaces.box.Space', 'Space', ([], {}), '()\n', (1917, 1919), False, 'from gym.spaces.box import Box, Space\n'), ((2009, 2026), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (2020, 2026), False, 'import random\n'), ((2035, 2055), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (2049, 2055), True, 'import numpy as np\n'), ((4318, 4343), 'copy.deepcopy', 'deepcopy', (['self.S_A_values'], {}), '(self.S_A_values)\n', (4326, 4343), False, 'from copy import deepcopy\n'), ((5532, 5557), 'numpy.arange', 'np.arange', (['self.actions.n'], {}), '(self.actions.n)\n', (5541, 5557), True, 'import numpy as np\n'), ((6480, 6492), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (6488, 6492), True, 'import numpy as np\n'), ((7130, 7155), 'numpy.arange', 'np.arange', (['self.actions.n'], {}), '(self.actions.n)\n', (7139, 7155), True, 'import numpy as np\n'), ((14132, 14144), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (14140, 14144), True, 'import numpy as np\n'), ((14323, 14345), 'numpy.array', 'np.array', (['[0, 0, 0, 0]'], {}), '([0, 0, 0, 0])\n', (14331, 14345), True, 'import numpy as np\n'), ((14967, 14992), 'numpy.arange', 'np.arange', (['self.actions.n'], {}), '(self.actions.n)\n', (14976, 14992), True, 'import numpy as np\n'), ((19561, 19583), 'numpy.array', 'np.array', (['[0, 0, 0, 0]'], {}), '([0, 0, 0, 0])\n', (19569, 19583), True, 'import numpy as np\n'), ((20172, 20197), 'numpy.arange', 'np.arange', (['self.actions.n'], {}), '(self.actions.n)\n', (20181, 20197), True, 'import numpy as np\n'), ((22933, 22958), 'copy.deepcopy', 'deepcopy', (['self.S_A_values'], {}), '(self.S_A_values)\n', (22941, 22958), False, 'from copy import deepcopy\n'), ((10163, 10181), 'numpy.sum', 'np.sum', (['p_sas[:-1]'], {}), '(p_sas[:-1])\n', (10169, 10181), True, 'import numpy as np\n'), ((10876, 10934), 'numpy.sum', 'np.sum', (['self.transition_table[:, self.y_lookup[lead_to_s]]'], {}), '(self.transition_table[:, self.y_lookup[lead_to_s]])\n', (10882, 10934), True, 'import numpy as np\n'), ((10957, 11019), 'numpy.nonzero', 'np.nonzero', (['self.transition_table[:, self.y_lookup[lead_to_s]]'], {}), '(self.transition_table[:, self.y_lookup[lead_to_s]])\n', (10967, 11019), True, 'import numpy as np\n'), ((17690, 17703), 'numpy.sum', 'np.sum', (['p_sas'], {}), '(p_sas)\n', (17696, 17703), True, 'import numpy as np\n'), ((17881, 17894), 'numpy.sum', 'np.sum', (['p_sas'], {}), '(p_sas)\n', (17887, 17894), True, 'import numpy as np\n'), ((11177, 11218), 'numpy.arange', 'np.arange', (['self.transition_table.shape[0]'], {}), '(self.transition_table.shape[0])\n', (11186, 11218), True, 'import numpy as np\n'), ((10298, 10315), 'numpy.nonzero', 'np.nonzero', (['p_sas'], {}), '(p_sas)\n', (10308, 10315), True, 'import numpy as np\n'), ((18181, 18194), 'numpy.sum', 'np.sum', (['p_sas'], {}), '(p_sas)\n', (18187, 18194), True, 'import numpy as np\n')]
import numpy import algopy def f_fcn(x): A = algopy.zeros((2,2), dtype=x) A[0,0] = x[0] A[1,0] = x[1] * x[0] A[0,1] = x[1] Q,R = algopy.qr(A) return R[0,0] # Method 1: Complex-step derivative approximation (CSDA) h = 10**-20 x0 = numpy.array([3,2],dtype=float) x1 = numpy.array([1,0]) yc = numpy.imag(f_fcn(x0 + 1j * h * x1) - f_fcn(x0 - 1j * h * x1))/(2*h) # Method 2: univariate Taylor polynomial arithmetic (UTP) ax = algopy.UTPM(numpy.zeros((2,1,2))) ax.data[0,0] = x0 ax.data[1,0] = x1 ay = f_fcn(ax) # Method 3: finite differences h = 10**-8 yf = (f_fcn(x0 + h * x1) - f_fcn(x0))/h # Print results print('CSDA result =',yc) print('UTP result =',ay.data[1,0]) print('FD result =',yf)
[ "numpy.zeros", "numpy.array", "algopy.qr", "algopy.zeros" ]
[((257, 289), 'numpy.array', 'numpy.array', (['[3, 2]'], {'dtype': 'float'}), '([3, 2], dtype=float)\n', (268, 289), False, 'import numpy\n'), ((293, 312), 'numpy.array', 'numpy.array', (['[1, 0]'], {}), '([1, 0])\n', (304, 312), False, 'import numpy\n'), ((50, 79), 'algopy.zeros', 'algopy.zeros', (['(2, 2)'], {'dtype': 'x'}), '((2, 2), dtype=x)\n', (62, 79), False, 'import algopy\n'), ((150, 162), 'algopy.qr', 'algopy.qr', (['A'], {}), '(A)\n', (159, 162), False, 'import algopy\n'), ((461, 483), 'numpy.zeros', 'numpy.zeros', (['(2, 1, 2)'], {}), '((2, 1, 2))\n', (472, 483), False, 'import numpy\n')]
import os import numpy as np if not os.path.exists('./npydata'): os.makedirs('./npydata') jhu_root = 'jhu_crowd_v2.0' try: Jhu_train_path = jhu_root + '/train/images_2048/' Jhu_val_path = jhu_root + '/val/images_2048/' jhu_test_path = jhu_root + '/test/images_2048/' train_list = [] for filename in os.listdir(Jhu_train_path): if filename.split('.')[1] == 'jpg': train_list.append(Jhu_train_path + filename) train_list.sort() np.save('./npydata/jhu_train.npy', train_list) val_list = [] for filename in os.listdir(Jhu_val_path): if filename.split('.')[1] == 'jpg': val_list.append(Jhu_val_path + filename) val_list.sort() np.save('./npydata/jhu_val.npy', val_list) test_list = [] for filename in os.listdir(jhu_test_path): if filename.split('.')[1] == 'jpg': test_list.append(jhu_test_path + filename) test_list.sort() np.save('./npydata/jhu_test.npy', test_list) print("Generate JHU image list successfully") except: print("The JHU dataset path is wrong. Please check your path.")
[ "os.listdir", "numpy.save", "os.path.exists", "os.makedirs" ]
[((37, 64), 'os.path.exists', 'os.path.exists', (['"""./npydata"""'], {}), "('./npydata')\n", (51, 64), False, 'import os\n'), ((70, 94), 'os.makedirs', 'os.makedirs', (['"""./npydata"""'], {}), "('./npydata')\n", (81, 94), False, 'import os\n'), ((329, 355), 'os.listdir', 'os.listdir', (['Jhu_train_path'], {}), '(Jhu_train_path)\n', (339, 355), False, 'import os\n'), ((484, 530), 'numpy.save', 'np.save', (['"""./npydata/jhu_train.npy"""', 'train_list'], {}), "('./npydata/jhu_train.npy', train_list)\n", (491, 530), True, 'import numpy as np\n'), ((570, 594), 'os.listdir', 'os.listdir', (['Jhu_val_path'], {}), '(Jhu_val_path)\n', (580, 594), False, 'import os\n'), ((717, 759), 'numpy.save', 'np.save', (['"""./npydata/jhu_val.npy"""', 'val_list'], {}), "('./npydata/jhu_val.npy', val_list)\n", (724, 759), True, 'import numpy as np\n'), ((800, 825), 'os.listdir', 'os.listdir', (['jhu_test_path'], {}), '(jhu_test_path)\n', (810, 825), False, 'import os\n'), ((951, 995), 'numpy.save', 'np.save', (['"""./npydata/jhu_test.npy"""', 'test_list'], {}), "('./npydata/jhu_test.npy', test_list)\n", (958, 995), True, 'import numpy as np\n')]
import copy import numpy as np import gsw from .operation import QCOperation, QCOperationError from .flag import Flag class ChlaTest(QCOperation): def run_impl(self): # note - need to calculate CHLA up here from FLUORESCENCE_CHLA # not sure where it will come from - need from Anh fluo = self.profile['FLUORESCENCE_CHLA'] # dark_chla = grab factory dark CHLA dark_chla = 4 # dummy placeholder # scale_chla = grab factory scale factor scale_chla = 1.13 # dummy placeholder chla = self.convert(dark_chla, scale_chla) self.log('Setting previously unset flags for CHLA to GOOD') Flag.update_safely(chla.qc, to=Flag.GOOD) self.log('Setting previously unset flags for CHLA_ADJUSTED to GOOD') Flag.update_safely(chla.adjusted_qc, to=Flag.GOOD) # global range test self.log('Applying global range test to CHLA') values_outside_range = (chla.value < -0.1) | (chla.value > 100.0) Flag.update_safely(chla.qc, Flag.BAD, values_outside_range) Flag.update_safely(chla.adjusted_qc, Flag.BAD, values_outside_range) # dark count test self.log('Checking for previous DARK_CHLA') # get previous dark count here # last_dark_chla = grab last DARK_CHLA considered good for calibration last_dark_chla = 5 # dummy placeholder self.log('Testing if factory calibration matches last good dark count') # test 1 if dark_chla != last_dark_chla: self.log('LAST_DARK_CHLA does not match factory DARK_CHLA, flagging CHLA as PROBABLY_BAD') Flag.update_safely(chla.qc, to=Flag.PROBABLY_BAD) # the mixed layer depth calculation can fail mixed_layer_depth = None flag_mld = False try: mixed_layer_depth = self.mixed_layer_depth() flag_mld = True except QCOperationError as e: self.log(e) if mixed_layer_depth is not None: self.log(f'Mixed layer depth calculated ({mixed_layer_depth} dbar)') # constants for mixed layer test delta_depth = 200 delta_dark = 50 # maximum pressure reached on this profile max_pres = np.nanmax(chla.pres) # test 2 if flag_mld: # I find the QC manual unclear on what to do here, should check with perhaps <NAME>ig on how to process w/ no MLD self.log('No mixed layer found, setting DARK_PRIME_CHLA to LAST_DARK_CHLA, CHLA_QC to PROBABLY_GOOD, and CHLA_ADJUSTED_QC to PROBABLY_GOOD') dark_prime_chla = last_dark_chla Flag.update_safely(chla.qc, to=Flag.PROBABLY_GOOD) Flag.update_safely(chla.adjusted_qc, to=Flag.PROBABLY_GOOD) elif max_pres < mixed_layer_depth + delta_depth + delta_dark: self.log('Max pressure is insufficiently deep, setting DARK_PRIME_CHLA to LAST_DARK_CHLA, CHLA_QC to PROBABLY_GOOD, and CHLA_ADJUSTED_QC to PROBABLY_GOOD') dark_prime_chla = last_dark_chla Flag.update_safely(chla.qc, to=Flag.PROBABLY_GOOD) Flag.update_safely(chla.adjusted_qc, to=Flag.PROBABLY_GOOD) else: dark_prime_chla = np.nanmedian(fluo.value[fluo.pres > (max_pres - delta_dark)]) # test 3 if np.abs(dark_prime_chla - dark_chla) > 0.2*dark_chla: self.log('DARK_PRIME_CHLA is more than 20%% different than last good calibration, reverting to LAST_DARK_CHLA and setting CHLA_QC to PROBABLY_BAD, CHLA_ADJUSTED_QC to PROBABLY_BAD') dark_prime_chla = last_dark_chla Flag.update_safely(chla.qc, to=Flag.PROBABLY_BAD) Flag.update_safely(chla.adjusted_qc, to=Flag.PROBABLY_BAD) else: # test 4 if dark_prime_chla != dark_chla: self.log('New DARK_CHLA value found, setting CHLA_QC to PROBABLY_BAD, CHLA_ADJUSTED_QC to GOOD, and updating LAST_DARK_CHLA') last_dark_chla = dark_prime_chla Flag.update_safely(chla.qc, to=Flag.PROBABLY_BAD) Flag.update_safely(chla.adjusted_qc, to=Flag.GOOD) chla.adjusted = self.convert(dark_prime_chla, scale_chla, adjusted=True) # CHLA spike test self.log('Performing negative spike test') median_chla = self.running_median(5) res = chla.value - median_chla spike_values = res < 2*np.percentile(res, 10) Flag.update_safely(chla.qc, Flag.BAD, spike_values) Flag.update_safely(chla.adjusted_qc, Flag.BAD, spike_values) # CHLA NPQ correction self.log('Performing Non-Photochemical Quenching (NPQ) test') if not flag_mld: positive_spikes = res > 2*np.percentile(res, 90) depthNPQ_ix = np.where(median_chla[~positive_spikes] == np.nanmax(median_chla[~positive_spikes]))[0][0] depthNPQ = chla.pres[depthNPQ_ix] if depthNPQ < 0.9*mixed_layer_depth: self.log(f'Adjusting surface values (P < {depthNPQ}dbar) to CHLA({depthNPQ}) = {chla.value[depthNPQ_ix]}mg/m3') chla.adjusted[:depthNPQ_ix] = chla.adjusted[depthNPQ_ix] self.log('Setting values above this depth in CHLA_QC to PROBABLY_BAD, and in CHLA_ADJUSTED_QC to changed') Flag.update_safely(chla.qc, to=Flag.PROBABLY_BAD, where=chla.pres < depthNPQ) Flag.update_safely(chla.adjusted_qc, to=Flag.CHANGED, where=chla.pres < depthNPQ) # Roesler et al. 2017 factor of 2 global bias chla.adjusted = chla.adjusted/2 # update the CHLA trace self.update_trace('CHLA', chla) def mixed_layer_depth(self): self.log('Calculating mixed layer depth') pres = self.profile['PRES'] temp = self.profile['TEMP'] psal = self.profile['PSAL'] if np.any(pres.value != temp.pres) or np.any(pres.value != psal.pres): self.error('PRES, TEMP, and PSAL are not aligned along the same pressure axis') # the longitude isn't actually important here because we're calculating relative # density in the same location longitude = 0 latitude = 0 abs_salinity = gsw.SA_from_SP(psal.value, pres.value, longitude, latitude) conservative_temp = gsw.CT_from_t(abs_salinity, temp.value, pres.value) density = gsw.sigma0(abs_salinity, conservative_temp) with self.pyplot() as plt: plt.plot(density, pres.value) plt.gca().invert_yaxis() plt.gca().set_xlabel('sigma0') mixed_layer_start = (np.diff(density) > 0.03) & (pres.value[:-1] > 10) if not np.any(mixed_layer_start): self.error("Can't determine mixed layer depth (no density changes > 0.03 below 10 dbar)") mixed_layer_start_index = np.where(mixed_layer_start)[0][0] mixed_layer_depth = pres.value[mixed_layer_start_index] self.log(f'...mixed layer depth found at {mixed_layer_depth} dbar') return mixed_layer_depth def convert(self, dark, scale, adjusted=False): fluo = self.profile['FLUORESCENCE_CHLA'] if adjusted: # just return the value so it can be assigned to a Trace().adjusted return (fluo.value - dark) * scale else: # create a trace, update value to be converted unit chla = copy.deepcopy(fluo) chla.value = (fluo.value - dark)*scale return chla def running_median(self, n): self.log(f'Calculating running median over window size {n}') x = self.profile['CHLA'] ix = np.arange(n) + np.arange(len(x)-n+1)[:,None] b = [row[row > 0] for row in x[ix]] k = int(n/2) med = [np.median(c) for c in b] med = np.array(k*[np.nan] + med + k*[np.nan]) return med
[ "copy.deepcopy", "numpy.abs", "gsw.SA_from_SP", "numpy.nanmedian", "gsw.CT_from_t", "numpy.median", "gsw.sigma0", "numpy.any", "numpy.percentile", "numpy.diff", "numpy.array", "numpy.arange", "numpy.where", "numpy.nanmax" ]
[((2261, 2281), 'numpy.nanmax', 'np.nanmax', (['chla.pres'], {}), '(chla.pres)\n', (2270, 2281), True, 'import numpy as np\n'), ((6229, 6288), 'gsw.SA_from_SP', 'gsw.SA_from_SP', (['psal.value', 'pres.value', 'longitude', 'latitude'], {}), '(psal.value, pres.value, longitude, latitude)\n', (6243, 6288), False, 'import gsw\n'), ((6317, 6368), 'gsw.CT_from_t', 'gsw.CT_from_t', (['abs_salinity', 'temp.value', 'pres.value'], {}), '(abs_salinity, temp.value, pres.value)\n', (6330, 6368), False, 'import gsw\n'), ((6387, 6430), 'gsw.sigma0', 'gsw.sigma0', (['abs_salinity', 'conservative_temp'], {}), '(abs_salinity, conservative_temp)\n', (6397, 6430), False, 'import gsw\n'), ((7812, 7855), 'numpy.array', 'np.array', (['(k * [np.nan] + med + k * [np.nan])'], {}), '(k * [np.nan] + med + k * [np.nan])\n', (7820, 7855), True, 'import numpy as np\n'), ((3325, 3360), 'numpy.abs', 'np.abs', (['(dark_prime_chla - dark_chla)'], {}), '(dark_prime_chla - dark_chla)\n', (3331, 3360), True, 'import numpy as np\n'), ((5874, 5905), 'numpy.any', 'np.any', (['(pres.value != temp.pres)'], {}), '(pres.value != temp.pres)\n', (5880, 5905), True, 'import numpy as np\n'), ((5909, 5940), 'numpy.any', 'np.any', (['(pres.value != psal.pres)'], {}), '(pres.value != psal.pres)\n', (5915, 5940), True, 'import numpy as np\n'), ((6684, 6709), 'numpy.any', 'np.any', (['mixed_layer_start'], {}), '(mixed_layer_start)\n', (6690, 6709), True, 'import numpy as np\n'), ((7404, 7423), 'copy.deepcopy', 'copy.deepcopy', (['fluo'], {}), '(fluo)\n', (7417, 7423), False, 'import copy\n'), ((7648, 7660), 'numpy.arange', 'np.arange', (['n'], {}), '(n)\n', (7657, 7660), True, 'import numpy as np\n'), ((7773, 7785), 'numpy.median', 'np.median', (['c'], {}), '(c)\n', (7782, 7785), True, 'import numpy as np\n'), ((3230, 3289), 'numpy.nanmedian', 'np.nanmedian', (['fluo.value[fluo.pres > max_pres - delta_dark]'], {}), '(fluo.value[fluo.pres > max_pres - delta_dark])\n', (3242, 3289), True, 'import numpy as np\n'), ((4429, 4451), 'numpy.percentile', 'np.percentile', (['res', '(10)'], {}), '(res, 10)\n', (4442, 4451), True, 'import numpy as np\n'), ((6619, 6635), 'numpy.diff', 'np.diff', (['density'], {}), '(density)\n', (6626, 6635), True, 'import numpy as np\n'), ((6848, 6875), 'numpy.where', 'np.where', (['mixed_layer_start'], {}), '(mixed_layer_start)\n', (6856, 6875), True, 'import numpy as np\n'), ((4753, 4775), 'numpy.percentile', 'np.percentile', (['res', '(90)'], {}), '(res, 90)\n', (4766, 4775), True, 'import numpy as np\n'), ((4844, 4884), 'numpy.nanmax', 'np.nanmax', (['median_chla[~positive_spikes]'], {}), '(median_chla[~positive_spikes])\n', (4853, 4884), True, 'import numpy as np\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import scipy.special import numpy as np def post_proba(Q, x, actions, T=1): """Posteria proba of c in actions {p(a|x)} ~ softmax(Q(x,a)) Arguments: Q {dict} -- Q table x {array} -- state actions {array|list} -- array of actions Keyword Arguments: T {number} -- scaling Q value (default: {1}) Returns: array with |actions| elements """ return scipy.special.softmax(T*Q[x, a] for a in actions) def joint_proba(Q, x, actions, T=1): # joint proba of x, c for c in actions return post_proba(Q, xi, actions, T) * proba(x) def joint_proba_i(Q, xi, i, states, actions, T=1): # joint proba of c in actions under Xi=xi return np.mean([post_proba(Q, xi, actions, T) * proba(x) for x in states if x[i]==xi], axis=0) def ez_proba_i(Q, xi, i, states, actions, T=1): # easy version of joint_proba_i return np.mean([post_proba(Q, xi, actions, T) for x in states if x[i]==xi], axis=0) def post_proba(Q, x, states, T=1): return scipy.special.softmax(join_proba_i(Q, xi, i, states, T)) def predict_proba(Q, x, states, T=1): P = np.array([joint_proba_i(Q, xi, i, states, T) for xi in x]) A = T * np.sum(P, axis=0) + (1-n) * np.log(pp) return A def predict(Q, x, states, T=1): A = predict_proba(Q, x, states, T) return np.argmax(A)
[ "numpy.sum", "numpy.log", "numpy.argmax" ]
[((1387, 1399), 'numpy.argmax', 'np.argmax', (['A'], {}), '(A)\n', (1396, 1399), True, 'import numpy as np\n'), ((1252, 1269), 'numpy.sum', 'np.sum', (['P'], {'axis': '(0)'}), '(P, axis=0)\n', (1258, 1269), True, 'import numpy as np\n'), ((1280, 1290), 'numpy.log', 'np.log', (['pp'], {}), '(pp)\n', (1286, 1290), True, 'import numpy as np\n')]
"""Default hyperparameters for 1D time-dep Burgers Equation.""" import numpy as np import tensorflow as tf HP = {} # Dimension of u(x, t, mu) HP["n_v"] = 1 # Space HP["n_x"] = 256 HP["x_min"] = 0. HP["x_max"] = 1.5 # Time HP["n_t"] = 1000 HP["t_min"] = 1. HP["t_max"] = 5. # Snapshots count HP["n_s"] = 300 HP["n_s_hifi"] = int(1e3) # POD stopping param HP["eps"] = 1e-10 HP["eps_init"] = 1e-10 # HP["eps_init"] = None # Train/val split HP["train_val_test"] = (1/3, 1/3, 1/3) # Deep NN hidden layers topology HP["h_layers"] = [64, 64] # Setting up _structthe TF SGD-based optimizer HP["epochs"] = 80000 HP["lr"] = 0.002 HP["lambda"] = 1e-4 # Frequency of the logger HP["log_frequency"] = 1000 # Burgers params HP["mu_min"] = [0.001] HP["mu_max"] = [0.0100] np.random.seed(1111) tf.random.set_seed(1111)
[ "tensorflow.random.set_seed", "numpy.random.seed" ]
[((761, 781), 'numpy.random.seed', 'np.random.seed', (['(1111)'], {}), '(1111)\n', (775, 781), True, 'import numpy as np\n'), ((782, 806), 'tensorflow.random.set_seed', 'tf.random.set_seed', (['(1111)'], {}), '(1111)\n', (800, 806), True, 'import tensorflow as tf\n')]
import sc2 from sc2 import run_game, maps, Race, Difficulty, position from sc2.player import Bot, Computer from sc2.constants import * import random import cv2 import numpy as np import time #from sc2.data import race_townhalls # the point of this class is to set all the attack type options for the units to attack. class IntelCoord(): intSimpleScout = 0 #intScoutTag = None listScoutTags = [] DrawDict = { NEXUS: [5, (0, 255, 0)], PYLON: [2, (20, 235, 0)], PROBE: [1, (55, 200, 0)], ASSIMILATOR: [2, (55, 200, 0)], GATEWAY: [3, (200, 100, 0)], CYBERNETICSCORE: [3, (150, 150, 0)], STARGATE: [3, (255, 0, 0)], VOIDRAY: [2, (255, 100, 0)], } listTrainData = [] objFlippedCVMap = None def select_target(self,draf_bot): if draf_bot.known_enemy_structures.exists: return random.choice(draf_bot.known_enemy_structures).position return draf_bot.enemy_start_locations[0] async def intel(self,draf_bot): game_data = np.zeros((draf_bot.game_info.map_size[1], draf_bot.game_info.map_size[0], 3), np.uint8) for unit_type in self.DrawDict: for unit in draf_bot.units(unit_type).ready: pos = unit.position cv2.circle(game_data, (int(pos[0]), int(pos[1])), int(unit.radius) * self.DrawDict[unit_type][0], self.DrawDict[unit_type][1], -1) main_base_names = ["nexus", "commandcenter", "hatchery"] for enemy_building in draf_bot.known_enemy_structures: pos = enemy_building.position if enemy_building.name.lower() not in main_base_names: cv2.circle(game_data, (int(pos[0]), int(pos[1])), 5, (200, 50, 212), -1) for enemy_building in draf_bot.known_enemy_structures: pos = enemy_building.position if enemy_building.name.lower() in main_base_names: cv2.circle(game_data, (int(pos[0]), int(pos[1])), 15, (0, 0, 255), -1) for enemy_unit in draf_bot.known_enemy_units: if not enemy_unit.is_structure: worker_names = ["probe", "scv", "drone"] # if that unit is a PROBE, SCV, or DRONE... it's a worker pos = enemy_unit.position if enemy_unit.name.lower() in worker_names: cv2.circle(game_data, (int(pos[0]), int(pos[1])), 1, (55, 0, 155), -1) else: cv2.circle(game_data, (int(pos[0]), int(pos[1])), 3, (50, 0, 215), -1) if len(self.listScoutTags) > 0: for _intScoutTag in self.listScoutTags: if draf_bot.units.find_by_tag(_intScoutTag) is not None: _posScout = draf_bot.units.find_by_tag(_intScoutTag).position #print("tag ==> " + str(self.objScout.tag)) #print("posScout ==> " + str(_posScout)) cv2.circle(game_data, (int(_posScout[0]), int(_posScout[1])), 1, (255, 255, 255), -1) self.objFlippedCVMap = cv2.flip(game_data, 0) resized = cv2.resize(self.objFlippedCVMap, dsize=None, fx=2, fy=2) cv2.imshow('Intel', resized) cv2.waitKey(1) self.appendTrainData([self.objFlippedCVMap]) def appendTrainData(self,objData): self.listTrainData.append(objData) def saveTrainData(self): np.save("G:\dev2\OPIMDemo\\drafbot\\train_data\\{}.npy".format(str(int(time.time()))), np.array(self.listTrainData)) #np.savetxt("G:\dev2\OPIMDemo\\drafbot\\train_data\\{}.txt".format(str(int(time.time()))), np.array(self.listTrainData)) def haveVisibleEnemyOffUnit(self, draf_bot): intNumEnemyUnitsStructures = len(draf_bot.known_enemy_units) intNumEnemyStructures = len(draf_bot.known_enemy_units) if len(draf_bot.known_enemy_units) > 0: return draf_bot.known_enemy_units def random_location_variance(self, draf_bot, enemy_start_location): x = enemy_start_location[0] y = enemy_start_location[1] x += ((random.randrange(-20, 20))/100) * enemy_start_location[0] y += ((random.randrange(-20, 20))/100) * enemy_start_location[1] if x < 0: x = 0 if y < 0: y = 0 if x > draf_bot.game_info.map_size[0]: x = draf_bot.game_info.map_size[0] if y > draf_bot.game_info.map_size[1]: y = draf_bot.game_info.map_size[1] go_to = position.Point2(position.Pointlike((x,y))) return go_to #This function will send a probe to scout. To resend a probe to scout, use #resendSimpleScout async def sendSimpleScout(self,draf_bot): if self.intSimpleScout < 1: _EnemyLocation = draf_bot.enemy_start_locations[0] _objScout = draf_bot.units(PROBE).ready.random self.listScoutTags.append(_objScout.tag) _scout_dest = self.random_location_variance(draf_bot,_EnemyLocation) #print("Scout Destinatino ==>" + str(_scout_dest)) await draf_bot.do(_objScout.move(_scout_dest)) self.intSimpleScout = self.intSimpleScout + 1 async def resendSimpleScout(self): self.intSimpleScout = 0 async def sendScout(self,draf_bot): if draf_bot.units(NEXUS).ready.exists > 1: self.sendObserver(draf_bot) else: self.sendSimpleScout(draf_bot) async def sendObserver(self,draf_bot): if len(draf_bot.units(OBSERVER)) > 0: scout = draf_bot.units(OBSERVER)[0] if scout.is_idle: enemy_location = draf_bot.enemy_start_locations[0] move_to = draf_bot.random_location_variance(enemy_location) print(move_to) self.listScoutTags.append(_objScout.tag) await draf_bot.do(scout.move(move_to)) else: for rf in draf_bot.units(ROBOTICSFACILITY).ready.noqueue: if draf_bot.can_afford(OBSERVER) and draf_bot.supply_left > 0: await draf_bot.do(rf.train(OBSERVER))
[ "sc2.position.Pointlike", "cv2.waitKey", "numpy.zeros", "random.choice", "time.time", "numpy.array", "random.randrange", "cv2.flip", "cv2.imshow", "cv2.resize" ]
[((1213, 1305), 'numpy.zeros', 'np.zeros', (['(draf_bot.game_info.map_size[1], draf_bot.game_info.map_size[0], 3)', 'np.uint8'], {}), '((draf_bot.game_info.map_size[1], draf_bot.game_info.map_size[0], 3\n ), np.uint8)\n', (1221, 1305), True, 'import numpy as np\n'), ((3332, 3354), 'cv2.flip', 'cv2.flip', (['game_data', '(0)'], {}), '(game_data, 0)\n', (3340, 3354), False, 'import cv2\n'), ((3382, 3438), 'cv2.resize', 'cv2.resize', (['self.objFlippedCVMap'], {'dsize': 'None', 'fx': '(2)', 'fy': '(2)'}), '(self.objFlippedCVMap, dsize=None, fx=2, fy=2)\n', (3392, 3438), False, 'import cv2\n'), ((3448, 3476), 'cv2.imshow', 'cv2.imshow', (['"""Intel"""', 'resized'], {}), "('Intel', resized)\n", (3458, 3476), False, 'import cv2\n'), ((3486, 3500), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (3497, 3500), False, 'import cv2\n'), ((3769, 3797), 'numpy.array', 'np.array', (['self.listTrainData'], {}), '(self.listTrainData)\n', (3777, 3797), True, 'import numpy as np\n'), ((4818, 4844), 'sc2.position.Pointlike', 'position.Pointlike', (['(x, y)'], {}), '((x, y))\n', (4836, 4844), False, 'from sc2 import run_game, maps, Race, Difficulty, position\n'), ((1045, 1091), 'random.choice', 'random.choice', (['draf_bot.known_enemy_structures'], {}), '(draf_bot.known_enemy_structures)\n', (1058, 1091), False, 'import random\n'), ((4381, 4406), 'random.randrange', 'random.randrange', (['(-20)', '(20)'], {}), '(-20, 20)\n', (4397, 4406), False, 'import random\n'), ((4455, 4480), 'random.randrange', 'random.randrange', (['(-20)', '(20)'], {}), '(-20, 20)\n', (4471, 4480), False, 'import random\n'), ((3753, 3764), 'time.time', 'time.time', ([], {}), '()\n', (3762, 3764), False, 'import time\n')]
import math import numpy import random # note that this only works for a single layer of depth INPUT_NODES = 2 OUTPUT_NODES = 1 HIDDEN_NODES = 2 ALPHA = 3.0 # Max seed, this is so we can experiment consistently MAX_SEED = 10000 # 15000 iterations is a good point for playing with learning rate MAX_ITERATIONS = 10000 # setting this too low makes everything change very slowly, but too high # makes it jump at each and every example and oscillate. I found .5 to be good LEARNING_RATE = .1 print("Neural Network Program - XOR Problem") class network: def __init__(self, input_nodes, hidden_nodes, output_nodes, learning_rate, alpha): self.input_nodes = input_nodes self.hidden_nodes = hidden_nodes self.output_nodes = output_nodes self.total_nodes = input_nodes + hidden_nodes + output_nodes self.learning_rate = learning_rate self.alpha = alpha; # set up the arrays self.values = numpy.zeros(self.total_nodes) self.expectedValues = numpy.zeros(self.total_nodes) self.thresholds = numpy.zeros(self.total_nodes) # the weight matrix is always square self.weights = numpy.zeros((self.total_nodes, self.total_nodes)) # set random seed! random.seed(MAX_SEED) # set initial random values for weights and thresholds # this is a strictly upper triangular matrix as there is no feedback # loop and there inputs do not affect other inputs for i in range(self.input_nodes, self.total_nodes): self.thresholds[i] = random.random() / random.random() for j in range(i + 1, self.total_nodes): self.weights[i][j] = random.random() * 2 # Activating function def sigmoid(self, x): return 1 / (1 + math.exp(-self.alpha * x)) # Deactivating function def deSigmoid(self, x): return self.alpha * x * (1 - x) def process(self): # update the hidden nodes for i in range(self.input_nodes, self.input_nodes + self.hidden_nodes): # sum weighted input nodes for each hidden node, compare threshold, apply sigmoid W_i = 0.0 for j in range(self.input_nodes): W_i += self.weights[j][i] * self.values[j] W_i -= self.thresholds[i] self.values[i] = self.sigmoid(W_i) # update the output nodes for i in range(self.input_nodes + self.hidden_nodes, self.total_nodes): # sum weighted hidden nodes for each output node, compare threshold, apply sigmoid W_i = 0.0 for j in range(self.input_nodes, self.input_nodes + self.hidden_nodes): W_i += self.weights[j][i] * self.values[j] W_i -= self.thresholds[i] self.values[i] = self.sigmoid(W_i) def processErrors(self): sumOfSquaredErrors = 0.0 # we only look at the output nodes for error calculation for i in range(self.input_nodes + self.hidden_nodes, self.total_nodes): error = self.expectedValues[i] - self.values[i] #print(error) sumOfSquaredErrors += math.pow(error, 2) outputErrorGradient = self.deSigmoid(self.values[i]) * error #print(outputErrorGradient) # now update the weights and thresholds for j in range(self.input_nodes, self.input_nodes + self.hidden_nodes): # first update for the hidden nodes to output nodes (1 layer) delta = self.alpha * self.learning_rate * self.values[j] * outputErrorGradient #print(delta) self.weights[j][i] += delta hiddenErrorGradient = self.deSigmoid(self.values[j]) * outputErrorGradient * self.weights[j][i] # and then update for the input nodes to hidden nodes for k in range(self.input_nodes): delta = self.learning_rate * self.values[k] * hiddenErrorGradient self.weights[k][j] += delta # update the thresholds for the hidden nodes delta = self.learning_rate * -1 * hiddenErrorGradient #print delta self.thresholds[j] += delta # update the thresholds for the output node(s) delta = self.learning_rate * -1 * outputErrorGradient self.thresholds[i] += delta return sumOfSquaredErrors class sampleMaker: def __init__(self, network): self.counter = 0 self.network = network def setXor(self, x): if x == 0: self.network.values[0] = 1 self.network.values[1] = 1 self.network.expectedValues[4] = 0 elif x == 1: self.network.values[0] = 0 self.network.values[1] = 1 self.network.expectedValues[4] = 1 elif x == 2: self.network.values[0] = 1 self.network.values[1] = 0 self.network.expectedValues[4] = 1 else: self.network.values[0] = 0 self.network.values[1] = 0 self.network.expectedValues[4] = 0 def setNextTrainingData(self): self.setXor(self.counter % 4) self.counter += 1 # start of main program loop, initialize classes net = network(INPUT_NODES, HIDDEN_NODES, OUTPUT_NODES, LEARNING_RATE, ALPHA) samples = sampleMaker(net) for i in range(MAX_ITERATIONS): samples.setNextTrainingData() net.process() error = net.processErrors() # prove that we got the right answers(ish)! if i > (MAX_ITERATIONS - 5): output = (net.values[0], net.values[1], net.values[4], net.expectedValues[4], error) print(output) # display final parameters #print(net.weights) #print(net.thresholds)
[ "math.exp", "math.pow", "numpy.zeros", "random.random", "random.seed" ]
[((954, 983), 'numpy.zeros', 'numpy.zeros', (['self.total_nodes'], {}), '(self.total_nodes)\n', (965, 983), False, 'import numpy\n'), ((1014, 1043), 'numpy.zeros', 'numpy.zeros', (['self.total_nodes'], {}), '(self.total_nodes)\n', (1025, 1043), False, 'import numpy\n'), ((1070, 1099), 'numpy.zeros', 'numpy.zeros', (['self.total_nodes'], {}), '(self.total_nodes)\n', (1081, 1099), False, 'import numpy\n'), ((1169, 1218), 'numpy.zeros', 'numpy.zeros', (['(self.total_nodes, self.total_nodes)'], {}), '((self.total_nodes, self.total_nodes))\n', (1180, 1218), False, 'import numpy\n'), ((1256, 1277), 'random.seed', 'random.seed', (['MAX_SEED'], {}), '(MAX_SEED)\n', (1267, 1277), False, 'import random\n'), ((3143, 3161), 'math.pow', 'math.pow', (['error', '(2)'], {}), '(error, 2)\n', (3151, 3161), False, 'import math\n'), ((1571, 1586), 'random.random', 'random.random', ([], {}), '()\n', (1584, 1586), False, 'import random\n'), ((1589, 1604), 'random.random', 'random.random', ([], {}), '()\n', (1602, 1604), False, 'import random\n'), ((1789, 1814), 'math.exp', 'math.exp', (['(-self.alpha * x)'], {}), '(-self.alpha * x)\n', (1797, 1814), False, 'import math\n'), ((1695, 1710), 'random.random', 'random.random', ([], {}), '()\n', (1708, 1710), False, 'import random\n')]
# -*- coding: utf-8 -*- """ Created on Sun Oct 31 10:36:53 2021 @author: TK >>>> Norlys ET -- Quant exercise <<<< One of your colleagues have discovered a trading strategy that looks to be quite profitable. The strategy works by opening a position on the DAH (Day Ahead) market, and then trade this out ID (intraday). It’s however starting to decline in performance, so you’re tasked with coming up with a new strategy. The new strategy shall be based on the forecasted wind and solar production as well as the forecasted consumption. The original strategy also contains derived features (an example could be difference in solar level from rolling two-week average). To compare the two strategies directly, you’ve been given a file (data_for_exercise.csv), that contains the following columns. data_input.columns = [ts, wind, solar, cons, spot, market] > ts: Timestamp [-] > wind, solar, cons: Forecasted wind, solar and consumption [MW]. > spot: The price we’re able to open the positions at [EUR/MWh]. > market: The price we’re able to close the positions at [EUR/MWh] NOTE: Python and module versions as follows... > Python: 3.8.8 > scipy: 1.7.1 > numpy: 1.21.2 > matplotlib: 3.4.3 > pandas: 1.3.3 > sklearn: 0.24.2 """ #%% load modules etc import sys import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns #from sci-kit-learn from sklearn.model_selection import train_test_split from sklearn.model_selection import cross_val_score from sklearn.model_selection import StratifiedKFold, KFold from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix from sklearn.metrics import accuracy_score from sklearn.metrics import mean_squared_error # ML models from sklearn.linear_model import LogisticRegression from sklearn.linear_model import LinearRegression from sklearn.linear_model import Lasso from sklearn.linear_model import Ridge from sklearn.tree import DecisionTreeClassifier from sklearn.neighbors import KNeighborsClassifier from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.naive_bayes import GaussianNB from sklearn.neighbors import KNeighborsRegressor from sklearn.tree import DecisionTreeRegressor from sklearn.ensemble import RandomForestRegressor from sklearn.svm import SVC from sklearn.svm import SVR #%% Load dataset filename = "data_new.csv" df = pd.read_csv(filename, parse_dates=['ts']) # set time column to index df = df.set_index('ts') # summary check print(df.describe()) #%% resample dfs to coarser time scales - may be useful for plotting/comparison daily_df = df.resample('D').mean() weekly_df = df.resample('W').mean() fortnight_df = df.resample('2W').mean() # Derived features: difference from rolling n-day aves def rolling_diff(dataframe, name , n): roll_ave = dataframe[name].rolling(n, center=True).mean() diff = dataframe[name] - roll_ave return diff # e.g. rolling 14 day aves for energy forecasts, as per the strategy doc solar_14d = df['solar'].rolling(14, center=True).mean() wind_14d = df['wind'].rolling(14, center=True).mean() cons_14d = df['cons'].rolling(14, center=True).mean() #%% new columns of interest? df0 = df.copy() # make a copy of original df df['dwind_14d'] = rolling_diff(df,'wind',14) df['dsolar_14d'] = rolling_diff(df,'solar',14) df['dcons_14d'] = rolling_diff(df,'cons',14) # df['total'] = df['solar'] + df['wind'] # total energy # df['dE'] = df['cons'] - df['total'] # difference in energy df['dP'] = df['market'] - df['spot'] # difference in price # df['Sp+'] = np.where(df['spot'] > 0, 1, 0) # df['Ma+'] = np.where(df['market'] > 0, 1, 0) df['dP+'] = np.where(df['market'] > df['spot'], 1., 0.) #NOTE: if market > spot, we make profit. So dP+ = 1 is the goal. # summary print(df.describe()) #%% 2. Explore data: summary plots # box and whisker plots (from original dataframe df0) df0.plot(kind='box', subplots=True, sharex=False, sharey=False) plt.show() # scatter plot matrix with histograms pd.plotting.scatter_matrix(df) plt.show() def correlated_mat(dataframe, plot=False): corr = dataframe.corr() if plot: # sns.set(rc={'figure.figsize': (10, 10)}) sns.heatmap(corr, cmap=plt.cm.RdBu, vmin=-1.0, vmax=1.0, annot=True, linewidths=.7) plt.xticks(rotation=60, size=10) plt.yticks(rotation=60, size=10) plt.title('Correlation Matrix', size=20) plt.show() correlated_mat(df, plot=True) #%% seaborn plots # choose variables of interest sns.jointplot(x='dsolar_14d', y='market', data=df) #recall dP+ = 1 if spot > market price, 0 if spot < market sns.FacetGrid(df, hue='dP+') \ .map(plt.scatter, 'solar', 'wind') \ .add_legend() plt.show() sns.pairplot(df, hue='dP+') plt.show() sns.FacetGrid(df, hue='dP+') \ .map(sns.kdeplot, 'wind') \ .add_legend() plt.show() #%% time series #energy forecasts for name in ['cons', 'wind', 'solar']: df[name].plot(ylabel='MWh',alpha = 0.4) daily_df[name].plot(legend=True) #energy forecasts name1 = ['cons', 'wind', 'solar'] df[name].plot(ylabel='MWh',alpha = 0.4) df[name].plot(legend=True) #prices for name in ['market', 'spot']: df[name].plot(ylabel='EUR/MWh',alpha = 0.4) daily_df[name].plot(legend=True) #compare e.g. wind and market price plt.figure() ax = df['market'].plot(color='r',ylabel='EUR/MWh',alpha = 0.4) daily_df['market'].plot(color='r',legend=True) df['wind'].plot(color='b',secondary_y=True,ylabel='MWh',alpha = 0.4) daily_df['wind'].plot(color='b',secondary_y=True,legend=True) ax.set_ylabel('EUR/MWh') ax.right_ax.set_ylabel('MWh') plt.show() # Autocorrelation (temporal) pd.plotting.autocorrelation_plot(df['wind']) pd.plotting.autocorrelation_plot(df['dP']) #%% 3. MODEL BUILDING - predicting dP+ #choose predictors and predictand # predictors = ['solar', 'wind', 'cons'] predictors = ['solar', 'wind', 'cons','dsolar_14d', 'dwind_14d', 'dcons_14d'] predictand = ['dP+'] # Binary Y/N: market price > spot price. df = df.dropna() # drop nans if they are present (e.g., due to rolling aves) X = df[predictors].values # predictors y = df[predictand].values # predictand y = f(X) y = np.ravel(y) X_train, X_validation, Y_train, Y_validation = train_test_split(X, y, test_size=0.2, random_state=0) #%% sklearn ML models -- i.e., the f in y = f(X). models = [] models.append(('LogR', LogisticRegression(solver='liblinear', multi_class='ovr'))) # models.append(('LinR', LinearRegression())) models.append(('LDA', LinearDiscriminantAnalysis())) models.append(('KNN', KNeighborsClassifier(n_neighbors=10))) models.append(('CART', DecisionTreeClassifier())) models.append(('NB', GaussianNB())) # models.append(('SVM', SVC(gamma='auto'))) #%% evaluate each model in turn results = [] names = [] for name, model in models: kfold = StratifiedKFold(n_splits=10, random_state=1, shuffle=True) cv_results = cross_val_score(model, X_train, Y_train, cv=kfold, scoring='accuracy') results.append(cv_results) names.append(name) print('%s: %f (%f)' % (name, cv_results.mean(), cv_results.std())) #%% Compare Algorithms plt.boxplot(results, labels=names) plt.title('Algorithm Comparison') plt.show() #%% Make predictions on validation dataset # model = SVC(gamma='auto') # model = LogisticRegression() model = models[2] print('Predictions using %s model...' % names[2]) model[1].fit(X_train, Y_train) predictions = model[1].predict(X_validation) #%% Evaluate predictions print(accuracy_score(Y_validation, predictions)) print(confusion_matrix(Y_validation, predictions)) print(classification_report(Y_validation, predictions)) #%% ''' #%% CONTINUOUS PREDICTIONS..? #%% 2. MODEL BUILDING - predicting dP #choose predictors and predictand predictors = ['solar', 'wind', 'cons'] predictand = ['market'] X = df[predictors].values # predictors y = df[predictand].values # predictand y = f(X) y = np.ravel(y) X_train, X_validation, Y_train, Y_validation = train_test_split(X, y, test_size=0.2, random_state=7) #%% sklearn ML models -- i.e., the f in y = f(X). models = [] models.append(('LinR', LinearRegression())) models.append(('Las', Lasso())) models.append(('Ridge', Ridge(alpha=.5))) models.append(('KNR', KNeighborsRegressor())) models.append(('DTR', DecisionTreeRegressor())) models.append(('RFR', RandomForestRegressor())) models.append(('SVR', SVR())) #%% evaluate each model in turn results = [] names = [] for name, model in models: kfold = KFold(n_splits=10) cv_results = cross_val_score(model, X_train, Y_train, cv = kfold) results.append(cv_results) names.append(name) print('%s: %f (%f)' % (name, cv_results.mean(), cv_results.std())) #%% Compare Algorithms plt.boxplot(results, labels=names) plt.title('Algorithm Comparison') plt.show() #%% Make predictions on validation dataset # model = SVC(gamma='auto') # model = LogisticRegression() model = models[3] print('Predictions using %s model...' % model[0]) model[1].fit(X_train, Y_train) predictions = model[1].predict(X_validation) print(model[1].score(X_validation, Y_validation), mean_squared_error(Y_validation, predictions)) '''
[ "matplotlib.pyplot.title", "seaborn.heatmap", "numpy.ravel", "pandas.read_csv", "sklearn.model_selection.train_test_split", "matplotlib.pyplot.boxplot", "sklearn.model_selection.cross_val_score", "sklearn.metrics.accuracy_score", "sklearn.metrics.classification_report", "sklearn.tree.DecisionTreeC...
[((2454, 2495), 'pandas.read_csv', 'pd.read_csv', (['filename'], {'parse_dates': "['ts']"}), "(filename, parse_dates=['ts'])\n", (2465, 2495), True, 'import pandas as pd\n'), ((3761, 3806), 'numpy.where', 'np.where', (["(df['market'] > df['spot'])", '(1.0)', '(0.0)'], {}), "(df['market'] > df['spot'], 1.0, 0.0)\n", (3769, 3806), True, 'import numpy as np\n'), ((4067, 4077), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4075, 4077), True, 'import matplotlib.pyplot as plt\n'), ((4120, 4150), 'pandas.plotting.scatter_matrix', 'pd.plotting.scatter_matrix', (['df'], {}), '(df)\n', (4146, 4150), True, 'import pandas as pd\n'), ((4152, 4162), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4160, 4162), True, 'import matplotlib.pyplot as plt\n'), ((4663, 4713), 'seaborn.jointplot', 'sns.jointplot', ([], {'x': '"""dsolar_14d"""', 'y': '"""market"""', 'data': 'df'}), "(x='dsolar_14d', y='market', data=df)\n", (4676, 4713), True, 'import seaborn as sns\n'), ((4868, 4878), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4876, 4878), True, 'import matplotlib.pyplot as plt\n'), ((4882, 4909), 'seaborn.pairplot', 'sns.pairplot', (['df'], {'hue': '"""dP+"""'}), "(df, hue='dP+')\n", (4894, 4909), True, 'import seaborn as sns\n'), ((4911, 4921), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4919, 4921), True, 'import matplotlib.pyplot as plt\n'), ((5007, 5017), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5015, 5017), True, 'import matplotlib.pyplot as plt\n'), ((5479, 5491), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (5489, 5491), True, 'import matplotlib.pyplot as plt\n'), ((5798, 5808), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5806, 5808), True, 'import matplotlib.pyplot as plt\n'), ((5842, 5886), 'pandas.plotting.autocorrelation_plot', 'pd.plotting.autocorrelation_plot', (["df['wind']"], {}), "(df['wind'])\n", (5874, 5886), True, 'import pandas as pd\n'), ((5888, 5930), 'pandas.plotting.autocorrelation_plot', 'pd.plotting.autocorrelation_plot', (["df['dP']"], {}), "(df['dP'])\n", (5920, 5930), True, 'import pandas as pd\n'), ((6369, 6380), 'numpy.ravel', 'np.ravel', (['y'], {}), '(y)\n', (6377, 6380), True, 'import numpy as np\n'), ((6429, 6482), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'test_size': '(0.2)', 'random_state': '(0)'}), '(X, y, test_size=0.2, random_state=0)\n', (6445, 6482), False, 'from sklearn.model_selection import train_test_split\n'), ((7330, 7364), 'matplotlib.pyplot.boxplot', 'plt.boxplot', (['results'], {'labels': 'names'}), '(results, labels=names)\n', (7341, 7364), True, 'import matplotlib.pyplot as plt\n'), ((7366, 7399), 'matplotlib.pyplot.title', 'plt.title', (['"""Algorithm Comparison"""'], {}), "('Algorithm Comparison')\n", (7375, 7399), True, 'import matplotlib.pyplot as plt\n'), ((7401, 7411), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (7409, 7411), True, 'import matplotlib.pyplot as plt\n'), ((7030, 7088), 'sklearn.model_selection.StratifiedKFold', 'StratifiedKFold', ([], {'n_splits': '(10)', 'random_state': '(1)', 'shuffle': '(True)'}), '(n_splits=10, random_state=1, shuffle=True)\n', (7045, 7088), False, 'from sklearn.model_selection import StratifiedKFold, KFold\n'), ((7105, 7175), 'sklearn.model_selection.cross_val_score', 'cross_val_score', (['model', 'X_train', 'Y_train'], {'cv': 'kfold', 'scoring': '"""accuracy"""'}), "(model, X_train, Y_train, cv=kfold, scoring='accuracy')\n", (7120, 7175), False, 'from sklearn.model_selection import cross_val_score\n'), ((7702, 7743), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['Y_validation', 'predictions'], {}), '(Y_validation, predictions)\n', (7716, 7743), False, 'from sklearn.metrics import accuracy_score\n'), ((7752, 7795), 'sklearn.metrics.confusion_matrix', 'confusion_matrix', (['Y_validation', 'predictions'], {}), '(Y_validation, predictions)\n', (7768, 7795), False, 'from sklearn.metrics import confusion_matrix\n'), ((7804, 7852), 'sklearn.metrics.classification_report', 'classification_report', (['Y_validation', 'predictions'], {}), '(Y_validation, predictions)\n', (7825, 7852), False, 'from sklearn.metrics import classification_report\n'), ((4315, 4403), 'seaborn.heatmap', 'sns.heatmap', (['corr'], {'cmap': 'plt.cm.RdBu', 'vmin': '(-1.0)', 'vmax': '(1.0)', 'annot': '(True)', 'linewidths': '(0.7)'}), '(corr, cmap=plt.cm.RdBu, vmin=-1.0, vmax=1.0, annot=True,\n linewidths=0.7)\n', (4326, 4403), True, 'import seaborn as sns\n'), ((4429, 4461), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'rotation': '(60)', 'size': '(10)'}), '(rotation=60, size=10)\n', (4439, 4461), True, 'import matplotlib.pyplot as plt\n'), ((4471, 4503), 'matplotlib.pyplot.yticks', 'plt.yticks', ([], {'rotation': '(60)', 'size': '(10)'}), '(rotation=60, size=10)\n', (4481, 4503), True, 'import matplotlib.pyplot as plt\n'), ((4513, 4553), 'matplotlib.pyplot.title', 'plt.title', (['"""Correlation Matrix"""'], {'size': '(20)'}), "('Correlation Matrix', size=20)\n", (4522, 4553), True, 'import matplotlib.pyplot as plt\n'), ((4563, 4573), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4571, 4573), True, 'import matplotlib.pyplot as plt\n'), ((6574, 6631), 'sklearn.linear_model.LogisticRegression', 'LogisticRegression', ([], {'solver': '"""liblinear"""', 'multi_class': '"""ovr"""'}), "(solver='liblinear', multi_class='ovr')\n", (6592, 6631), False, 'from sklearn.linear_model import LogisticRegression\n'), ((6704, 6732), 'sklearn.discriminant_analysis.LinearDiscriminantAnalysis', 'LinearDiscriminantAnalysis', ([], {}), '()\n', (6730, 6732), False, 'from sklearn.discriminant_analysis import LinearDiscriminantAnalysis\n'), ((6758, 6794), 'sklearn.neighbors.KNeighborsClassifier', 'KNeighborsClassifier', ([], {'n_neighbors': '(10)'}), '(n_neighbors=10)\n', (6778, 6794), False, 'from sklearn.neighbors import KNeighborsClassifier\n'), ((6821, 6845), 'sklearn.tree.DecisionTreeClassifier', 'DecisionTreeClassifier', ([], {}), '()\n', (6843, 6845), False, 'from sklearn.tree import DecisionTreeClassifier\n'), ((6870, 6882), 'sklearn.naive_bayes.GaussianNB', 'GaussianNB', ([], {}), '()\n', (6880, 6882), False, 'from sklearn.naive_bayes import GaussianNB\n'), ((4777, 4805), 'seaborn.FacetGrid', 'sns.FacetGrid', (['df'], {'hue': '"""dP+"""'}), "(df, hue='dP+')\n", (4790, 4805), True, 'import seaborn as sns\n'), ((4925, 4953), 'seaborn.FacetGrid', 'sns.FacetGrid', (['df'], {'hue': '"""dP+"""'}), "(df, hue='dP+')\n", (4938, 4953), True, 'import seaborn as sns\n')]
""" This file contains the code for training the speaker verification lstm model """ import speaker_diarization from configuration import get_config import os import numpy as np import speaker_verification_lstm_model import signal_processing import librosa import speaker_verfier # get arguments from parser config = get_config() def get_single_speaker_frames_from_utterances_path(utterances_folder): """ Extract frames of speach from folder with speaker uterrances Input: path to folder with a utternaces files Output: numpy array of frames """ # for each one of the utterances extract spectrogram and get frames voice_utterances = [] for single_utterance_file in os.listdir(utterances_folder): if os.path.isfile(os.path.join(utterances_folder, single_utterance_file)): utterance_path = os.path.join(utterances_folder, single_utterance_file) # extract audio utterance_audio, _ = librosa.core.load(utterance_path, config.sr) voice_utterances.append(utterance_audio) #extract spectrogram spectrograms = signal_processing.extract_spectrograms_from_utterances(voice_utterances) speaker_frames = [] # for each spectrogram save only first and last frames for single_spect in spectrograms: # take only utterrances that are long enough if single_spect.shape[0] > config.tisv_frame: speaker_frames.append(single_spect[:config.tisv_frame, :]) # first frames of partial utterance speaker_frames.append(single_spect[-config.tisv_frame:, :]) # last frames of partial utterance return np.concatenate( speaker_frames, axis=0) def create_embeddings_db_from_calls(is_test=0): """ Use audio files to build DB of embeddings for each customer Input: Audio files path is saved in config is_test - only run the code, don't write file Output: Embeddings DB is saved in npy file in the path defined by config file """ # iterate over all existing calls and extract embeddings for each user embeddings = [] # for each call create database of utterances for single_call_file in os.listdir(config.calls_path): call_file_path = os.path.join(config.calls_path, single_call_file) # Get embeddings of a single file, find mean embedding per speaker and append to the list single_speaker_embedding = speaker_verfier.get_single_speaker_embeddings_from_call_center_call(call_file_path) embeddings.append(single_speaker_embedding) #save the embedding into the DBs if is_test != 1: os.makedirs(config.embeddings_db_path, exist_ok=True) np.save(os.path.join(config.embeddings_db_path, "embedding_db"), embeddings) def create_embeddings_db_from_utternaces(is_test=0): """ Use single speaker utterances files to build DB of embeddings for each speaker Input: Audio files path is saved in config and contains folder per speaker is_test - only run the code, don't write file Output: Embeddings DB is saved in npy file in the path defined by config file """ # iterate over all existing calls and extract embeddings for each speaker embeddings = [] # Get embeddings of a single speaker, find mean embedding per speaker and append to the list for single_speaker_folder in os.listdir(config.utterance_path): single_speaker_folder = os.path.join(config.utterance_path, single_speaker_folder) single_speaker_frames = get_single_speaker_frames_from_utterances_path(single_speaker_folder) single_speaker_embeddings = speaker_verification_lstm_model.extract_embedding(single_speaker_frames) embeddings.append(np.mean(single_speaker_embeddings, axis=0)) #save the embedding into the DBs if is_test != 1: print(" Created new embedding DB in ", config.embeddings_db_path, ". There are", len(embeddings), "embeddings, with shape", embeddings[0].shape, "each.") os.makedirs(config.embeddings_db_path, exist_ok=True) np.save(os.path.join(config.embeddings_db_path, "embedding_db"), embeddings) # Run to create utternaces database given a path to a folder with different speaker utterances or calls if __name__ == "__main__": if config.embeddings_from_calls: create_embeddings_db_from_calls(is_test=0) else: create_embeddings_db_from_utternaces(is_test=0)
[ "signal_processing.extract_spectrograms_from_utterances", "speaker_verification_lstm_model.extract_embedding", "os.makedirs", "speaker_verfier.get_single_speaker_embeddings_from_call_center_call", "librosa.core.load", "numpy.mean", "configuration.get_config", "os.path.join", "os.listdir", "numpy.c...
[((320, 332), 'configuration.get_config', 'get_config', ([], {}), '()\n', (330, 332), False, 'from configuration import get_config\n'), ((708, 737), 'os.listdir', 'os.listdir', (['utterances_folder'], {}), '(utterances_folder)\n', (718, 737), False, 'import os\n'), ((1112, 1184), 'signal_processing.extract_spectrograms_from_utterances', 'signal_processing.extract_spectrograms_from_utterances', (['voice_utterances'], {}), '(voice_utterances)\n', (1166, 1184), False, 'import signal_processing\n'), ((1643, 1681), 'numpy.concatenate', 'np.concatenate', (['speaker_frames'], {'axis': '(0)'}), '(speaker_frames, axis=0)\n', (1657, 1681), True, 'import numpy as np\n'), ((2168, 2197), 'os.listdir', 'os.listdir', (['config.calls_path'], {}), '(config.calls_path)\n', (2178, 2197), False, 'import os\n'), ((3344, 3377), 'os.listdir', 'os.listdir', (['config.utterance_path'], {}), '(config.utterance_path)\n', (3354, 3377), False, 'import os\n'), ((2224, 2273), 'os.path.join', 'os.path.join', (['config.calls_path', 'single_call_file'], {}), '(config.calls_path, single_call_file)\n', (2236, 2273), False, 'import os\n'), ((2407, 2495), 'speaker_verfier.get_single_speaker_embeddings_from_call_center_call', 'speaker_verfier.get_single_speaker_embeddings_from_call_center_call', (['call_file_path'], {}), '(\n call_file_path)\n', (2474, 2495), False, 'import speaker_verfier\n'), ((2609, 2662), 'os.makedirs', 'os.makedirs', (['config.embeddings_db_path'], {'exist_ok': '(True)'}), '(config.embeddings_db_path, exist_ok=True)\n', (2620, 2662), False, 'import os\n'), ((3411, 3469), 'os.path.join', 'os.path.join', (['config.utterance_path', 'single_speaker_folder'], {}), '(config.utterance_path, single_speaker_folder)\n', (3423, 3469), False, 'import os\n'), ((3608, 3680), 'speaker_verification_lstm_model.extract_embedding', 'speaker_verification_lstm_model.extract_embedding', (['single_speaker_frames'], {}), '(single_speaker_frames)\n', (3657, 3680), False, 'import speaker_verification_lstm_model\n'), ((3995, 4048), 'os.makedirs', 'os.makedirs', (['config.embeddings_db_path'], {'exist_ok': '(True)'}), '(config.embeddings_db_path, exist_ok=True)\n', (4006, 4048), False, 'import os\n'), ((765, 819), 'os.path.join', 'os.path.join', (['utterances_folder', 'single_utterance_file'], {}), '(utterances_folder, single_utterance_file)\n', (777, 819), False, 'import os\n'), ((851, 905), 'os.path.join', 'os.path.join', (['utterances_folder', 'single_utterance_file'], {}), '(utterances_folder, single_utterance_file)\n', (863, 905), False, 'import os\n'), ((969, 1013), 'librosa.core.load', 'librosa.core.load', (['utterance_path', 'config.sr'], {}), '(utterance_path, config.sr)\n', (986, 1013), False, 'import librosa\n'), ((2679, 2734), 'os.path.join', 'os.path.join', (['config.embeddings_db_path', '"""embedding_db"""'], {}), "(config.embeddings_db_path, 'embedding_db')\n", (2691, 2734), False, 'import os\n'), ((3707, 3749), 'numpy.mean', 'np.mean', (['single_speaker_embeddings'], {'axis': '(0)'}), '(single_speaker_embeddings, axis=0)\n', (3714, 3749), True, 'import numpy as np\n'), ((4065, 4120), 'os.path.join', 'os.path.join', (['config.embeddings_db_path', '"""embedding_db"""'], {}), "(config.embeddings_db_path, 'embedding_db')\n", (4077, 4120), False, 'import os\n')]
import os import csv import numpy as np import cv2 from albumentations import (ToGray, OneOf, Compose, RandomBrightnessContrast, RandomGamma, GaussianBlur, MotionBlur, ToSepia, InvertImg, RandomSnow, RandomSunFlare, RandomRain, RandomShadow, HueSaturationValue, HorizontalFlip) from albumentations import BboxParams from keras.utils import Sequence from matplotlib import pyplot as plt def strong_aug(p=0.6): return Compose([ RandomShadow(shadow_roi=(0, 0, 1, 1), p=0.75), OneOf([ MotionBlur(), GaussianBlur() ]), OneOf([ ToGray(), ToSepia() ]), OneOf([ InvertImg(), RandomBrightnessContrast(brightness_limit=0.75, p=0.75), RandomGamma(), HueSaturationValue() ], p=0.75) ], bbox_params=BboxParams("pascal_voc", label_fields=["category_id"], min_area=0.0, min_visibility=0.0), p=p) class CSVGenerator(Sequence): def __init__(self, annotations_path, classes_path, img_height, img_width, batch_size, augs): self.classes_path = classes_path self.annotations_path = annotations_path self.annotations = {} self.imgs_list = [] self.out_height = img_height self.out_width = img_width self.augs = augs self.clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8)) self.classes = {} self.num_classes = 0 with open(self.classes_path, 'r') as f: csv_reader = csv.reader(f) for row in csv_reader: self.classes[row[0]] = int(row[1]) self.num_classes += 1 with open(self.annotations_path, 'r') as f: csv_reader = csv.reader(f) for row in csv_reader: if row[0] not in self.annotations: self.annotations[row[0]] = [] xmin = -1 ymin = -1 xmax = -1 ymax = -1 if row[1] == '': xmin = -1 else: xmin = int(row[1]) if row[2] == '': ymin = -1 else: ymin = int(row[2]) if row[3] == '': xmax = -1 else: xmax = int(row[3]) if row[4] == '': ymax = -1 else: ymax = int(row[4]) class_id = 0 annotation = [xmin, ymin, xmax, ymax, class_id] self.annotations[row[0]].append(annotation) self.imgs_list = list(self.annotations.keys()) self.img_height = img_height self.img_width = img_width self.batch_size = batch_size def __len__(self): return int(len(self.imgs_list) / self.batch_size) def __getitem__(self, idx): batch = self.imgs_list[idx * self.batch_size : (idx + 1) * self.batch_size] imgs = np.empty((self.batch_size, self.img_height, self.img_width, 3), dtype=np.float32) batch_centers = np.zeros((self.batch_size, self.out_height, self.out_width, self.num_classes + 2), dtype=np.float32) for i in range(len(batch)): img = cv2.imread(batch[i], cv2.IMREAD_COLOR) if img is None: print(batch[i]) orig_h = img.shape[0] orig_w = img.shape[1] annotations = [] for ann in self.annotations[batch[i]]: annotations.append(ann.copy()) img = cv2.resize(img, dsize=(self.img_width, self.img_height), interpolation=cv2.INTER_AREA) img_h = img.shape[0] img_w = img.shape[1] img_scale_h = orig_h / img.shape[0] img_scale_w = orig_w / img.shape[1] for j in range(len(annotations)): annotations[j][0] = int(np.round(annotations[j][0] / img_scale_w)) annotations[j][1] = int(np.round(annotations[j][1] / img_scale_h)) annotations[j][2] = int(np.round(annotations[j][2] / img_scale_w)) annotations[j][3] = int(np.round(annotations[j][3] / img_scale_h)) if self.augs is not None: boxes = [] category_ids = [] for j in range(len(annotations)): boxes.append([annotations[j][0], annotations[j][1], annotations[j][2], annotations[j][3]]) category_ids.append(annotations[j][4]) data = {'image': img, 'bboxes': boxes, 'category_id':category_ids} augmented = self.augs(**data) img = augmented['image'] #img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #img = self.clahe.apply(img) #img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) #img = np.reshape(img, (img.shape[0], img.shape[1], 1)) img = img.astype(np.float32) img /= 255. imgs[i] = img if self.augs is not None: annotations = [] for j in range(len(augmented['bboxes'])): annotations.append([int(np.round(augmented['bboxes'][j][0])), int(np.round(augmented['bboxes'][j][1])), int(np.round(augmented['bboxes'][j][2])), int(np.round(augmented['bboxes'][j][3])), augmented['category_id'][j]]) centers = np.zeros((self.out_height, self.out_width, self.num_classes), dtype=np.float32) scales = np.zeros((self.out_height, self.out_width, 2), dtype=np.float32) for j, bbox in enumerate(annotations): #orig_bbox = bbox.copy() #cv2.rectangle(img, (orig_bbox[0], orig_bbox[1]), (orig_bbox[2], orig_bbox[3]), (0, 255, 0), 2) #bbox = [int(np.round(bbox[0])), int(np.round(bbox[1])), int(np.round(bbox[2])), int(np.round(bbox[3])), int(bbox[4])] if (bbox[0] == 0) or (bbox[1] == 0) or (bbox[2] == 0) or (bbox[3] == 0) or (bbox[2] - bbox[0] == 0) or (bbox[3] - bbox[1] == 0): continue center_x = int((bbox[2] + bbox[0]) / 2) if center_x == self.out_width: center_x -= 1 center_y = int((bbox[3] + bbox[1]) / 2) if center_y >= self.out_height: center_y = self.out_height - 1 h = bbox[3] - bbox[1] sc_h = h / img_h if sc_h > 1.0: sc_h = 1.0 w = bbox[2] - bbox[0] sc_w = w / img_w if sc_w > 1.0: sc_w = 1.0 xmin = int(bbox[0]-1) xmax = int(bbox[2]-1) ymin = int(bbox[1]-1) ymax = int(bbox[3]-1) if ymax >= centers.shape[0]: ymax = centers.shape[0] - 1 if xmax >= centers.shape[1]: xmax = centers.shape[1] - 1 rhmin = -int(h/2) rhmax = int(h/2) rwmin = -int(w/2) rwmax = int(w/2) if h % 2 != 0: rhmax = int(h/2) + 1 if w % 2 != 0: rwmax = int(w/2) + 1 y, x = np.ogrid[rhmin:rhmax,rwmin:rwmax] e = np.exp(-((x*x/(2*(w/12.0)*(w/12.0)) + (y*y/(2*(h/12.0)*(h/12.0)))))) tmp = np.zeros_like(centers) tmp[ymin:ymax, xmin:xmax, 0] = e centers = np.where(tmp > centers, tmp, centers) #for x in range(xmin, xmax + 1): # for y in range(ymin, ymax + 1): # conf = np.exp((-1.0) * ( # (np.square(x - center_x)/(2.0 * (w / 3.))) + # (np.square(y - center_y)/(2.0 * (h / 3.))) # )) # if conf > centers[y, x, int(bbox[4])]: # centers[y, x, int(bbox[4])] = conf centers[int(center_y-1), int(center_x-1), 0] = 1.0 scales[int(center_y-1), int(center_x-1), 0] = sc_h scales[int(center_y-1), int(center_x-1), 1] = sc_w #cv2.imshow('tester', tester1) #cv2.waitKey() batch_centers[i] = np.concatenate([centers, scales], axis=2) #print(labels.shape) return imgs, batch_centers if __name__ == '__main__': gen = CSVGenerator('train.csv', 'class.csv', 640, 1024, 1, None) for i in range(2583): imgs, centers = gen.__getitem__(i) plt.imshow(centers[0, :, :, 3]) plt.show() print(np.sum(centers[0, :, :, 3])) print(np.count_nonzero(centers[0, :, :, 3]))
[ "csv.reader", "numpy.sum", "numpy.empty", "albumentations.RandomShadow", "numpy.exp", "numpy.round", "albumentations.MotionBlur", "numpy.zeros_like", "matplotlib.pyplot.imshow", "albumentations.ToGray", "cv2.resize", "matplotlib.pyplot.show", "albumentations.ToSepia", "albumentations.Rando...
[((1426, 1477), 'cv2.createCLAHE', 'cv2.createCLAHE', ([], {'clipLimit': '(2.0)', 'tileGridSize': '(8, 8)'}), '(clipLimit=2.0, tileGridSize=(8, 8))\n', (1441, 1477), False, 'import cv2\n'), ((3163, 3249), 'numpy.empty', 'np.empty', (['(self.batch_size, self.img_height, self.img_width, 3)'], {'dtype': 'np.float32'}), '((self.batch_size, self.img_height, self.img_width, 3), dtype=np.\n float32)\n', (3171, 3249), True, 'import numpy as np\n'), ((3269, 3374), 'numpy.zeros', 'np.zeros', (['(self.batch_size, self.out_height, self.out_width, self.num_classes + 2)'], {'dtype': 'np.float32'}), '((self.batch_size, self.out_height, self.out_width, self.\n num_classes + 2), dtype=np.float32)\n', (3277, 3374), True, 'import numpy as np\n'), ((9044, 9075), 'matplotlib.pyplot.imshow', 'plt.imshow', (['centers[0, :, :, 3]'], {}), '(centers[0, :, :, 3])\n', (9054, 9075), True, 'from matplotlib import pyplot as plt\n'), ((9084, 9094), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (9092, 9094), True, 'from matplotlib import pyplot as plt\n'), ((439, 484), 'albumentations.RandomShadow', 'RandomShadow', ([], {'shadow_roi': '(0, 0, 1, 1)', 'p': '(0.75)'}), '(shadow_roi=(0, 0, 1, 1), p=0.75)\n', (451, 484), False, 'from albumentations import ToGray, OneOf, Compose, RandomBrightnessContrast, RandomGamma, GaussianBlur, MotionBlur, ToSepia, InvertImg, RandomSnow, RandomSunFlare, RandomRain, RandomShadow, HueSaturationValue, HorizontalFlip\n'), ((847, 939), 'albumentations.BboxParams', 'BboxParams', (['"""pascal_voc"""'], {'label_fields': "['category_id']", 'min_area': '(0.0)', 'min_visibility': '(0.0)'}), "('pascal_voc', label_fields=['category_id'], min_area=0.0,\n min_visibility=0.0)\n", (857, 939), False, 'from albumentations import BboxParams\n'), ((1606, 1619), 'csv.reader', 'csv.reader', (['f'], {}), '(f)\n', (1616, 1619), False, 'import csv\n'), ((1823, 1836), 'csv.reader', 'csv.reader', (['f'], {}), '(f)\n', (1833, 1836), False, 'import csv\n'), ((3433, 3471), 'cv2.imread', 'cv2.imread', (['batch[i]', 'cv2.IMREAD_COLOR'], {}), '(batch[i], cv2.IMREAD_COLOR)\n', (3443, 3471), False, 'import cv2\n'), ((3759, 3850), 'cv2.resize', 'cv2.resize', (['img'], {'dsize': '(self.img_width, self.img_height)', 'interpolation': 'cv2.INTER_AREA'}), '(img, dsize=(self.img_width, self.img_height), interpolation=cv2.\n INTER_AREA)\n', (3769, 3850), False, 'import cv2\n'), ((5806, 5885), 'numpy.zeros', 'np.zeros', (['(self.out_height, self.out_width, self.num_classes)'], {'dtype': 'np.float32'}), '((self.out_height, self.out_width, self.num_classes), dtype=np.float32)\n', (5814, 5885), True, 'import numpy as np\n'), ((5907, 5971), 'numpy.zeros', 'np.zeros', (['(self.out_height, self.out_width, 2)'], {'dtype': 'np.float32'}), '((self.out_height, self.out_width, 2), dtype=np.float32)\n', (5915, 5971), True, 'import numpy as np\n'), ((8753, 8794), 'numpy.concatenate', 'np.concatenate', (['[centers, scales]'], {'axis': '(2)'}), '([centers, scales], axis=2)\n', (8767, 8794), True, 'import numpy as np\n'), ((9109, 9136), 'numpy.sum', 'np.sum', (['centers[0, :, :, 3]'], {}), '(centers[0, :, :, 3])\n', (9115, 9136), True, 'import numpy as np\n'), ((9152, 9189), 'numpy.count_nonzero', 'np.count_nonzero', (['centers[0, :, :, 3]'], {}), '(centers[0, :, :, 3])\n', (9168, 9189), True, 'import numpy as np\n'), ((7765, 7857), 'numpy.exp', 'np.exp', (['(-(x * x / (2 * (w / 12.0) * (w / 12.0)) + y * y / (2 * (h / 12.0) * (h / \n 12.0))))'], {}), '(-(x * x / (2 * (w / 12.0) * (w / 12.0)) + y * y / (2 * (h / 12.0) *\n (h / 12.0))))\n', (7771, 7857), True, 'import numpy as np\n'), ((7857, 7879), 'numpy.zeros_like', 'np.zeros_like', (['centers'], {}), '(centers)\n', (7870, 7879), True, 'import numpy as np\n'), ((7956, 7993), 'numpy.where', 'np.where', (['(tmp > centers)', 'tmp', 'centers'], {}), '(tmp > centers, tmp, centers)\n', (7964, 7993), True, 'import numpy as np\n'), ((514, 526), 'albumentations.MotionBlur', 'MotionBlur', ([], {}), '()\n', (524, 526), False, 'from albumentations import ToGray, OneOf, Compose, RandomBrightnessContrast, RandomGamma, GaussianBlur, MotionBlur, ToSepia, InvertImg, RandomSnow, RandomSunFlare, RandomRain, RandomShadow, HueSaturationValue, HorizontalFlip\n'), ((540, 554), 'albumentations.GaussianBlur', 'GaussianBlur', ([], {}), '()\n', (552, 554), False, 'from albumentations import ToGray, OneOf, Compose, RandomBrightnessContrast, RandomGamma, GaussianBlur, MotionBlur, ToSepia, InvertImg, RandomSnow, RandomSunFlare, RandomRain, RandomShadow, HueSaturationValue, HorizontalFlip\n'), ((595, 603), 'albumentations.ToGray', 'ToGray', ([], {}), '()\n', (601, 603), False, 'from albumentations import ToGray, OneOf, Compose, RandomBrightnessContrast, RandomGamma, GaussianBlur, MotionBlur, ToSepia, InvertImg, RandomSnow, RandomSunFlare, RandomRain, RandomShadow, HueSaturationValue, HorizontalFlip\n'), ((617, 626), 'albumentations.ToSepia', 'ToSepia', ([], {}), '()\n', (624, 626), False, 'from albumentations import ToGray, OneOf, Compose, RandomBrightnessContrast, RandomGamma, GaussianBlur, MotionBlur, ToSepia, InvertImg, RandomSnow, RandomSunFlare, RandomRain, RandomShadow, HueSaturationValue, HorizontalFlip\n'), ((667, 678), 'albumentations.InvertImg', 'InvertImg', ([], {}), '()\n', (676, 678), False, 'from albumentations import ToGray, OneOf, Compose, RandomBrightnessContrast, RandomGamma, GaussianBlur, MotionBlur, ToSepia, InvertImg, RandomSnow, RandomSunFlare, RandomRain, RandomShadow, HueSaturationValue, HorizontalFlip\n'), ((692, 747), 'albumentations.RandomBrightnessContrast', 'RandomBrightnessContrast', ([], {'brightness_limit': '(0.75)', 'p': '(0.75)'}), '(brightness_limit=0.75, p=0.75)\n', (716, 747), False, 'from albumentations import ToGray, OneOf, Compose, RandomBrightnessContrast, RandomGamma, GaussianBlur, MotionBlur, ToSepia, InvertImg, RandomSnow, RandomSunFlare, RandomRain, RandomShadow, HueSaturationValue, HorizontalFlip\n'), ((761, 774), 'albumentations.RandomGamma', 'RandomGamma', ([], {}), '()\n', (772, 774), False, 'from albumentations import ToGray, OneOf, Compose, RandomBrightnessContrast, RandomGamma, GaussianBlur, MotionBlur, ToSepia, InvertImg, RandomSnow, RandomSunFlare, RandomRain, RandomShadow, HueSaturationValue, HorizontalFlip\n'), ((788, 808), 'albumentations.HueSaturationValue', 'HueSaturationValue', ([], {}), '()\n', (806, 808), False, 'from albumentations import ToGray, OneOf, Compose, RandomBrightnessContrast, RandomGamma, GaussianBlur, MotionBlur, ToSepia, InvertImg, RandomSnow, RandomSunFlare, RandomRain, RandomShadow, HueSaturationValue, HorizontalFlip\n'), ((4095, 4136), 'numpy.round', 'np.round', (['(annotations[j][0] / img_scale_w)'], {}), '(annotations[j][0] / img_scale_w)\n', (4103, 4136), True, 'import numpy as np\n'), ((4178, 4219), 'numpy.round', 'np.round', (['(annotations[j][1] / img_scale_h)'], {}), '(annotations[j][1] / img_scale_h)\n', (4186, 4219), True, 'import numpy as np\n'), ((4261, 4302), 'numpy.round', 'np.round', (['(annotations[j][2] / img_scale_w)'], {}), '(annotations[j][2] / img_scale_w)\n', (4269, 4302), True, 'import numpy as np\n'), ((4344, 4385), 'numpy.round', 'np.round', (['(annotations[j][3] / img_scale_h)'], {}), '(annotations[j][3] / img_scale_h)\n', (4352, 4385), True, 'import numpy as np\n'), ((5428, 5463), 'numpy.round', 'np.round', (["augmented['bboxes'][j][0]"], {}), "(augmented['bboxes'][j][0])\n", (5436, 5463), True, 'import numpy as np\n'), ((5510, 5545), 'numpy.round', 'np.round', (["augmented['bboxes'][j][1]"], {}), "(augmented['bboxes'][j][1])\n", (5518, 5545), True, 'import numpy as np\n'), ((5592, 5627), 'numpy.round', 'np.round', (["augmented['bboxes'][j][2]"], {}), "(augmented['bboxes'][j][2])\n", (5600, 5627), True, 'import numpy as np\n'), ((5674, 5709), 'numpy.round', 'np.round', (["augmented['bboxes'][j][3]"], {}), "(augmented['bboxes'][j][3])\n", (5682, 5709), True, 'import numpy as np\n')]
from ..builder import PIPELINES from .transforms import Resize, RandomFlip, RandomCrop import numpy as np @PIPELINES.register_module() class RResize(Resize): """ Resize images & rotated bbox Inherit Resize pipeline class to handle rotated bboxes """ def __init__(self, img_scale=None, multiscale_mode='range', ratio_range=None): super(RResize, self).__init__(img_scale=img_scale, multiscale_mode=multiscale_mode, ratio_range=ratio_range, keep_ratio=True) def _resize_bboxes(self, results): for key in results.get('bbox_fields', []): bboxes = results[key] orig_shape = bboxes.shape bboxes = bboxes.reshape((-1, 5)) w_scale, h_scale, _, _ = results['scale_factor'] bboxes[:, 0] *= w_scale bboxes[:, 1] *= h_scale bboxes[:, 2:4] *= np.sqrt(w_scale * h_scale) results[key] = bboxes.reshape(orig_shape) @PIPELINES.register_module() class RRandomFlip(RandomFlip): """Flip the image & bbox & mask. If the input dict contains the key "flip", then the flag will be used, otherwise it will be randomly decided by a ratio specified in the init method. Args: flip_ratio (float, optional): The flipping probability. """ def bbox_flip(self, bboxes, img_shape, direction): """Flip bboxes horizontally or vertically. Args: bboxes(ndarray): shape (..., 5*k) img_shape(tuple): (height, width) """ assert bboxes.shape[-1] % 5 == 0 orig_shape = bboxes.shape bboxes = bboxes.reshape((-1, 5)) flipped = bboxes.copy() if direction == 'horizontal': flipped[:, 0] = img_shape[1] - bboxes[:, 0] - 1 elif direction == 'vertical': flipped[:, 1] = img_shape[0] - bboxes[:, 1] - 1 else: raise ValueError( 'Invalid flipping direction "{}"'.format(direction)) rotated_flag = (bboxes[:, 4] != -np.pi / 2) flipped[rotated_flag, 4] = -np.pi / 2 - bboxes[rotated_flag, 4] flipped[rotated_flag, 2] = bboxes[rotated_flag, 3], flipped[rotated_flag, 3] = bboxes[rotated_flag, 2] return flipped.reshape(orig_shape)
[ "numpy.sqrt" ]
[((1030, 1056), 'numpy.sqrt', 'np.sqrt', (['(w_scale * h_scale)'], {}), '(w_scale * h_scale)\n', (1037, 1056), True, 'import numpy as np\n')]
#! /usr/bin/env python import argparse import os import cv2 import numpy as np from tqdm import tqdm from preprocessing import parse_annotation from utils import * from utils import BoundBox from frontend import YOLO import json from skimage import io from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, Flatten from keras.layers import Convolution2D, MaxPooling2D from keras.utils import np_utils from keras.datasets import mnist from keras.callbacks import ModelCheckpoint from keras.callbacks import EarlyStopping import skimage.io as skio from keras.models import load_model from skimage.transform import resize os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" os.environ["CUDA_VISIBLE_DEVICES"]="0" argparser = argparse.ArgumentParser( description='Train and validate YOLO_v2 model on any dataset') argparser.add_argument( '-c', '--conf', help='path to configuration file') argparser.add_argument( '-w', '--weights', help='path to pretrained weights') argparser.add_argument( '-i', '--input', help='path to an image or an video (mp4 format)') def load_live_dead_model(save_path): model = load_model(save_path) print(model) return model def resize_images(images,new_shape): n = images.shape[0] out = [] #print(np.max(images[0])) for k in range(0,n): i = resize(images[k],new_shape,mode='reflect',preserve_range = True) #print(np.max(i)) #exit() out = out + [i] out = np.array(out) out = out.reshape(n,1,new_shape[0],new_shape[1]) return out def get_cell_status(images,model): #eval_Images = np.asarray(images) #images = np.array(images) #print(images.shape) X_eval = images.reshape(images.shape[0],1,100,100) shape = model.input.shape if shape[1] == 1: channel_order = "channels_first" input_size = (int(shape[2]),int(shape[3])) else: channel_order = "channels_last" input_size = (int(shape[1]),int(shape[2])) X_eval = np.moveaxis(X_eval,1,3) w=input_size[1] h=input_size[0] if w != 100 and h != 100: X_eval = resize_images(images,(h,w)) X_eval = X_eval / 65535 pred = model.predict(X_eval) #print(len(pred)) status = pred[:,0] >= 0.5 return status def remove_dead_cells(images,model,boxes): if boxes == None: return boxes status = get_cell_status(images,model) out_box = [] for box,test in zip(boxes,status): if test: out_box.append(box) return out_box def remove_dead_cells2(image,model,boxes): #check cells over all timepoints if boxes == None: return boxes out_box = [] for box in boxes: images = get_images2(image,box,100) status = get_cell_status(images,model) if any(status): #if it was alive at some timepoint out_box.append(box) return out_box def get_dead_cells(images,model,boxes): if boxes == None: return boxes status = get_cell_status(images,model) out_box = [] for box,test in zip(boxes,status): if test == False: out_box.append(box) return out_box def make_output_image(cell_images): #will make a final image that all the cell_image timecources can be placed into h = cell_images.shape[1] w = cell_images.shape[2] z = cell_images.shape[0] out = np.zeros((h*z,w),dtype = np.uint16) for k in range(0,z): out[k*h:(k+1)*h,0:w] = cell_images[k] return out def scanImage(image,yolo,config): height = image.shape[0] width = image.shape[1] inc = 416 step = 316 boxes2 = [] for yPos in range(0,height,step): for xPos in range(0,width, step): minx = 50 maxx = 366 miny = 50 maxy = 366 if xPos + inc >= width: minx = xPos + 50 xPos = width - inc minx = minx - xPos maxx = 416 if yPos + inc >= height: miny = yPos + 50 yPos = height - inc miny = miny - yPos maxy = 416 if xPos == 0: xmin = 0 if yPos == 0: ymin = 0 image2 = image[yPos:yPos + inc,xPos:xPos + inc] #draw_boxes(image2, boxes, config['model']['labels']) #print("Shape " + str(image2.shape[1])) boxes = yolo.predict(image2) #boxes = filter_boxes(xPos,yPos,image2,boxes,Q1x,Q1y) boxes = filter_boxes2(xPos,yPos,image2,boxes,minx,maxx,miny,maxy) #boxes = remove_edge_boxes(xPos,yPos,image2,image,boxes) boxes = reshape_boxes(xPos,yPos,image2,image,boxes) boxes2 = boxes2 + boxes #image2 = draw_boxes(image2, boxes, config['model']['labels']) #image[yPos:yPos + inc,xPos:xPos + inc] = image2 #(tensorflow) C:\Users\UMW\Desktop\YOLO\basic-yolo-keras-master>python predict.py -c config.json -w full_yolo_cells.h5 -i C:/Users/UMW/Desktop/YOLO/basic-yolo-keras-master/images/C2-1.tif print("Box len " + str(len(boxes2))) boxes2 = sort_boxes(boxes2) print("Sorted Box len " + str(len(boxes2))) boxes2 = remove_overlap(image,boxes2) print("overlap filtered Box len " + str(len(boxes2))) return boxes2 def find_cells(file,yolo,qa_path,config,cell_path,image_name,live_dead,data_writer): #yolo is the model, image is the first image int he stack, write_path is where the image with boxes will be written,config is the model info,cell_path is where the cells will be dumped for classification image = cv2.imread(file) unclassified_cells = scanImage(image,yolo,config) if len(unclassified_cells) == 0: print("no cells") return image16 = io.imread(file) cell_images = get_images(image16[0],unclassified_cells,100) #dead_cells = get_dead_cells(cell_images,live_dead,unclassified_cells) #dead_images = get_images(image16[0],dead_cells,100) classified_cells = remove_dead_cells(cell_images,live_dead,unclassified_cells) if len(classified_cells) == 0: print("no cells") return out_image = draw_boxes(np.copy(image), unclassified_cells, config['model']['labels']) out_image2 = draw_boxes(np.copy(image), classified_cells, config['model']['labels']) cv2.imwrite(qa_path + image_name +'_uc.tif',out_image) cv2.imwrite(qa_path + image_name +'_cl.tif',out_image2) cell_number = 1 time = 1 all_images= get_images2(image16,classified_cells,100) status = get_cell_status(all_images,live_dead) write_status(qa_path + image_name + '.csv',status,image16.shape[0]) montage = get_montages(image16,classified_cells,100) large_montage = make_output_image(montage) io.imsave(qa_path + image_name + "montage.tif",large_montage) write_data(image_name,data_writer,status,image16.shape[0]) #write_boxes(unclassified_cells, qa_path + image_name + '.csv',image) ''' for cell in all_images: io.imsave(cell_path + image_name +'_c_' + str(cell_number) + '_t_' + str(time) +'.tif',cell) time = time + 1 if time > image16.shape[0]: cell_number += 1 time = 1 ''' #for cell in dead_images: # io.imsave(cell_path + image_name + str(cell_number) +'.tif',cell) # cell_number += 1 def process_directory(image_path,output_path,yolo,config,qa_path,live_dead): files = os.listdir(image_path) #files = files[26:] data_writer,csvfile = prepare_data(qa_path + "Data.csv") for f in tqdm(files): #image = cv2.imread(image_path + f) print(f) file = os.path.basename(f) image_name = os.path.splitext(file)[0] find_cells(image_path + f, yolo,qa_path,config,output_path,image_name,live_dead,data_writer) csvfile.close() def _main_(args): config_path = args.conf weights_path = args.weights image_path = args.input with open(config_path) as config_buffer: config = json.load(config_buffer) ############################### # Make the model ############################### yolo = YOLO(architecture = config['model']['architecture'], input_size = config['model']['input_size'], labels = config['model']['labels'], max_box_per_image = config['model']['max_box_per_image'], anchors = config['model']['anchors']) ############################### # Load trained weights ############################### print(weights_path) yolo.load_weights(weights_path) ############################### # Predict bounding boxes ############################### if image_path[-4:] == '.mp4': video_out = image_path[:-4] + '_detected' + image_path[-4:] video_reader = cv2.VideoCapture(image_path) nb_frames = int(video_reader.get(cv2.CAP_PROP_FRAME_COUNT)) frame_h = int(video_reader.get(cv2.CAP_PROP_FRAME_HEIGHT)) frame_w = int(video_reader.get(cv2.CAP_PROP_FRAME_WIDTH)) video_writer = cv2.VideoWriter(video_out, cv2.VideoWriter_fourcc(*'MPEG'), 50.0, (frame_w, frame_h)) for i in tqdm(range(nb_frames)): _, image = video_reader.read() boxes = yolo.predict(image) image = draw_boxes(image, boxes, config['model']['labels']) video_writer.write(np.uint8(image)) video_reader.release() video_writer.release() else: #image = cv2.imread(image_path) output_path = "/content/gdrive/My Drive/Publication/unclassified/" qa_path = "/content/gdrive/My Drive/Publication/qa/" image_path = "/content/gdrive/My Drive/Publication/images/" #image_path = "V:/Anthony/12.26.17_transfection_started_viewing12.28/Stacks_aligned/" #image_path = "V:/Anthony/12.12.17_12.13.17_transfections_384wellFalcon/12.12.17transfectionPlateA/plateAStacksAligned/" #image_path = "V:/Anthony/11.14.17 and 11.15 transfections/11.14.17 transfection PlateD Arbez Method/11.14.17plateD aligned/" image_path = "/content/StitchedImages/" ld_model_path = "/content/LDModel/LDVGG19.h5" image_path = args.input #boxes = yolo.predict(image) #image = scanImage(image,yolo,config) #image = draw_boxes(image, boxes, config['model']['labels']) #find_cells(yolo,image,"fill",config,ip,"test") #print(len(boxes), 'boxes are found') live_dead = load_live_dead_model(ld_model_path) process_directory(image_path,output_path,yolo,config,qa_path,live_dead) #cv2.imwrite(image_path[:-4] + '_detected' + image_path[-4:], image) if __name__ == '__main__': args = argparser.parse_args() _main_(args)
[ "keras.models.load_model", "numpy.moveaxis", "argparse.ArgumentParser", "frontend.YOLO", "cv2.VideoWriter_fourcc", "skimage.transform.resize", "numpy.copy", "cv2.imwrite", "skimage.io.imsave", "skimage.io.imread", "tqdm.tqdm", "numpy.uint8", "os.path.basename", "os.listdir", "json.load",...
[((779, 870), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Train and validate YOLO_v2 model on any dataset"""'}), "(description=\n 'Train and validate YOLO_v2 model on any dataset')\n", (802, 870), False, 'import argparse\n'), ((1223, 1244), 'keras.models.load_model', 'load_model', (['save_path'], {}), '(save_path)\n', (1233, 1244), False, 'from keras.models import load_model\n'), ((1575, 1588), 'numpy.array', 'np.array', (['out'], {}), '(out)\n', (1583, 1588), True, 'import numpy as np\n'), ((3612, 3649), 'numpy.zeros', 'np.zeros', (['(h * z, w)'], {'dtype': 'np.uint16'}), '((h * z, w), dtype=np.uint16)\n', (3620, 3649), True, 'import numpy as np\n'), ((6026, 6042), 'cv2.imread', 'cv2.imread', (['file'], {}), '(file)\n', (6036, 6042), False, 'import cv2\n'), ((6194, 6209), 'skimage.io.imread', 'io.imread', (['file'], {}), '(file)\n', (6203, 6209), False, 'from skimage import io\n'), ((6764, 6820), 'cv2.imwrite', 'cv2.imwrite', (["(qa_path + image_name + '_uc.tif')", 'out_image'], {}), "(qa_path + image_name + '_uc.tif', out_image)\n", (6775, 6820), False, 'import cv2\n'), ((6824, 6881), 'cv2.imwrite', 'cv2.imwrite', (["(qa_path + image_name + '_cl.tif')", 'out_image2'], {}), "(qa_path + image_name + '_cl.tif', out_image2)\n", (6835, 6881), False, 'import cv2\n'), ((7216, 7278), 'skimage.io.imsave', 'io.imsave', (["(qa_path + image_name + 'montage.tif')", 'large_montage'], {}), "(qa_path + image_name + 'montage.tif', large_montage)\n", (7225, 7278), False, 'from skimage import io\n'), ((7926, 7948), 'os.listdir', 'os.listdir', (['image_path'], {}), '(image_path)\n', (7936, 7948), False, 'import os\n'), ((8050, 8061), 'tqdm.tqdm', 'tqdm', (['files'], {}), '(files)\n', (8054, 8061), False, 'from tqdm import tqdm\n'), ((8667, 8899), 'frontend.YOLO', 'YOLO', ([], {'architecture': "config['model']['architecture']", 'input_size': "config['model']['input_size']", 'labels': "config['model']['labels']", 'max_box_per_image': "config['model']['max_box_per_image']", 'anchors': "config['model']['anchors']"}), "(architecture=config['model']['architecture'], input_size=config[\n 'model']['input_size'], labels=config['model']['labels'],\n max_box_per_image=config['model']['max_box_per_image'], anchors=config[\n 'model']['anchors'])\n", (8671, 8899), False, 'from frontend import YOLO\n'), ((1430, 1495), 'skimage.transform.resize', 'resize', (['images[k]', 'new_shape'], {'mode': '"""reflect"""', 'preserve_range': '(True)'}), "(images[k], new_shape, mode='reflect', preserve_range=True)\n", (1436, 1495), False, 'from skimage.transform import resize\n'), ((2127, 2152), 'numpy.moveaxis', 'np.moveaxis', (['X_eval', '(1)', '(3)'], {}), '(X_eval, 1, 3)\n', (2138, 2152), True, 'import numpy as np\n'), ((6606, 6620), 'numpy.copy', 'np.copy', (['image'], {}), '(image)\n', (6613, 6620), True, 'import numpy as np\n'), ((6698, 6712), 'numpy.copy', 'np.copy', (['image'], {}), '(image)\n', (6705, 6712), True, 'import numpy as np\n'), ((8142, 8161), 'os.path.basename', 'os.path.basename', (['f'], {}), '(f)\n', (8158, 8161), False, 'import os\n'), ((8527, 8551), 'json.load', 'json.load', (['config_buffer'], {}), '(config_buffer)\n', (8536, 8551), False, 'import json\n'), ((9424, 9452), 'cv2.VideoCapture', 'cv2.VideoCapture', (['image_path'], {}), '(image_path)\n', (9440, 9452), False, 'import cv2\n'), ((8184, 8206), 'os.path.splitext', 'os.path.splitext', (['file'], {}), '(file)\n', (8200, 8206), False, 'import os\n'), ((9744, 9775), 'cv2.VideoWriter_fourcc', 'cv2.VideoWriter_fourcc', (["*'MPEG'"], {}), "(*'MPEG')\n", (9766, 9775), False, 'import cv2\n'), ((10131, 10146), 'numpy.uint8', 'np.uint8', (['image'], {}), '(image)\n', (10139, 10146), True, 'import numpy as np\n')]
import sys import random import numpy as np import json # Bestandsnamen voor de huidige telling, doorgegeven voorkeuren, nieuwe telling & selectie output tellingIn, voorkeurIn, tellingOut, selectieOut = sys.argv[1:] # test telling vanuit csv # tellingData = np.genfromtxt("telling.csv", names=True, dtype=None, delimiter=',', encoding=None).T # telling = {} # for row in tellingData: # telling[row[0]] = {"HR": bool(row[1]), "n": int(row[2])} # Import telling vanuit json naar dictionary f = open(tellingIn, 'r') telling = json.loads(f.read()) f.close() # Import hardrijders en pas aan waar nodig in de dictionary f = open("hardrijders.txt") hardrijders = f.read().split('\n') for hr in hardrijders: if hr in telling: telling[hr]["HR"] = True else: telling[hr] = {"HR": True, "n": 0} f.close() # Import donateurs f = open("donateurs.txt") donateurs = f.read().split('\n') f.close() # Import aanmeldingen # kolommen: Voornaam, Achternaam, email, maandag?, donderdag?, zondag? TjassersData = np.genfromtxt(voorkeurIn, names=True, dtype=None, delimiter=',', encoding=None) # recreanten en hardrijders splitsen, zodat die uniform verdeeld kunnen worden over de dagen # waar nodig voeg toe aan telling dictionary recreantenData = [] hardrijdersData = [] for Tjasser in TjassersData: Tjasser = list(Tjasser) email = Tjasser[2] if email in telling: if telling[email]["HR"]: hardrijdersData.append(Tjasser) else: recreantenData.append(Tjasser) else: telling[email] = {"HR": False, 'n': 0} recreantenData.append(Tjasser) # sorteer op volgorde van aantal keren geschaatst, zodat het zo uniform mogelijk verdeeld wordt over de dagen def sorteer(Data): Data = np.array(Data) emails = Data.T[2] nschaatsen = np.array([telling[email]['n'] for email in emails]) inds = nschaatsen.argsort() return Data[inds] recreantenData = sorteer(recreantenData) hardrijdersData = sorteer(hardrijdersData) TjassersMaandag = [] TjassersDonderdag = [] TjassersZondag = [] zf = 22.0/27.0 # compensatiefactor omdat er meer plek is op zondag # verdeel Tjassers zo gelijk mogelijk over de dagen for data in (list(recreantenData), list(hardrijdersData)): for Tjasser in data: m, d, z = Tjasser[3:] m = int(m) d = int(d) z = int(z) if m: TjassersMaandag.append(Tjasser) if d: TjassersDonderdag.append(Tjasser) if z: TjassersZondag.append(Tjasser) # Aanpassing 14 nov.: # onderstaand algorithme deelt elke Tjasser maar op één dag in, dat lijkt me bij nader inzien een onnodige beperking # # Als de Tjasser maar op een dag kan, deel hem daar in # if m+d+z == 1: # if m: # TjassersMaandag.append(Tjasser) # elif d: # TjassersDonderdag.append(Tjasser) # elif z: # TjassersZondag.append(Tjasser) # # else: # mN, dN, zN = len(TjassersMaandag), len(TjassersDonderdag), len(TjassersZondag)*zf # # # Als de Tjasser op de dag met de minste mensen kan, deel hem daar in # if min(mN, dN, zN) == mN and m: # TjassersMaandag.append(Tjasser) # elif min(mN, dN, zN) == dN and d: # TjassersDonderdag.append(Tjasser) # elif min(mN, dN, zN) == zN and z: # TjassersZondag.append(Tjasser) # # Probeer het anders op de dag waar niet de meeste mensen komen # elif max(mN, dN, zN) != mN and m: # TjassersMaandag.append(Tjasser) # elif max(mN, dN, zN) != dN and d: # TjassersDonderdag.append(Tjasser) # elif z: # TjassersZondag.append(Tjasser) # # Opvanger voor het geval twee dagen even vol zitten # else: # TjassersDonderdag.append(Tjasser) # wat als mensen 0 voorkeursdagen hebben ingevuld? dan komen ze ook hier terecht. Antwoord: mensen met 0 voorkeursdagen kunnen niet trainen en schrijven zich dus ook niet in... hopelijk print("Totaal aantal Tjassers:", len(TjassersData)) print("Pool maandag:", len(TjassersMaandag)) print("Pool donderdag:", len(TjassersDonderdag)) print("Pool zondag:", len(TjassersZondag), "Gecorrigeerd:", len(TjassersZondag)*zf) geselecteerdenMaandag = [] geselecteerdenDonderdag = [] geselecteerdenZondag = [] gesnDagen = (geselecteerdenMaandag, geselecteerdenDonderdag, geselecteerdenZondag) TjassersDagen = (TjassersMaandag, TjassersDonderdag, TjassersZondag) plekkenDagen = (22, 22, 27) hf = 3/2 #compensatiefactor voor hardrijders for geselecteerden, Tjassers, plekken in zip(gesnDagen, TjassersDagen, plekkenDagen): while len(geselecteerden) < plekken: # Zet de Tjassers elke ronde op willekeurige volgorde, dit is eigenlijk de enige loting random.shuffle(Tjassers) tried = [] while len(Tjassers) > 1: # pak de eerstvolgende Tjasser om te vergelijken met de rest Tjasser = Tjassers.pop() email = Tjasser[2] # donateurs mogen maar 3x schaatsen if email in donateurs and telling[email]['n'] >= 3: continue # vind wat het minst aantal keren geschaatst is van de rest emails = [T[2] for T in Tjassers] nschaatsen = [telling[e]['n'] for e in emails] minN = float(min(nschaatsen)) # Compenseer minst aantal keren geschaatst voor hardrijders if telling[email]["HR"]: minN *= hf # Vergelijk het aantal keren geschaatst van de Tjasser met het minste aantal van de rest if telling[email]['n'] <= minN: geselecteerden.append(Tjasser) telling[email]['n'] += 1 if len(geselecteerden) == plekken: break else: tried.append(Tjasser) # begin opnieuw als de hele groep geprobeerd is maar er nog plekken zijn Tjassers += tried # opvanger voor als de dag niet vol zit if len(Tjassers) == 1 and len(geselecteerden) < plekken: geselecteerden.append(Tjassers[0]) telling[Tjassers[0][2]]['n'] += 1 # Output de selectie f = open(selectieOut, 'w') for geselecteerden, dag in zip(gesnDagen, ("maandag", "donderdag", "zondag")): f.write("Geselecteerden " + dag + ":\n") for geselecteerde in geselecteerden: f.write(", ".join(geselecteerde[0:3]) + '\n') f.write("\n-------------------------------\n\n") f.close() # Export nieuwe telling s = json.dumps(telling) f = open(tellingOut, 'w') f.write(s) f.close()
[ "random.shuffle", "numpy.array", "numpy.genfromtxt", "json.dumps" ]
[((1062, 1141), 'numpy.genfromtxt', 'np.genfromtxt', (['voorkeurIn'], {'names': '(True)', 'dtype': 'None', 'delimiter': '""","""', 'encoding': 'None'}), "(voorkeurIn, names=True, dtype=None, delimiter=',', encoding=None)\n", (1075, 1141), True, 'import numpy as np\n'), ((6878, 6897), 'json.dumps', 'json.dumps', (['telling'], {}), '(telling)\n', (6888, 6897), False, 'import json\n'), ((1818, 1832), 'numpy.array', 'np.array', (['Data'], {}), '(Data)\n', (1826, 1832), True, 'import numpy as np\n'), ((1875, 1926), 'numpy.array', 'np.array', (["[telling[email]['n'] for email in emails]"], {}), "([telling[email]['n'] for email in emails])\n", (1883, 1926), True, 'import numpy as np\n'), ((5098, 5122), 'random.shuffle', 'random.shuffle', (['Tjassers'], {}), '(Tjassers)\n', (5112, 5122), False, 'import random\n')]
import pandas as pd import numpy as np from statsmodels.tsa.stattools import kpss from statsmodels.tsa.stattools import adfuller def get_ts_strength(tt, st, rt): trend_strength = np.var(rt)/np.var(tt+rt) trend_strength = max([0, 1-trend_strength]) seasonal_strength = np.var(rt)/np.var(st+rt) seasonal_strength = max([0, 1-seasonal_strength]) sdf = pd.DataFrame([trend_strength, seasonal_strength], columns=['Strength'], index=['Trend', 'Seasonal']) return sdf def adf_test(timeseries, autolag='AIC',**kwargs): dftest = adfuller(timeseries, autolag=autolag, **kwargs) df = pd.Series(dftest[0:4], index=['Test Statistic','p-value','#Lags Used','Number of Observations Used']) for key,value in dftest[4].items(): df['Critical Value (%s)'%key] = value return df.to_frame() def kpss_test(timeseries, regression='c', nlags="auto", **kwargs): kpsstest = kpss(timeseries, regression=regression, nlags=nlags, **kwargs) kpss_output = pd.Series(kpsstest[0:3], index=['Test Statistic','p-value','Lags Used']) for key,value in kpsstest[3].items(): kpss_output['Critical Value (%s)'%key] = value return kpss_output.to_frame()
[ "pandas.DataFrame", "statsmodels.tsa.stattools.adfuller", "statsmodels.tsa.stattools.kpss", "pandas.Series", "numpy.var" ]
[((383, 487), 'pandas.DataFrame', 'pd.DataFrame', (['[trend_strength, seasonal_strength]'], {'columns': "['Strength']", 'index': "['Trend', 'Seasonal']"}), "([trend_strength, seasonal_strength], columns=['Strength'],\n index=['Trend', 'Seasonal'])\n", (395, 487), True, 'import pandas as pd\n'), ((593, 640), 'statsmodels.tsa.stattools.adfuller', 'adfuller', (['timeseries'], {'autolag': 'autolag'}), '(timeseries, autolag=autolag, **kwargs)\n', (601, 640), False, 'from statsmodels.tsa.stattools import adfuller\n'), ((650, 758), 'pandas.Series', 'pd.Series', (['dftest[0:4]'], {'index': "['Test Statistic', 'p-value', '#Lags Used', 'Number of Observations Used']"}), "(dftest[0:4], index=['Test Statistic', 'p-value', '#Lags Used',\n 'Number of Observations Used'])\n", (659, 758), True, 'import pandas as pd\n'), ((965, 1027), 'statsmodels.tsa.stattools.kpss', 'kpss', (['timeseries'], {'regression': 'regression', 'nlags': 'nlags'}), '(timeseries, regression=regression, nlags=nlags, **kwargs)\n', (969, 1027), False, 'from statsmodels.tsa.stattools import kpss\n'), ((1046, 1120), 'pandas.Series', 'pd.Series', (['kpsstest[0:3]'], {'index': "['Test Statistic', 'p-value', 'Lags Used']"}), "(kpsstest[0:3], index=['Test Statistic', 'p-value', 'Lags Used'])\n", (1055, 1120), True, 'import pandas as pd\n'), ((191, 201), 'numpy.var', 'np.var', (['rt'], {}), '(rt)\n', (197, 201), True, 'import numpy as np\n'), ((202, 217), 'numpy.var', 'np.var', (['(tt + rt)'], {}), '(tt + rt)\n', (208, 217), True, 'import numpy as np\n'), ((289, 299), 'numpy.var', 'np.var', (['rt'], {}), '(rt)\n', (295, 299), True, 'import numpy as np\n'), ((300, 315), 'numpy.var', 'np.var', (['(st + rt)'], {}), '(st + rt)\n', (306, 315), True, 'import numpy as np\n')]
""" Utility functions """ import csv import torch import os import warnings import numpy as np from skimage import io, img_as_uint from tqdm import tqdm from zipfile import ZipFile from Evaluator import shift_cPSNR from DataLoader import ImageSet def read_baseline_CPSNR(path): """ Reads the baseline cPSNR scores from `path`. Args: filePath: str, path/filename of the baseline cPSNR scores Returns: scores: dict, of {'imagexxx' (str): score (float)} """ scores = dict() with open(path, 'r') as file: reader = csv.reader(file, delimiter=' ') for row in reader: scores[row[0].strip()] = float(row[1].strip()) return scores def get_imageset_directories(data_dir): """ Returns a list of paths to directories, one for every imageset in `data_dir`. Args: data_dir: str, path/dir of the dataset Returns: imageset_dirs: list of str, imageset directories """ imageset_dirs = [] for channel_dir in ['RED', 'NIR']: path = os.path.join(data_dir, channel_dir) for imageset_name in os.listdir(path): imageset_dirs.append(os.path.join(path, imageset_name)) return imageset_dirs class collateFunction(): """ Util class to create padded batches of data. """ def __init__(self, min_L=32): """ Args: min_L: int, pad length """ self.min_L = min_L def __call__(self, batch): return self.collateFunction(batch) def collateFunction(self, batch): """ Custom collate function to adjust a variable number of low-res images. Args: batch: list of imageset Returns: padded_lr_batch: tensor (B, min_L, W, H), low resolution images alpha_batch: tensor (B, min_L), low resolution indicator (0 if padded view, 1 otherwise) hr_batch: tensor (B, W, H), high resolution images hm_batch: tensor (B, W, H), high resolution status maps isn_batch: list of imageset names """ lr_batch = [] # batch of low-resolution views alpha_batch = [] # batch of indicators (0 if padded view, 1 if genuine view) hr_batch = [] # batch of high-resolution views hm_batch = [] # batch of high-resolution status maps isn_batch = [] # batch of site names train_batch = True for imageset in batch: lrs = imageset['lr'] L, H, W = lrs.shape if L >= self.min_L: # pad input to top_k lr_batch.append(lrs[:self.min_L]) alpha_batch.append(torch.ones(self.min_L)) else: pad = torch.zeros(self.min_L - L, H, W) lr_batch.append(torch.cat([lrs, pad], dim=0)) alpha_batch.append(torch.cat([torch.ones(L), torch.zeros(self.min_L - L)], dim=0)) hr = imageset['hr'] if train_batch and hr is not None: hr_batch.append(hr) else: train_batch = False hm_batch.append(imageset['hr_map']) isn_batch.append(imageset['name']) padded_lr_batch = torch.stack(lr_batch, dim=0) alpha_batch = torch.stack(alpha_batch, dim=0) if train_batch: hr_batch = torch.stack(hr_batch, dim=0) hm_batch = torch.stack(hm_batch, dim=0) return padded_lr_batch, alpha_batch, hr_batch, hm_batch, isn_batch def get_sr_and_score(imset, model, min_L=16): ''' Super resolves an imset with a given model. Args: imset: imageset model: HRNet, pytorch model min_L: int, pad length Returns: sr: tensor (1, C_out, W, H), super resolved image scPSNR: float, shift cPSNR score ''' if imset.__class__ is ImageSet: collator = collateFunction(min_L=min_L) lrs, alphas, hrs, hr_maps, names = collator([imset]) elif isinstance(imset, tuple): # imset is a tuple of batches lrs, alphas, hrs, hr_maps, names = imset device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') lrs = lrs.float().to(device) alphas = alphas.float().to(device) sr = model(lrs, alphas)[:, 0] sr = sr.detach().cpu().numpy()[0] if len(hrs) > 0: scPSNR = shift_cPSNR(sr=np.clip(sr, 0, 1), hr=hrs.numpy()[0], hr_map=hr_maps.numpy()[0]) else: scPSNR = None return sr, scPSNR def generate_submission_file(model, imset_dataset, out='../submission'): ''' USAGE: generate_submission_file [path to testfolder] [name of the submission folder] EXAMPLE: generate_submission_file data submission ''' print('generating solutions: ', end='', flush='True') os.makedirs(out, exist_ok=True) for imset in tqdm(imset_dataset): folder = imset['name'] sr, _ = get_sr_and_score(imset, model) sr = img_as_uint(sr) # normalize and safe resulting image in temporary folder (complains on low contrast if not suppressed) with warnings.catch_warnings(): warnings.simplefilter("ignore") io.imsave(os.path.join(out, folder + '.png'), sr) print('*', end='', flush='True') print('\narchiving: ') sub_archive = out + '/submission.zip' # name of submission archive zf = ZipFile(sub_archive, mode='w') try: for img in os.listdir(out): if not img.startswith('imgset'): # ignore the .zip-file itself continue zf.write(os.path.join(out, img), arcname=img) print('*', end='', flush='True') finally: zf.close() print('\ndone. The submission-file is found at {}. Bye!'.format(sub_archive))
[ "torch.ones", "tqdm.tqdm", "csv.reader", "zipfile.ZipFile", "os.makedirs", "torch.stack", "skimage.img_as_uint", "warnings.simplefilter", "torch.cat", "numpy.clip", "torch.cuda.is_available", "warnings.catch_warnings", "torch.zeros", "os.path.join", "os.listdir" ]
[((4847, 4878), 'os.makedirs', 'os.makedirs', (['out'], {'exist_ok': '(True)'}), '(out, exist_ok=True)\n', (4858, 4878), False, 'import os\n'), ((4897, 4916), 'tqdm.tqdm', 'tqdm', (['imset_dataset'], {}), '(imset_dataset)\n', (4901, 4916), False, 'from tqdm import tqdm\n'), ((5437, 5467), 'zipfile.ZipFile', 'ZipFile', (['sub_archive'], {'mode': '"""w"""'}), "(sub_archive, mode='w')\n", (5444, 5467), False, 'from zipfile import ZipFile\n'), ((565, 596), 'csv.reader', 'csv.reader', (['file'], {'delimiter': '""" """'}), "(file, delimiter=' ')\n", (575, 596), False, 'import csv\n'), ((1050, 1085), 'os.path.join', 'os.path.join', (['data_dir', 'channel_dir'], {}), '(data_dir, channel_dir)\n', (1062, 1085), False, 'import os\n'), ((1115, 1131), 'os.listdir', 'os.listdir', (['path'], {}), '(path)\n', (1125, 1131), False, 'import os\n'), ((3224, 3252), 'torch.stack', 'torch.stack', (['lr_batch'], {'dim': '(0)'}), '(lr_batch, dim=0)\n', (3235, 3252), False, 'import torch\n'), ((3275, 3306), 'torch.stack', 'torch.stack', (['alpha_batch'], {'dim': '(0)'}), '(alpha_batch, dim=0)\n', (3286, 3306), False, 'import torch\n'), ((5009, 5024), 'skimage.img_as_uint', 'img_as_uint', (['sr'], {}), '(sr)\n', (5020, 5024), False, 'from skimage import io, img_as_uint\n'), ((5496, 5511), 'os.listdir', 'os.listdir', (['out'], {}), '(out)\n', (5506, 5511), False, 'import os\n'), ((3355, 3383), 'torch.stack', 'torch.stack', (['hr_batch'], {'dim': '(0)'}), '(hr_batch, dim=0)\n', (3366, 3383), False, 'import torch\n'), ((3407, 3435), 'torch.stack', 'torch.stack', (['hm_batch'], {'dim': '(0)'}), '(hm_batch, dim=0)\n', (3418, 3435), False, 'import torch\n'), ((4135, 4160), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (4158, 4160), False, 'import torch\n'), ((5150, 5175), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {}), '()\n', (5173, 5175), False, 'import warnings\n'), ((5189, 5220), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""'], {}), "('ignore')\n", (5210, 5220), False, 'import warnings\n'), ((1166, 1199), 'os.path.join', 'os.path.join', (['path', 'imageset_name'], {}), '(path, imageset_name)\n', (1178, 1199), False, 'import os\n'), ((2736, 2769), 'torch.zeros', 'torch.zeros', (['(self.min_L - L)', 'H', 'W'], {}), '(self.min_L - L, H, W)\n', (2747, 2769), False, 'import torch\n'), ((4372, 4389), 'numpy.clip', 'np.clip', (['sr', '(0)', '(1)'], {}), '(sr, 0, 1)\n', (4379, 4389), True, 'import numpy as np\n'), ((5243, 5277), 'os.path.join', 'os.path.join', (['out', "(folder + '.png')"], {}), "(out, folder + '.png')\n", (5255, 5277), False, 'import os\n'), ((5635, 5657), 'os.path.join', 'os.path.join', (['out', 'img'], {}), '(out, img)\n', (5647, 5657), False, 'import os\n'), ((2672, 2694), 'torch.ones', 'torch.ones', (['self.min_L'], {}), '(self.min_L)\n', (2682, 2694), False, 'import torch\n'), ((2802, 2830), 'torch.cat', 'torch.cat', (['[lrs, pad]'], {'dim': '(0)'}), '([lrs, pad], dim=0)\n', (2811, 2830), False, 'import torch\n'), ((2878, 2891), 'torch.ones', 'torch.ones', (['L'], {}), '(L)\n', (2888, 2891), False, 'import torch\n'), ((2893, 2920), 'torch.zeros', 'torch.zeros', (['(self.min_L - L)'], {}), '(self.min_L - L)\n', (2904, 2920), False, 'import torch\n')]
import astropy.constants as const import astropy.units as u import numpy as np import scipy.interpolate import xarray as xr from .base import ModelOutput from psipy.io import read_mas_file, get_mas_variables __all__ = ['MASOutput'] # A mapping from unit names to their units, and factors the data needs to be # multiplied to get them into these units. _vunit = [u.km / u.s, 481.37] _bunit = [u.G, 2.205] _junit = [u.A / u.m**2, 2.267e4] _mas_units = {'vr': _vunit, 'vt': _vunit, 'vp': _vunit, 'va': _vunit, 'br': _bunit, 'bt': _bunit, 'bp': _bunit, 'bmag': _bunit, 'rho': [u.N / u.cm**3, 1.67e-16 / 1.67e-24], 't': [u.K, 2.804e7], 'p': [u.Pa, 3.875717e-2], 'jr': _junit, 'jt': _junit, 'jp': _junit } class MASOutput(ModelOutput): """ The results from a single run of MAS. This is a storage object that contains a number of `Variable` objects. It is designed to be used like:: mas_output = MASOutput('directory') br = mas_output['br'] Notes ----- Variables are loaded on demand. To see the list of available variables use `MASOutput.variables`, and to see the list of already loaded variables use `MASOutput.loaded_variables`. """ def get_unit(self, var): return _mas_units[var] def get_variables(self): return get_mas_variables(self.path) def load_file(self, var): return read_mas_file(self.path, var) def __repr__(self): return f'psipy.model.mas.MASOutput("{self.path}")' def __str__(self): return f"MAS output in directory {self.path}\n" + super().__str__() def cell_centered_v(self, extra_phi_coord=False): """ Get the velocity vector at the cell centres. Because the locations of the vector component outputs Parameters ---------- extra_phi_coord: bool If `True`, add an extra phi slice. """ if not set(['vr', 'vt', 'vp']) <= set(self.variables): raise RuntimeError('MAS output must have the vr, vt, vp variables loaded') # Interpolate new radial coordiantes new_rcoord = self['vr'].r_coords vt = scipy.interpolate.interp1d(self['vt'].r_coords, self['vt'].data, axis=2)(new_rcoord) vp = scipy.interpolate.interp1d(self['vp'].r_coords, self['vp'].data, axis=2)(new_rcoord) # Interpolate new theta coordinates new_tcoord = self['vt'].theta_coords vr = scipy.interpolate.interp1d(self['vr'].theta_coords, self['vr'].data, axis=1)(new_tcoord) vp = scipy.interpolate.interp1d(self['vp'].theta_coords, vp, axis=1)(new_tcoord) # Don't need to interpolate phi coords, but get a copy new_pcoord = self['vr'].phi_coords if extra_phi_coord: dphi = np.mean(np.diff(new_pcoord)) assert np.allclose(new_pcoord[0] + 2 * np.pi, new_pcoord[-1] + dphi) new_pcoord = np.append(new_pcoord, new_pcoord[-1] + dphi) vp = np.append(vp, vp[0:1, :, :], axis=0) vt = np.append(vt, vt[0:1, :, :], axis=0) vr = np.append(vr, vr[0:1, :, :], axis=0) return xr.DataArray(np.stack([vp, vt, vr], axis=-1), dims=['phi', 'theta', 'r', 'component'], coords=[new_pcoord, new_tcoord, new_rcoord, ['vp', 'vt', 'vr']])
[ "numpy.stack", "numpy.allclose", "psipy.io.read_mas_file", "numpy.append", "numpy.diff", "psipy.io.get_mas_variables" ]
[((1496, 1524), 'psipy.io.get_mas_variables', 'get_mas_variables', (['self.path'], {}), '(self.path)\n', (1513, 1524), False, 'from psipy.io import read_mas_file, get_mas_variables\n'), ((1571, 1600), 'psipy.io.read_mas_file', 'read_mas_file', (['self.path', 'var'], {}), '(self.path, var)\n', (1584, 1600), False, 'from psipy.io import read_mas_file, get_mas_variables\n'), ((3332, 3393), 'numpy.allclose', 'np.allclose', (['(new_pcoord[0] + 2 * np.pi)', '(new_pcoord[-1] + dphi)'], {}), '(new_pcoord[0] + 2 * np.pi, new_pcoord[-1] + dphi)\n', (3343, 3393), True, 'import numpy as np\n'), ((3420, 3464), 'numpy.append', 'np.append', (['new_pcoord', '(new_pcoord[-1] + dphi)'], {}), '(new_pcoord, new_pcoord[-1] + dphi)\n', (3429, 3464), True, 'import numpy as np\n'), ((3482, 3518), 'numpy.append', 'np.append', (['vp', 'vp[0:1, :, :]'], {'axis': '(0)'}), '(vp, vp[0:1, :, :], axis=0)\n', (3491, 3518), True, 'import numpy as np\n'), ((3536, 3572), 'numpy.append', 'np.append', (['vt', 'vt[0:1, :, :]'], {'axis': '(0)'}), '(vt, vt[0:1, :, :], axis=0)\n', (3545, 3572), True, 'import numpy as np\n'), ((3590, 3626), 'numpy.append', 'np.append', (['vr', 'vr[0:1, :, :]'], {'axis': '(0)'}), '(vr, vr[0:1, :, :], axis=0)\n', (3599, 3626), True, 'import numpy as np\n'), ((3656, 3687), 'numpy.stack', 'np.stack', (['[vp, vt, vr]'], {'axis': '(-1)'}), '([vp, vt, vr], axis=-1)\n', (3664, 3687), True, 'import numpy as np\n'), ((3292, 3311), 'numpy.diff', 'np.diff', (['new_pcoord'], {}), '(new_pcoord)\n', (3299, 3311), True, 'import numpy as np\n')]
import time import numpy as np import scipy.sparse as sp import ed_geometry as geom import ed_symmetry as symm import ed_base class spinSystem(ed_base.ed_base): #nbasis = 2 nspecies = 1 # index that "looks" the same as the spatial index from the perspective of constructing operators. E.g. for # fermions we have spatial index + spin index, but it is convenient to treat this like an enlarged set of # spatial indices. This is the reason it is called "nspin" ng = np.array([[0, 0], [0, 1]]) nr = np.array([[1, 0], [0, 0]]) nplus = 0.5 * np.array([[1, 1], [1, 1]]) nminus = 0.5 * np.array([[1, -1], [-1, 1]]) swap_op = np.array([[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]]) def __init__(self, geometry, jx=0.0, jy=0.0, jz=0.0, hx=0.0, hy=0.0, hz=0.0, use_ryd_detunes=0, spin=0.5): """ This class implements a spin system with the following Hamiltonian: H = \sum_<i, j, \alpha=x,y,z> 0.5 * j_alpha * \sigma_i^\alpha * \sigma_j^\alpha - \sum_{i, \alpha=x,y,z} 0.5 * h_\alpha * \sigma_i^\alpha If write this in terms of spin operators instead of Pauli matrices, S_i^\alpha = 0.5 * \sigma_i^\alpha H = \sum_<i, j, \alpha=x,y,z> 2 * j_\alpha * S_i^\alpha * \S_j^\alpha - \sum_{i, \alpha=x,y,z} h_\alpha * S_i^\alpha :param geometry: :param jx: :param jy: :param jz: :param hx: :param hy: :param hz: :param use_ryd_detunes: """ # TODO: update this to allow easy use of Heisenberg or Rydberg self.nbasis = int(2 * spin + 1) self.splus = self.get_splus(spin) self.sminus = self.get_sminus(spin) self.sz = self.get_sz(spin) self.sy = self.get_sy(spin) self.sx = self.get_sx(spin) ed_base.ed_base.__init__(self, geometry) self.jx = self.get_interaction_mat(jx) self.jy = self.get_interaction_mat(jy) self.jz = self.get_interaction_mat(jz) self.hx = self.get_field_mat(hx) self.hy = self.get_field_mat(hy) self.hz = self.get_field_mat(hz) if use_ryd_detunes: self.rydberg_detunings = self.get_rydberg_detunes(self.jz) self.hz = self.hz + self.rydberg_detunings def get_splus(self, spin): """ S^+ |s m> = sqrt( (s-m) * (s+m+1) ) |s (m+1)> :param spin: :return: """ ms = np.arange(spin - 1, -spin - 1, -1) return sp.diags(np.sqrt((spin - ms) * (spin + ms + 1)), -1) def get_sminus(self, spin): """ S^- |s m> = sqrt( (s+m) * (s_m+1) ) |s (m-1)> :param spin: :return: """ ms = np.arange(spin, -spin, -1) return sp.diags(np.sqrt((spin + ms) * (spin - ms + 1)), 1) def get_sx(self, spin): """ s^x = 0.5 * (s^+ + s^-) :param spin: :return: """ return 0.5 * (self.get_splus(spin) + self.get_sminus(spin)) def get_sy(self, spin): """ s^y = 0.5 * (s^+ - s^-) :param spin: :return: """ return 0.5 * (self.get_splus(spin) - self.get_sminus(spin)) / 1j def get_sz(self, spin): """ S^z |s m> = m |s m> :param spin: :return: """ return sp.diags(np.arange(spin, -spin - 1, -1)) def get_interaction_mat_c6(self, C6, cutoff_dist=1.5): """ Get interaction matrix by using real space distances. This allows, e.g. anisotropic interactions_4. :param xlocs: :param ylocs: :param C6: :param xscale: :param yscale: :param cutoff_dist: :return: """ distmat = np.sqrt(self.geometry.site_distances_reduced_x ** 2 + self.geometry.site_distances_reduced_y ** 2) jmat = np.zeros(distmat.shape) jmat[distmat != 0] = C6*np.power(np.reciprocal(distmat[distmat != 0]), 6) return jmat def get_interaction_mat(self, j): """ Get interaction matrix, which is a matrix of size nsites x nsites where m[ii, jj] gives the interaction strength between sites ii and jj :param j: integer giving uniform interaction strength for all sites :return: """ if isinstance(j, (int, float)): j_mat = j * self.geometry.adjacency_mat * self.geometry.phase_mat elif isinstance(j, np.ndarray): if j.shape == (self.geometry.nsites, self.geometry.nsites): j_mat = j elif j.size == self.geometry.nsites: j_mat = np.diag(j[:-1], 1) + np.diag(j[-1], -1) j_mat[0, self.geometry.nsites - 1] = j[-1] else: raise Exception('j should be nsites x nsites matrix or a list of size nsites') else: raise Exception('j was not integer, float, or numpy array.') return j_mat def get_field_mat(self, h): if isinstance(h, (int, float)): h_mat = h * np.ones(self.geometry.nsites) elif isinstance(h, np.ndarray): if h.size != self.geometry.nsites: raise Exception('j was a numpy array, but size did not match geometry.') h_mat = h else: raise Exception('j was not integer, float, or numpy array.') return h_mat def get_state_vects(self, print_results=False): """ Generate a description of the basis states in the full tensor product of spins space :param nsites: Int, total number of sites in the system :param print_results: :return: NumPy array of size 2 ** nsites x nsites describing each basis state in the tensor product spin space. Each row represents the spins for a given state according to |up> = 1, |down> = 0 on the site corresponding to the column index. """ if print_results: tstart = time.perf_counter() nsites = self.geometry.nsites StateSpinLabels = sp.csc_matrix((2 ** nsites, nsites)) # csc 0.7s vs. csr 9s. As expected for vertical slicing. RootMat = sp.csc_matrix([[1], [0]]) for ii in range(0, nsites): # simple pattern to create the columns of the matrix. It goes like this: the last column alternates as # 1,0,1,0,... the second to last column goes 1,1,0,0,1,1,..., all the way to the first, which goes, # 1,1,...,1,0,...0 (is first half ones, second half zeros). StateSpinLabels[:, ii] = sp.kron(np.ones([2 ** ii, 1]), sp.kron(RootMat, np.ones([2 ** (nsites - ii - 1), 1]))) # self.StateSpinLabels = StateSpinLabels StateSpinLabels.eliminate_zeros() if print_results: tend = time.perf_counter() print("Took %0.2f s to generate state vector labels" % (tend - tstart)) return StateSpinLabels def get_state_parity(self, print_results=False): """ Get parity of basis states :param nsites: :param nstates: :param print_results: :return: """ if print_results: tstart = time.perf_counter() StateParity = np.mod(np.array(self.get_state_vects(self.geometry.nsites, 2 ** self.geometry.nsites).sum(1)), 2) if print_results: tend = time.perf_counter() print("get_state_parity took %0.2fs" % (tend - tstart)) return StateParity # ######################## # Build and diagonalize H # ######################## def get_rydberg_detunes(self, jsmat): """ Generate rydberg detuning terms for each site. :param nsites: Int, number of sites :param jsmat: nsites x nsites NumPy array :return: rydberg_detunings, an nsites NumPy array """ nsites = self.geometry.nsites rydberg_detunings = np.zeros(nsites, dtype = np.complex) for ii in range(0, nsites): rydberg_detunings[ii] = 0.5 * np.sum(jsmat[ii, :]) rydberg_detunings = -2.0*rydberg_detunings # need this to keep same term in Hamiltonian had before. if not (rydberg_detunings.imag > 10 ** -14).any(): rydberg_detunings = rydberg_detunings.real return rydberg_detunings def createH(self, projector=None, print_results=False): """ :param nsites: Int, total number of sites :param detunes: Int or NumPy array of length nsites, specifying detuning (longitudinal field) at each site :param rabis: Int or NumPy array of length nsites, specifying rabi frequency (transverse field) at each site :param jsmat: NumPy array of size nsites x nsites x 3. Interaction term between sites ii, jj is jsmat[ii,jj,kk]*sigma^kk_i*sigma^kk_j where kk = x, y, or z. :param projector: :param print_results: :return: """ #TODO: if I do twisted boundary conditions can I still only sum over ii > jj? nsites = self.geometry.nsites nstates = self.nbasis ** nsites if print_results: tstart = time.perf_counter() if projector is None: projector = sp.eye(nstates) nstates = projector.shape[0] # transverse and longitudinal field terms H = sp.csr_matrix((nstates, nstates)) for ii in range(0, nsites): if self.hx[ii] != 0: # THESE factors of two related to the fact I've written things in terms of the pauli matrices, instead # of spin matrix = 0.5 * pauli_matrices # H = H - 0.5 * self.hx[ii] * projector * self.get_single_site_op(ii, 0, self.pauli_x, format="boson") * \ # projector.conj().transpose() H = H - self.hx[ii] * projector * self.get_single_site_op(ii, 0, self.sx, format="boson") * \ projector.conj().transpose() if self.hy[ii] != 0: # H = H - 0.5 * self.hy[ii] * projector * self.get_single_site_op(ii, 0, self.pauli_y, format="boson") * \ # projector.conj().transpose() H = H - self.hy[ii] * projector * self.get_single_site_op(ii, 0, self.sy, format="boson") * \ projector.conj().transpose() if self.hz[ii] != 0: # H = H - 0.5 * self.hz[ii] * projector * self.get_single_site_op(ii, 0, self.pauli_z, format="boson") * \ # projector.conj().transpose() H = H - self.hz[ii] * projector * self.get_single_site_op(ii, 0, self.sz, format="boson") * \ projector.conj().transpose() # interaction terms if nsites > 1: for ii in range(0, nsites): for jj in range(0, nsites): if ii > jj: # to avoid repeating elements jx = self.jx[ii, jj] jy = self.jy[ii, jj] jz = self.jz[ii, jj] # factors of 2 => 0.5 * \sum sigma*sigma = 2 * \sum s*s if jx != 0: # H = H + 0.5 * jx * projector * \ # self.get_two_site_op(ii, 0, jj, 0, self.pauli_x, self.pauli_x, format="boson") * \ # projector.conj().transpose() H = H + 2 * jx * projector * \ self.get_two_site_op(ii, 0, jj, 0, self.sx, self.sx, format="boson") * \ projector.conj().transpose() if jy != 0: # H = H + 0.5 * jy * projector * \ # self.get_two_site_op(ii, 0, jj, 0, self.pauli_y, self.pauli_y, format="boson") * \ # projector.conj().transpose() H = H + 2 * jy * projector * \ self.get_two_site_op(ii, 0, jj, 0, self.sy, self.sy, format="boson") * \ projector.conj().transpose() if jz != 0: # H = H + 0.5 * jz * projector * \ # self.get_two_site_op(ii, 0, jj, 0, self.pauli_z, self.pauli_z, format="boson") * \ # projector.conj().transpose() H = H + 2 * jz * projector * \ self.get_two_site_op(ii, 0, jj, 0, self.sz, self.sz, format="boson") * \ projector.conj().transpose() if print_results: tend = time.perf_counter() print("Constructing H of size %d x %d took %0.2f s" % (H.shape[0], H.shape[0], tend - tstart)) return H def get_interaction_op(self, projector=None): pass def get_field_op(self, projector=None): pass # ######################## # miscellanoues functions # ######################## def find_special_states(self, xsites, ysites, number_left2right_top2bottom=0): """ Generate state vectors for special states. Currently, the ferromagnetic states, anti-ferromagnetic states, and plus and minus product states :param xsites: :param ysites: :param number_left2right_top2bottom: :return: """ NSites = self.geometry.nsites#XSites * YSites NStates = 2 ** NSites AllUpStateInd = 0 # AllUpState = np.zeros([NStates,1]) # AllUpState[AllUpStateInd] = 1 AllUpState = sp.csr_matrix((np.array([1]), (np.array([AllUpStateInd]), np.array([0]))), shape=(NStates, 1)) AllDnStateInd = NStates - 1 # AllDnState = np.zeros([NStates,1]) # AllDnState[AllDnStateInd] = 1 AllDnState = sp.csr_matrix((np.array([1]), (np.array([AllDnStateInd]), np.array([0]))), shape=(NStates, 1)) if ((xsites % 2) or not number_left2right_top2bottom) and (NSites > 1): # if Xsites is odd if NSites % 2: # if nsites is odd AFMState1Ind = (1 + NStates) / 3 - 1 else: # if nsites is even AFMState1Ind = (2 + NStates) / 3 - 1 AFMState2Ind = NStates - AFMState1Ind else: print('AFM State finder not implemented for even number of sites in X-direction when using ' \ 'conventional number, or not implemented for only a single site. Will return FM states instead') AFMState1Ind = 0 AFMState2Ind = NStates - 1 AFMState1 = sp.csr_matrix((np.array([1]), (np.array([AFMState1Ind]), np.array([0]))), shape=(NStates, 1)) AFMState2 = sp.csr_matrix((np.array([1]), (np.array([AFMState2Ind]), np.array([0]))), shape=(NStates, 1)) AllPlusState = np.ones([NStates, 1]) / np.sqrt(NStates) AllMinusState = sp.csr_matrix.dot(self.get_allsite_op(self.pauli_z), AllPlusState) SymmExcState = np.zeros([NStates, 1]) for ii in range(0, NSites): SymmExcState[2 ** NSites - 2 ** ii - 1] = 1 / np.sqrt(NSites) Rows = 2 ** NSites - np.power(2, np.arange(0, NSites)) - 1 Cols = np.zeros([NSites]) Vals = np.ones([NSites]) / np.sqrt(NSites) SymmExcState = sp.csr_matrix((Vals, (Rows, Cols)), shape=(NStates, 1)) states = sp.hstack((AllUpState, AllDnState, AFMState1, AFMState2, AllPlusState, AllMinusState, SymmExcState)) Descriptions = ['AllUp', 'AllDn', 'AFM1', 'AFM2', 'AllPlus', 'AllMinus', 'SymmExc'] return states.tocsr(), Descriptions # ######################## # Calculate operators # ######################## def get_npairs_op(self, corr_sites_conn): """ Get operator that counts number of pairs of rydbergs. (i.e. spin-ups on NN sites) :param corr_sites_conn: :param nsites: :return: """ nsites = self.geometry.nsites op = 0 xs, ys = np.meshgrid(range(0, nsites), range(0, nsites)) i_corr = xs[xs > ys] j_corr = ys[xs > ys] i_corr = i_corr[corr_sites_conn == 1] j_corr = j_corr[corr_sites_conn == 1] for ii in range(0, len(i_corr)): op = op + self.get_two_site_op(i_corr[ii], 0, j_corr[ii], 0, self.nr, self.nr, format="boson") return op def get_allsite_op(self, op_onsite): """ operators which are product of nsites copies of a single operator. :param nsites: Int, total number of sites :param op_onsite: :return: op_full, sparse COO matrix """ op_full = sp.coo_matrix(1) op_onsite = sp.coo_matrix(op_onsite) for ff in range(0, self.geometry.nsites): op_full = sp.kron(op_full, op_onsite, 'coo') return op_full def get_sum_op(self, op): """ Get operator that counts the number of spins ups/rydberg excitations :param nsites: Int, total number of sites :param op: 2x2 operator acting on each site :return: OpMat, sparse matrix """ species_index = 0 return ed_base.ed_base.get_sum_op(self, op, species_index, format="boson", print_results=False) def get_swap_up_down_op(self): swapped_state = self.nstates - 1 - np.arange(self.nstates) op = sp.csc_matrix((np.ones(self.nstates), swapped_state, np.arange(self.nstates+1))) return op def get_swap_op(self, site1, site2, species=0): """ Construct an operator that swaps the states of two sites. This version does not require any recursion. :param site1: Integer value specifying first site :param site2: Integer value specifying second site :param species: Integer specifying species (should always be zero in this case) :return: Sparse matrix """ return self.get_two_site_op(site1, species, site2, species, self.pauli_plus, self.pauli_minus, format="boson") + \ self.get_two_site_op(site1, species, site2, species, self.pauli_minus, self.pauli_plus, format="boson") + \ 0.5 * sp.eye(self.nstates) + \ 0.5 * self.get_two_site_op(site1, species, site2, species, self.pauli_z, self.pauli_z, format="boson")
[ "ed_base.ed_base.get_sum_op", "scipy.sparse.kron", "numpy.sum", "scipy.sparse.eye", "numpy.zeros", "time.perf_counter", "numpy.ones", "numpy.reciprocal", "scipy.sparse.csc_matrix", "scipy.sparse.csr_matrix", "numpy.array", "numpy.arange", "scipy.sparse.coo_matrix", "numpy.diag", "scipy.s...
[((504, 530), 'numpy.array', 'np.array', (['[[0, 0], [0, 1]]'], {}), '([[0, 0], [0, 1]])\n', (512, 530), True, 'import numpy as np\n'), ((541, 567), 'numpy.array', 'np.array', (['[[1, 0], [0, 0]]'], {}), '([[1, 0], [0, 0]])\n', (549, 567), True, 'import numpy as np\n'), ((678, 744), 'numpy.array', 'np.array', (['[[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]]'], {}), '([[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]])\n', (686, 744), True, 'import numpy as np\n'), ((587, 613), 'numpy.array', 'np.array', (['[[1, 1], [1, 1]]'], {}), '([[1, 1], [1, 1]])\n', (595, 613), True, 'import numpy as np\n'), ((634, 662), 'numpy.array', 'np.array', (['[[1, -1], [-1, 1]]'], {}), '([[1, -1], [-1, 1]])\n', (642, 662), True, 'import numpy as np\n'), ((1876, 1916), 'ed_base.ed_base.__init__', 'ed_base.ed_base.__init__', (['self', 'geometry'], {}), '(self, geometry)\n', (1900, 1916), False, 'import ed_base\n'), ((2515, 2549), 'numpy.arange', 'np.arange', (['(spin - 1)', '(-spin - 1)', '(-1)'], {}), '(spin - 1, -spin - 1, -1)\n', (2524, 2549), True, 'import numpy as np\n'), ((2789, 2815), 'numpy.arange', 'np.arange', (['spin', '(-spin)', '(-1)'], {}), '(spin, -spin, -1)\n', (2798, 2815), True, 'import numpy as np\n'), ((3847, 3950), 'numpy.sqrt', 'np.sqrt', (['(self.geometry.site_distances_reduced_x ** 2 + self.geometry.\n site_distances_reduced_y ** 2)'], {}), '(self.geometry.site_distances_reduced_x ** 2 + self.geometry.\n site_distances_reduced_y ** 2)\n', (3854, 3950), True, 'import numpy as np\n'), ((3962, 3985), 'numpy.zeros', 'np.zeros', (['distmat.shape'], {}), '(distmat.shape)\n', (3970, 3985), True, 'import numpy as np\n'), ((6193, 6229), 'scipy.sparse.csc_matrix', 'sp.csc_matrix', (['(2 ** nsites, nsites)'], {}), '((2 ** nsites, nsites))\n', (6206, 6229), True, 'import scipy.sparse as sp\n'), ((6307, 6332), 'scipy.sparse.csc_matrix', 'sp.csc_matrix', (['[[1], [0]]'], {}), '([[1], [0]])\n', (6320, 6332), True, 'import scipy.sparse as sp\n'), ((8139, 8173), 'numpy.zeros', 'np.zeros', (['nsites'], {'dtype': 'np.complex'}), '(nsites, dtype=np.complex)\n', (8147, 8173), True, 'import numpy as np\n'), ((9584, 9617), 'scipy.sparse.csr_matrix', 'sp.csr_matrix', (['(nstates, nstates)'], {}), '((nstates, nstates))\n', (9597, 9617), True, 'import scipy.sparse as sp\n'), ((15394, 15416), 'numpy.zeros', 'np.zeros', (['[NStates, 1]'], {}), '([NStates, 1])\n', (15402, 15416), True, 'import numpy as np\n'), ((15615, 15633), 'numpy.zeros', 'np.zeros', (['[NSites]'], {}), '([NSites])\n', (15623, 15633), True, 'import numpy as np\n'), ((15710, 15765), 'scipy.sparse.csr_matrix', 'sp.csr_matrix', (['(Vals, (Rows, Cols))'], {'shape': '(NStates, 1)'}), '((Vals, (Rows, Cols)), shape=(NStates, 1))\n', (15723, 15765), True, 'import scipy.sparse as sp\n'), ((15786, 15890), 'scipy.sparse.hstack', 'sp.hstack', (['(AllUpState, AllDnState, AFMState1, AFMState2, AllPlusState, AllMinusState,\n SymmExcState)'], {}), '((AllUpState, AllDnState, AFMState1, AFMState2, AllPlusState,\n AllMinusState, SymmExcState))\n', (15795, 15890), True, 'import scipy.sparse as sp\n'), ((17089, 17105), 'scipy.sparse.coo_matrix', 'sp.coo_matrix', (['(1)'], {}), '(1)\n', (17102, 17105), True, 'import scipy.sparse as sp\n'), ((17127, 17151), 'scipy.sparse.coo_matrix', 'sp.coo_matrix', (['op_onsite'], {}), '(op_onsite)\n', (17140, 17151), True, 'import scipy.sparse as sp\n'), ((17608, 17700), 'ed_base.ed_base.get_sum_op', 'ed_base.ed_base.get_sum_op', (['self', 'op', 'species_index'], {'format': '"""boson"""', 'print_results': '(False)'}), "(self, op, species_index, format='boson',\n print_results=False)\n", (17634, 17700), False, 'import ed_base\n'), ((2575, 2613), 'numpy.sqrt', 'np.sqrt', (['((spin - ms) * (spin + ms + 1))'], {}), '((spin - ms) * (spin + ms + 1))\n', (2582, 2613), True, 'import numpy as np\n'), ((2841, 2879), 'numpy.sqrt', 'np.sqrt', (['((spin + ms) * (spin - ms + 1))'], {}), '((spin + ms) * (spin - ms + 1))\n', (2848, 2879), True, 'import numpy as np\n'), ((3438, 3468), 'numpy.arange', 'np.arange', (['spin', '(-spin - 1)', '(-1)'], {}), '(spin, -spin - 1, -1)\n', (3447, 3468), True, 'import numpy as np\n'), ((6105, 6124), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (6122, 6124), False, 'import time\n'), ((6983, 7002), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (7000, 7002), False, 'import time\n'), ((7385, 7404), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (7402, 7404), False, 'import time\n'), ((7573, 7592), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (7590, 7592), False, 'import time\n'), ((9386, 9405), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (9403, 9405), False, 'import time\n'), ((9464, 9479), 'scipy.sparse.eye', 'sp.eye', (['nstates'], {}), '(nstates)\n', (9470, 9479), True, 'import scipy.sparse as sp\n'), ((12954, 12973), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (12971, 12973), False, 'import time\n'), ((15235, 15256), 'numpy.ones', 'np.ones', (['[NStates, 1]'], {}), '([NStates, 1])\n', (15242, 15256), True, 'import numpy as np\n'), ((15259, 15275), 'numpy.sqrt', 'np.sqrt', (['NStates'], {}), '(NStates)\n', (15266, 15275), True, 'import numpy as np\n'), ((15650, 15667), 'numpy.ones', 'np.ones', (['[NSites]'], {}), '([NSites])\n', (15657, 15667), True, 'import numpy as np\n'), ((15670, 15685), 'numpy.sqrt', 'np.sqrt', (['NSites'], {}), '(NSites)\n', (15677, 15685), True, 'import numpy as np\n'), ((17226, 17260), 'scipy.sparse.kron', 'sp.kron', (['op_full', 'op_onsite', '"""coo"""'], {}), "(op_full, op_onsite, 'coo')\n", (17233, 17260), True, 'import scipy.sparse as sp\n'), ((17779, 17802), 'numpy.arange', 'np.arange', (['self.nstates'], {}), '(self.nstates)\n', (17788, 17802), True, 'import numpy as np\n'), ((4028, 4064), 'numpy.reciprocal', 'np.reciprocal', (['distmat[distmat != 0]'], {}), '(distmat[distmat != 0])\n', (4041, 4064), True, 'import numpy as np\n'), ((5172, 5201), 'numpy.ones', 'np.ones', (['self.geometry.nsites'], {}), '(self.geometry.nsites)\n', (5179, 5201), True, 'import numpy as np\n'), ((6718, 6739), 'numpy.ones', 'np.ones', (['[2 ** ii, 1]'], {}), '([2 ** ii, 1])\n', (6725, 6739), True, 'import numpy as np\n'), ((8256, 8276), 'numpy.sum', 'np.sum', (['jsmat[ii, :]'], {}), '(jsmat[ii, :])\n', (8262, 8276), True, 'import numpy as np\n'), ((13947, 13960), 'numpy.array', 'np.array', (['[1]'], {}), '([1])\n', (13955, 13960), True, 'import numpy as np\n'), ((14190, 14203), 'numpy.array', 'np.array', (['[1]'], {}), '([1])\n', (14198, 14203), True, 'import numpy as np\n'), ((15015, 15028), 'numpy.array', 'np.array', (['[1]'], {}), '([1])\n', (15023, 15028), True, 'import numpy as np\n'), ((15130, 15143), 'numpy.array', 'np.array', (['[1]'], {}), '([1])\n', (15138, 15143), True, 'import numpy as np\n'), ((15513, 15528), 'numpy.sqrt', 'np.sqrt', (['NSites'], {}), '(NSites)\n', (15520, 15528), True, 'import numpy as np\n'), ((17832, 17853), 'numpy.ones', 'np.ones', (['self.nstates'], {}), '(self.nstates)\n', (17839, 17853), True, 'import numpy as np\n'), ((17870, 17897), 'numpy.arange', 'np.arange', (['(self.nstates + 1)'], {}), '(self.nstates + 1)\n', (17879, 17897), True, 'import numpy as np\n'), ((6804, 6840), 'numpy.ones', 'np.ones', (['[2 ** (nsites - ii - 1), 1]'], {}), '([2 ** (nsites - ii - 1), 1])\n', (6811, 6840), True, 'import numpy as np\n'), ((13963, 13988), 'numpy.array', 'np.array', (['[AllUpStateInd]'], {}), '([AllUpStateInd])\n', (13971, 13988), True, 'import numpy as np\n'), ((13990, 14003), 'numpy.array', 'np.array', (['[0]'], {}), '([0])\n', (13998, 14003), True, 'import numpy as np\n'), ((14206, 14231), 'numpy.array', 'np.array', (['[AllDnStateInd]'], {}), '([AllDnStateInd])\n', (14214, 14231), True, 'import numpy as np\n'), ((14233, 14246), 'numpy.array', 'np.array', (['[0]'], {}), '([0])\n', (14241, 14246), True, 'import numpy as np\n'), ((15031, 15055), 'numpy.array', 'np.array', (['[AFMState1Ind]'], {}), '([AFMState1Ind])\n', (15039, 15055), True, 'import numpy as np\n'), ((15057, 15070), 'numpy.array', 'np.array', (['[0]'], {}), '([0])\n', (15065, 15070), True, 'import numpy as np\n'), ((15146, 15170), 'numpy.array', 'np.array', (['[AFMState2Ind]'], {}), '([AFMState2Ind])\n', (15154, 15170), True, 'import numpy as np\n'), ((15172, 15185), 'numpy.array', 'np.array', (['[0]'], {}), '([0])\n', (15180, 15185), True, 'import numpy as np\n'), ((15573, 15593), 'numpy.arange', 'np.arange', (['(0)', 'NSites'], {}), '(0, NSites)\n', (15582, 15593), True, 'import numpy as np\n'), ((18620, 18640), 'scipy.sparse.eye', 'sp.eye', (['self.nstates'], {}), '(self.nstates)\n', (18626, 18640), True, 'import scipy.sparse as sp\n'), ((4743, 4761), 'numpy.diag', 'np.diag', (['j[:-1]', '(1)'], {}), '(j[:-1], 1)\n', (4750, 4761), True, 'import numpy as np\n'), ((4764, 4782), 'numpy.diag', 'np.diag', (['j[-1]', '(-1)'], {}), '(j[-1], -1)\n', (4771, 4782), True, 'import numpy as np\n')]
import os import argparse from sklearn.model_selection import train_test_split import random import numpy as np import json def read_jsonl(path): examples = [] with open(path, 'r') as f: for line in f: line = line.strip() if line: ex = json.loads(line) examples.append(ex) return examples def write_jsonl(data, path): with open(path, 'w') as f: for example in data: json_data = json.dumps(example, ensure_ascii=False) f.write(json_data + '\n') if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('-i', '--input_path', required=True) parser.add_argument('-o', '--output_path', required=True) parser.add_argument('-m', '--misinfo_path', required=True) parser.add_argument('-dm', '--dev_mids', required=True) parser.add_argument('-tm', '--test_mids', required=True) parser.add_argument('-s', '--seed', default=0, type=int) args = parser.parse_args() np.random.seed(args.seed) random.seed(args.seed) if not os.path.exists(args.output_path): os.mkdir(args.output_path) data = read_jsonl(args.input_path) with open(args.misinfo_path) as f: misinfo = json.load(f) dev_mids = set(args.dev_mids.split(',')) test_mids = set(args.test_mids.split(',')) train_misinfo = {m_id: m for m_id, m in misinfo.items() if m_id not in dev_mids and m_id not in test_mids} dev_misinfo = {m_id: m for m_id, m in misinfo.items() if m_id not in test_mids} test_misinfo = {m_id: m for m_id, m in misinfo.items()} train_data = [] dev_data = [] test_data = [] for tweet in data: found_mid = False for m_id, m_label in tweet['misinfo'].items(): if m_id in test_mids: test_data.append(tweet) found_mid = True break elif m_id in dev_mids: dev_data.append(tweet) found_mid = True break if not found_mid: train_data.append(tweet) print(f'Train size: {len(train_data)}, Dev size: {len(dev_data)}, Test size: {len(test_data)}') write_jsonl(train_data, os.path.join(args.output_path, 'train.jsonl')) with open(os.path.join(args.output_path, 'train_misinfo.json'), 'w') as f: json.dump(train_misinfo, f, indent=4) write_jsonl(dev_data, os.path.join(args.output_path, 'dev.jsonl')) with open(os.path.join(args.output_path, 'dev_misinfo.json'), 'w') as f: json.dump(dev_misinfo, f, indent=4) write_jsonl(test_data, os.path.join(args.output_path, 'test.jsonl')) with open(os.path.join(args.output_path, 'test_misinfo.json'), 'w') as f: json.dump(test_misinfo, f, indent=4)
[ "os.mkdir", "json.dump", "json.load", "numpy.random.seed", "argparse.ArgumentParser", "json.loads", "os.path.exists", "json.dumps", "random.seed", "os.path.join" ]
[((516, 541), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (539, 541), False, 'import argparse\n'), ((922, 947), 'numpy.random.seed', 'np.random.seed', (['args.seed'], {}), '(args.seed)\n', (936, 947), True, 'import numpy as np\n'), ((949, 971), 'random.seed', 'random.seed', (['args.seed'], {}), '(args.seed)\n', (960, 971), False, 'import random\n'), ((981, 1013), 'os.path.exists', 'os.path.exists', (['args.output_path'], {}), '(args.output_path)\n', (995, 1013), False, 'import os\n'), ((1017, 1043), 'os.mkdir', 'os.mkdir', (['args.output_path'], {}), '(args.output_path)\n', (1025, 1043), False, 'import os\n'), ((1130, 1142), 'json.load', 'json.load', (['f'], {}), '(f)\n', (1139, 1142), False, 'import json\n'), ((1956, 2001), 'os.path.join', 'os.path.join', (['args.output_path', '"""train.jsonl"""'], {}), "(args.output_path, 'train.jsonl')\n", (1968, 2001), False, 'import os\n'), ((2081, 2118), 'json.dump', 'json.dump', (['train_misinfo', 'f'], {'indent': '(4)'}), '(train_misinfo, f, indent=4)\n', (2090, 2118), False, 'import json\n'), ((2142, 2185), 'os.path.join', 'os.path.join', (['args.output_path', '"""dev.jsonl"""'], {}), "(args.output_path, 'dev.jsonl')\n", (2154, 2185), False, 'import os\n'), ((2263, 2298), 'json.dump', 'json.dump', (['dev_misinfo', 'f'], {'indent': '(4)'}), '(dev_misinfo, f, indent=4)\n', (2272, 2298), False, 'import json\n'), ((2323, 2367), 'os.path.join', 'os.path.join', (['args.output_path', '"""test.jsonl"""'], {}), "(args.output_path, 'test.jsonl')\n", (2335, 2367), False, 'import os\n'), ((2446, 2482), 'json.dump', 'json.dump', (['test_misinfo', 'f'], {'indent': '(4)'}), '(test_misinfo, f, indent=4)\n', (2455, 2482), False, 'import json\n'), ((408, 447), 'json.dumps', 'json.dumps', (['example'], {'ensure_ascii': '(False)'}), '(example, ensure_ascii=False)\n', (418, 447), False, 'import json\n'), ((2014, 2066), 'os.path.join', 'os.path.join', (['args.output_path', '"""train_misinfo.json"""'], {}), "(args.output_path, 'train_misinfo.json')\n", (2026, 2066), False, 'import os\n'), ((2198, 2248), 'os.path.join', 'os.path.join', (['args.output_path', '"""dev_misinfo.json"""'], {}), "(args.output_path, 'dev_misinfo.json')\n", (2210, 2248), False, 'import os\n'), ((2380, 2431), 'os.path.join', 'os.path.join', (['args.output_path', '"""test_misinfo.json"""'], {}), "(args.output_path, 'test_misinfo.json')\n", (2392, 2431), False, 'import os\n'), ((253, 269), 'json.loads', 'json.loads', (['line'], {}), '(line)\n', (263, 269), False, 'import json\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import sys import time import socket from multiprocessing import Process, Pipe #from PyQt5.QtWidgets import QListView, QAction, QWidget from PyQt5.QtWidgets import QWidget, QFileDialog from PyQt5 import QtWidgets, uic #, QtCore, QtGui from PyQt5.QtGui import QIcon import atomize.general_modules.general_functions as general import atomize.device_modules.PB_ESR_500_pro as pb_pro ###import atomize.device_modules.BH_15 as bh class MainWindow(QtWidgets.QMainWindow): """ A main window class """ def __init__(self, *args, **kwargs): """ A function for connecting actions and creating a main window """ super(MainWindow, self).__init__(*args, **kwargs) path_to_main = os.path.dirname(os.path.abspath(__file__)) gui_path = os.path.join(path_to_main,'gui/phasing_main_window.ui') icon_path = os.path.join(path_to_main, 'gui/icon_pulse.png') self.setWindowIcon( QIcon(icon_path) ) self.path = os.path.join(path_to_main, '..', 'tests/pulse_epr') self.destroyed.connect(lambda: self._on_destroyed()) # connect some actions to exit # Load the UI Page uic.loadUi(gui_path, self) # Design file self.pb = pb_pro.PB_ESR_500_Pro() ###self.bh15 = bh.BH_15() # First initialization problem # corrected directly in the module BH-15 #try: #self.bh15.magnet_setup( 3500, 0.5 ) #except BrokenPipeError: # pass # Connection of different action to different Menus and Buttons self.button_off.clicked.connect(self.turn_off) self.button_off.setStyleSheet("QPushButton {border-radius: 4px; background-color: rgb(63, 63, 97);\ border-style: outset; color: rgb(193, 202, 227);}\ QPushButton:pressed {background-color: rgb(211, 194, 78); ; border-style: inset}") self.button_stop.clicked.connect(self.dig_stop) self.button_stop.setStyleSheet("QPushButton {border-radius: 4px; background-color: rgb(63, 63, 97);\ border-style: outset; color: rgb(193, 202, 227);}\ QPushButton:pressed {background-color: rgb(211, 194, 78); ; border-style: inset}") self.button_update.clicked.connect(self.update) self.button_update.setStyleSheet("QPushButton {border-radius: 4px; background-color: rgb(63, 63, 97);\ border-style: outset; color: rgb(193, 202, 227);}\ QPushButton:pressed {background-color: rgb(211, 194, 78); ; border-style: inset}") # text labels self.errors.setStyleSheet("QPlainTextEdit { color : rgb(211, 194, 78); }") # rgb(193, 202, 227) self.label.setStyleSheet("QLabel { color : rgb(193, 202, 227); }") self.label_2.setStyleSheet("QLabel { color : rgb(193, 202, 227); }") self.label_3.setStyleSheet("QLabel { color : rgb(193, 202, 227); }") self.label_4.setStyleSheet("QLabel { color : rgb(193, 202, 227); }") self.label_5.setStyleSheet("QLabel { color : rgb(193, 202, 227); }") self.label_6.setStyleSheet("QLabel { color : rgb(193, 202, 227); }") self.label_7.setStyleSheet("QLabel { color : rgb(193, 202, 227); }") self.label_8.setStyleSheet("QLabel { color : rgb(193, 202, 227); }") self.label_9.setStyleSheet("QLabel { color : rgb(193, 202, 227); }") self.label_10.setStyleSheet("QLabel { color : rgb(193, 202, 227); }") self.label_11.setStyleSheet("QLabel { color : rgb(193, 202, 227); }") self.label_12.setStyleSheet("QLabel { color : rgb(193, 202, 227); }") self.label_13.setStyleSheet("QLabel { color : rgb(193, 202, 227); }") # Spinboxes self.P1_st.setStyleSheet("QSpinBox { color : rgb(193, 202, 227); }") #self.P1_st.lineEdit().setReadOnly( True ) # block input from keyboard self.P2_st.setStyleSheet("QSpinBox { color : rgb(193, 202, 227); }") self.P3_st.setStyleSheet("QSpinBox { color : rgb(193, 202, 227); }") self.P4_st.setStyleSheet("QSpinBox { color : rgb(193, 202, 227); }") self.P5_st.setStyleSheet("QSpinBox { color : rgb(193, 202, 227); }") self.P6_st.setStyleSheet("QSpinBox { color : rgb(193, 202, 227); }") self.P7_st.setStyleSheet("QSpinBox { color : rgb(193, 202, 227); }") self.Rep_rate.setStyleSheet("QSpinBox { color : rgb(193, 202, 227); }") self.Field.setStyleSheet("QDoubleSpinBox { color : rgb(193, 202, 227); }") self.P1_len.setStyleSheet("QSpinBox { color : rgb(193, 202, 227); }") self.P2_len.setStyleSheet("QSpinBox { color : rgb(193, 202, 227); }") self.P3_len.setStyleSheet("QSpinBox { color : rgb(193, 202, 227); }") self.P4_len.setStyleSheet("QSpinBox { color : rgb(193, 202, 227); }") self.P5_len.setStyleSheet("QSpinBox { color : rgb(193, 202, 227); }") self.P6_len.setStyleSheet("QSpinBox { color : rgb(193, 202, 227); }") self.P7_len.setStyleSheet("QSpinBox { color : rgb(193, 202, 227); }") self.P1_type.setStyleSheet("QComboBox { color : rgb(193, 202, 227); selection-color: rgb(211, 194, 78); }") self.P2_type.setStyleSheet("QComboBox { color : rgb(193, 202, 227); selection-color: rgb(211, 194, 78); }") self.P3_type.setStyleSheet("QComboBox { color : rgb(193, 202, 227); selection-color: rgb(211, 194, 78); }") self.P4_type.setStyleSheet("QComboBox { color : rgb(193, 202, 227); selection-color: rgb(211, 194, 78); }") self.P5_type.setStyleSheet("QComboBox { color : rgb(193, 202, 227); selection-color: rgb(211, 194, 78); }") self.P6_type.setStyleSheet("QComboBox { color : rgb(193, 202, 227); selection-color: rgb(211, 194, 78); }") self.P7_type.setStyleSheet("QComboBox { color : rgb(193, 202, 227); selection-color: rgb(211, 194, 78); }") self.Phase_1.setStyleSheet("QPlainTextEdit { color: rgb(211, 194, 78); }") self.Phase_2.setStyleSheet("QPlainTextEdit { color: rgb(211, 194, 78); }") self.Phase_3.setStyleSheet("QPlainTextEdit { color: rgb(211, 194, 78); }") self.Phase_4.setStyleSheet("QPlainTextEdit { color: rgb(211, 194, 78); }") self.Phase_5.setStyleSheet("QPlainTextEdit { color: rgb(211, 194, 78); }") self.Phase_6.setStyleSheet("QPlainTextEdit { color: rgb(211, 194, 78); }") self.Phase_7.setStyleSheet("QPlainTextEdit { color: rgb(211, 194, 78); }") # Functions self.P1_st.valueChanged.connect(self.p1_st) self.p1_start = self.add_ns( self.P1_st.value() ) self.P2_st.valueChanged.connect(self.p2_st) self.p2_start = self.add_ns( self.P2_st.value() ) self.P3_st.valueChanged.connect(self.p3_st) self.p3_start = self.add_ns( self.P3_st.value() ) self.P4_st.valueChanged.connect(self.p4_st) self.p4_start = self.add_ns( self.P4_st.value() ) self.P5_st.valueChanged.connect(self.p5_st) self.p5_start = self.add_ns( self.P5_st.value() ) self.P6_st.valueChanged.connect(self.p6_st) self.p6_start = self.add_ns( self.P6_st.value() ) self.P7_st.valueChanged.connect(self.p7_st) self.p7_start = self.add_ns( self.P7_st.value() ) self.P1_len.valueChanged.connect(self.p1_len) self.p1_length = self.add_ns( self.P1_len.value() ) self.P2_len.valueChanged.connect(self.p2_len) self.p2_length = self.add_ns( self.P2_len.value() ) self.P3_len.valueChanged.connect(self.p3_len) self.p3_length = self.add_ns( self.P3_len.value() ) self.P4_len.valueChanged.connect(self.p4_len) self.p4_length = self.add_ns( self.P4_len.value() ) self.P5_len.valueChanged.connect(self.p5_len) self.p5_length = self.add_ns( self.P5_len.value() ) self.P6_len.valueChanged.connect(self.p6_len) self.p6_length = self.add_ns( self.P6_len.value() ) self.P7_len.valueChanged.connect(self.p7_len) self.p7_length = self.add_ns( self.P7_len.value() ) self.Rep_rate.valueChanged.connect(self.rep_rate) self.repetition_rate = str( self.Rep_rate.value() ) + ' Hz' self.Field.valueChanged.connect(self.field) self.mag_field = float( self.Field.value() ) ###self.bh15.magnet_setup( self.mag_field, 0.5 ) self.P1_type.currentIndexChanged.connect(self.p1_type) self.p1_typ = str( self.P1_type.currentText() ) self.P2_type.currentIndexChanged.connect(self.p2_type) self.p2_typ = str( self.P2_type.currentText() ) self.P3_type.currentIndexChanged.connect(self.p3_type) self.p3_typ = str( self.P3_type.currentText() ) self.P4_type.currentIndexChanged.connect(self.p4_type) self.p4_typ = str( self.P4_type.currentText() ) self.P5_type.currentIndexChanged.connect(self.p5_type) self.p5_typ = str( self.P5_type.currentText() ) self.P6_type.currentIndexChanged.connect(self.p6_type) self.p6_typ = str( self.P6_type.currentText() ) self.P7_type.currentIndexChanged.connect(self.p7_type) self.p7_typ = str( self.P7_type.currentText() ) self.laser_flag = 0 self.laser_q_switch_delay = 165000 # in ns self.Phase_1.textChanged.connect(self.phase_1) self.ph_1 = self.Phase_1.toPlainText()[1:(len(self.Phase_1.toPlainText())-1)].split(',') self.Phase_2.textChanged.connect(self.phase_2) self.ph_2 = self.Phase_2.toPlainText()[1:(len(self.Phase_2.toPlainText())-1)].split(',') self.Phase_3.textChanged.connect(self.phase_3) self.ph_3 = self.Phase_3.toPlainText()[1:(len(self.Phase_3.toPlainText())-1)].split(',') self.Phase_4.textChanged.connect(self.phase_4) self.ph_4 = self.Phase_4.toPlainText()[1:(len(self.Phase_4.toPlainText())-1)].split(',') self.Phase_5.textChanged.connect(self.phase_5) self.ph_5 = self.Phase_5.toPlainText()[1:(len(self.Phase_5.toPlainText())-1)].split(',') self.Phase_6.textChanged.connect(self.phase_6) self.ph_6 = self.Phase_6.toPlainText()[1:(len(self.Phase_6.toPlainText())-1)].split(',') self.Phase_7.textChanged.connect(self.phase_7) self.ph_7 = self.Phase_7.toPlainText()[1:(len(self.Phase_7.toPlainText())-1)].split(',') self.menu_bar_file() self.dig_part() def dig_part(self): """ Digitizer settings """ # time per point is fixed self.time_per_point = 2 self.Timescale.valueChanged.connect(self.timescale) self.points = int( self.Timescale.value() ) self.Timescale.setStyleSheet("QSpinBox { color : rgb(193, 202, 227); }") self.Hor_offset.valueChanged.connect(self.hor_offset) self.posttrigger = int( self.Hor_offset.value() ) self.Hor_offset.setStyleSheet("QSpinBox { color : rgb(193, 202, 227); }") self.Win_left.valueChanged.connect(self.win_left) self.cur_win_left = int( self.Win_left.value() ) * self.time_per_point self.Win_left.setStyleSheet("QSpinBox { color : rgb(193, 202, 227); }") self.Win_right.valueChanged.connect(self.win_right) self.cur_win_right = int( self.Win_right.value() ) * self.time_per_point self.Win_right.setStyleSheet("QSpinBox { color : rgb(193, 202, 227); }") self.Acq_number.valueChanged.connect(self.acq_number) self.number_averages = int( self.Acq_number.value() ) self.Acq_number.setStyleSheet("QSpinBox { color : rgb(193, 202, 227); }") self.shift_box.setStyleSheet("QCheckBox { color : rgb(193, 202, 227); }") self.fft_box.setStyleSheet("QCheckBox { color : rgb(193, 202, 227); }") self.shift_box.stateChanged.connect( self.simul_shift ) self.fft_box.stateChanged.connect( self.fft_online ) # flag for not writing the data when digitizer is off self.opened = 0 self.fft = 0 """ Create a process to interact with an experimental script that will run on a different thread. We need a different thread here, since PyQt GUI applications have a main thread of execution that runs the event loop and GUI. If you launch a long-running task in this thread, then your GUI will freeze until the task terminates. During that time, the user won’t be able to interact with the application """ self.worker = Worker() def fft_online(self): """ Turn on/off FFT """ if self.fft_box.checkState() == 2: # checked self.fft = 1 elif self.fft_box.checkState() == 0: # unchecked self.fft = 0 try: self.parent_conn_dig.send( 'FF' + str( self.fft ) ) except AttributeError: self.message('Digitizer is not running') def simul_shift(self): """ Special function for simultaneous change of number of points and horizontal offset """ if self.shift_box.checkState() == 2: # checked self.Timescale.valueChanged.disconnect() #self.Hor_offset.valueChanged.disconnect() self.Timescale.valueChanged.connect(self.timescale_hor_offset) #self.Hor_offset.valueChanged.connect(self.timescale_hor_offset) elif self.shift_box.checkState() == 0: # unchecked self.Timescale.valueChanged.disconnect() self.Timescale.valueChanged.connect(self.timescale) self.points = int( self.Timescale.value() ) #self.Hor_offset.valueChanged.disconnect() #self.Hor_offset.valueChanged.connect(self.hor_offset) self.posttrigger = int( self.Hor_offset.value() ) def timescale_hor_offset(self): """ A function to simultaneously change a number of points and horizontal offset of the digitizer """ dif = abs( self.points - self.posttrigger ) self.timescale() self.posttrigger = self.points - dif self.Hor_offset.setValue( self.posttrigger ) #if self.opened == 0: # try: # self.parent_conn_dig.send( 'HO' + str( self.posttrigger ) ) # except AttributeError: # self.message('Digitizer is not running') def timescale(self): """ A function to change a number of points of the digitizer """ self.points = int( self.Timescale.value() ) if self.points % 16 != 0: self.points = self.round_to_closest( self.points, 16 ) self.Timescale.setValue( self.points ) if self.shift_box.checkState() == 0: if self.points - self.posttrigger < 16: self.points = self.points + 16 self.Timescale.setValue( self.points ) else: pass if self.opened == 0: try: self.parent_conn_dig.send( 'PO' + str( self.points ) ) except AttributeError: self.message('Digitizer is not running') #self.opened = 0 def hor_offset(self): """ A function to change horizontal offset (posttrigger) """ self.posttrigger = int( self.Hor_offset.value() ) if self.posttrigger % 16 != 0: self.posttrigger = self.round_to_closest( self.posttrigger, 16 ) self.Hor_offset.setValue( self.posttrigger ) if self.points - self.posttrigger <= 16: self.posttrigger = self.points - 16 self.Hor_offset.setValue( self.posttrigger ) if self.opened == 0: try: self.parent_conn_dig.send( 'HO' + str( self.posttrigger ) ) except AttributeError: self.message('Digitizer is not running') def win_left(self): """ A function to change left integration window """ self.cur_win_left = int( self.Win_left.value() ) * self.time_per_point if self.cur_win_left / self.time_per_point > self.points: self.cur_win_left = self.points * self.time_per_point self.Win_left.setValue( self.cur_win_left / self.time_per_point ) if self.opened == 0: try: self.parent_conn_dig.send( 'WL' + str( self.cur_win_left ) ) except AttributeError: self.message('Digitizer is not running') def win_right(self): self.cur_win_right = int( self.Win_right.value() ) * self.time_per_point if self.cur_win_right / self.time_per_point > self.points: self.cur_win_right = self.points * self.time_per_point self.Win_right.setValue( self.cur_win_right / self.time_per_point ) if self.opened == 0: try: self.parent_conn_dig.send( 'WR' + str( self.cur_win_right ) ) except AttributeError: self.message('Digitizer is not running') def acq_number(self): """ A function to change number of averages """ self.number_averages = int( self.Acq_number.value() ) if self.opened == 0: try: self.parent_conn_dig.send( 'NA' + str( self.number_averages ) ) except AttributeError: self.message('Digitizer is not running') def menu_bar_file(self): """ Design settings for QMenuBar """ self.menuBar.setStyleSheet("QMenuBar { color: rgb(193, 202, 227); } \ QMenu::item { color: rgb(211, 194, 78); } QMenu::item:selected {color: rgb(193, 202, 227); }") self.action_read.triggered.connect( self.open_file_dialog ) self.action_save.triggered.connect( self.save_file_dialog ) def open_file_dialog(self): """ A function to open a new window for choosing a pulse list """ filedialog = QFileDialog(self, 'Open File', directory = self.path, filter = "Pulse Phase List (*.phase)",\ options = QtWidgets.QFileDialog.DontUseNativeDialog) # use QFileDialog.DontUseNativeDialog to change directory filedialog.setStyleSheet("QWidget { background-color : rgb(42, 42, 64); color: rgb(211, 194, 78);}") filedialog.setFileMode(QtWidgets.QFileDialog.AnyFile) filedialog.fileSelected.connect(self.open_file) filedialog.show() def save_file_dialog(self): """ A function to open a new window for choosing a pulse list """ filedialog = QFileDialog(self, 'Save File', directory = self.path, filter = "Pulse Phase List (*.phase)",\ options = QtWidgets.QFileDialog.DontUseNativeDialog) filedialog.setAcceptMode(QFileDialog.AcceptSave) # use QFileDialog.DontUseNativeDialog to change directory filedialog.setStyleSheet("QWidget { background-color : rgb(42, 42, 64); color: rgb(211, 194, 78);}") filedialog.setFileMode(QtWidgets.QFileDialog.AnyFile) filedialog.fileSelected.connect(self.save_file) filedialog.show() def open_file(self, filename): """ A function to open a pulse list :param filename: string """ self.opened = 1 text = open(filename).read() lines = text.split('\n') self.setter(text, 0, self.P1_type, self.P1_st, self.P1_len, self.Phase_1) self.setter(text, 1, self.P2_type, self.P2_st, self.P2_len, self.Phase_2) self.setter(text, 2, self.P3_type, self.P3_st, self.P3_len, self.Phase_3) self.setter(text, 3, self.P4_type, self.P4_st, self.P4_len, self.Phase_4) self.setter(text, 4, self.P5_type, self.P5_st, self.P5_len, self.Phase_5) self.setter(text, 5, self.P6_type, self.P6_st, self.P6_len, self.Phase_6) self.setter(text, 6, self.P7_type, self.P7_st, self.P7_len, self.Phase_7) self.Rep_rate.setValue( int( lines[7].split(': ')[1] ) ) self.Field.setValue( float( lines[8].split(': ')[1] ) ) self.shift_box.setCheckState(0) self.fft_box.setCheckState(0) self.Timescale.setValue( int( lines[9].split(': ')[1] ) ) self.Hor_offset.setValue( int( lines[10].split(': ')[1] ) ) self.Win_left.setValue( int( lines[11].split(': ')[1] ) ) self.Win_right.setValue( int( lines[12].split(': ')[1] ) ) self.Acq_number.setValue( int( lines[13].split(': ')[1] ) ) self.dig_stop() self.fft = 0 self.opened = 0 def setter(self, text, index, typ, st, leng, phase): """ Auxiliary function to set all the values from *.pulse file """ array = text.split('\n')[index].split(': ')[1].split(', ') typ.setCurrentText( array[0] ) st.setValue( int( array[1] ) ) leng.setValue( int( array[2] ) ) phase.setPlainText( str( array[3] ) ) def save_file(self, filename): """ A function to save a new pulse list :param filename: string """ if filename[-5:] != 'phase': filename = filename + '.phase' with open(filename, 'w') as file: file.write( 'P1: ' + self.P1_type.currentText() + ', ' + str(self.P1_st.value()) + ', ' + str(self.P1_len.value()) + ', ' + str('[' + ','.join(self.ph_1) + ']') + '\n' ) file.write( 'P2: ' + self.P2_type.currentText() + ', ' + str(self.P2_st.value()) + ', ' + str(self.P2_len.value()) + ', ' + str('[' + ','.join(self.ph_2) + ']') + '\n' ) file.write( 'P3: ' + self.P3_type.currentText() + ', ' + str(self.P3_st.value()) + ', ' + str(self.P3_len.value()) + ', ' + str('[' + ','.join(self.ph_3) + ']') + '\n' ) file.write( 'P4: ' + self.P4_type.currentText() + ', ' + str(self.P4_st.value()) + ', ' + str(self.P4_len.value()) + ', ' + str('[' + ','.join(self.ph_4) + ']') + '\n' ) file.write( 'P5: ' + self.P5_type.currentText() + ', ' + str(self.P5_st.value()) + ', ' + str(self.P5_len.value()) + ', ' + str('[' + ','.join(self.ph_5) + ']') + '\n' ) file.write( 'P6: ' + self.P6_type.currentText() + ', ' + str(self.P6_st.value()) + ', ' + str(self.P6_len.value()) + ', ' + str('[' + ','.join(self.ph_6) + ']') + '\n' ) file.write( 'P7: ' + self.P7_type.currentText() + ', ' + str(self.P7_st.value()) + ', ' + str(self.P7_len.value()) + ', ' + str('[' + ','.join(self.ph_7) + ']') + '\n' ) file.write( 'Rep rate: ' + str(self.Rep_rate.value()) + '\n' ) file.write( 'Field: ' + str(self.Field.value()) + '\n' ) file.write( 'Points: ' + str(self.Timescale.value()) + '\n' ) file.write( 'Horizontal offset: ' + str(self.Hor_offset.value()) + '\n' ) file.write( 'Window left: ' + str(self.Win_left.value()) + '\n' ) file.write( 'Window right: ' + str(self.Win_right.value()) + '\n' ) file.write( 'Acquisitions: ' + str(self.Acq_number.value()) + '\n' ) def phase_converted(self, ph_str): if ph_str == '+x': return '+x' elif ph_str == '-x': return '-x' elif ph_str == '+y': return '+y' elif ph_str == '-y': return '-y' def phase_1(self): """ A function to change a pulse 1 phase """ temp = self.Phase_1.toPlainText() try: if temp[-1] == ']' and temp[0] == '[': self.ph_1 = temp[1:(len(temp)-1)].split(',') #print(self.ph_1) except IndexError: pass def phase_2(self): """ A function to change a pulse 2 phase """ temp = self.Phase_2.toPlainText() try: if temp[-1] == ']' and temp[0] == '[': self.ph_2 = temp[1:(len(temp)-1)].split(',') except IndexError: pass def phase_3(self): """ A function to change a pulse 3 phase """ temp = self.Phase_3.toPlainText() try: if temp[-1] == ']' and temp[0] == '[': self.ph_3 = temp[1:(len(temp)-1)].split(',') except IndexError: pass def phase_4(self): """ A function to change a pulse 4 phase """ temp = self.Phase_4.toPlainText() try: if temp[-1] == ']' and temp[0] == '[': self.ph_4 = temp[1:(len(temp)-1)].split(',') except IndexError: pass def phase_5(self): """ A function to change a pulse 5 phase """ temp = self.Phase_5.toPlainText() try: if temp[-1] == ']' and temp[0] == '[': self.ph_5 = temp[1:(len(temp)-1)].split(',') except IndexError: pass def phase_6(self): """ A function to change a pulse 6 phase """ temp = self.Phase_6.toPlainText() try: if temp[-1] == ']' and temp[0] == '[': self.ph_6 = temp[1:(len(temp)-1)].split(',') except IndexError: pass def phase_7(self): """ A function to change a pulse 7 phase """ temp = self.Phase_7.toPlainText() try: if temp[-1] == ']' and temp[0] == '[': self.ph_7 = temp[1:(len(temp)-1)].split(',') except IndexError: pass def remove_ns(self, string1): return string1.split(' ')[0] def add_ns(self, string1): """ Function to add ' ns' """ return str( string1 ) + ' ns' def check_length(self, length): self.errors.clear() if int( length ) != 0 and int( length ) < 12: self.errors.appendPlainText( 'Pulse should be longer than 12 ns' ) return length # stop? def _on_destroyed(self): """ A function to do some actions when the main window is closing. """ try: self.parent_conn_dig.send('exit') except BrokenPipeError: self.message('Digitizer is not running') except AttributeError: self.message('Digitizer is not running') self.digitizer_process.join() self.dig_stop() ##self.pb.pulser_stop() #sys.exit() def quit(self): """ A function to quit the programm """ self._on_destroyed() sys.exit() def p1_st(self): """ A function to set pulse 1 start """ self.p1_start = self.P1_st.value() if self.p1_start % 2 != 0: self.p1_start = self.p1_start + 1 self.P1_st.setValue( self.p1_start ) self.p1_start = self.add_ns( self.P1_st.value() ) def p2_st(self): """ A function to set pulse 2 start """ self.p2_start = self.P2_st.value() if self.p2_start % 2 != 0: self.p2_start = self.p2_start + 1 self.P2_st.setValue( self.p2_start ) self.p2_start = self.add_ns( self.P2_st.value() ) def p3_st(self): """ A function to set pulse 3 start """ self.p3_start = self.P3_st.value() if self.p3_start % 2 != 0: self.p3_start = self.p3_start + 1 self.P3_st.setValue( self.p3_start ) self.p3_start = self.add_ns( self.P3_st.value() ) def p4_st(self): """ A function to set pulse 4 start """ self.p4_start = self.P4_st.value() if self.p4_start % 2 != 0: self.p4_start = self.p4_start + 1 self.P4_st.setValue( self.p4_start ) self.p4_start = self.add_ns( self.P4_st.value() ) def p5_st(self): """ A function to set pulse 5 start """ self.p5_start = self.P5_st.value() if self.p5_start % 2 != 0: self.p5_start = self.p5_start + 1 self.P5_st.setValue( self.p5_start ) self.p5_start = self.add_ns( self.P5_st.value() ) def p6_st(self): """ A function to set pulse 6 start """ self.p6_start = self.P6_st.value() if self.p6_start % 2 != 0: self.p6_start = self.p6_start + 1 self.P6_st.setValue( self.p6_start ) self.p6_start = self.add_ns( self.P6_st.value() ) def p7_st(self): """ A function to set pulse 7 start """ self.p7_start = self.P7_st.value() if self.p7_start % 2 != 0: self.p7_start = self.p7_start + 1 self.P7_st.setValue( self.p7_start ) self.p7_start = self.add_ns( self.P7_st.value() ) def p1_len(self): """ A function to change a pulse 1 length """ self.p1_length = self.P1_len.value() if self.p1_length % 2 != 0: self.p1_length = self.p1_length + 1 self.P1_len.setValue( self.p1_length ) pl = self.check_length( self.P1_len.value() ) self.p1_length = self.add_ns( pl ) def p2_len(self): """ A function to change a pulse 2 length """ self.p2_length = self.P2_len.value() if self.p2_length % 2 != 0: self.p2_length = self.p2_length + 1 self.P2_len.setValue( self.p2_length ) pl = self.check_length( self.P2_len.value() ) self.p2_length = self.add_ns( pl ) def p3_len(self): """ A function to change a pulse 3 length """ self.p3_length = self.P3_len.value() if self.p3_length % 2 != 0: self.p3_length = self.p3_length + 1 self.P3_len.setValue( self.p3_length ) pl = self.check_length( self.P3_len.value() ) self.p3_length = self.add_ns( pl ) def p4_len(self): """ A function to change a pulse 4 length """ self.p4_length = self.P4_len.value() if self.p4_length % 2 != 0: self.p4_length = self.p4_length + 1 self.P4_len.setValue( self.p4_length ) pl = self.check_length( self.P4_len.value() ) self.p4_length = self.add_ns( pl ) def p5_len(self): """ A function to change a pulse 5 length """ self.p5_length = self.P5_len.value() if self.p5_length % 2 != 0: self.p5_length = self.p5_length + 1 self.P5_len.setValue( self.p5_length ) pl = self.check_length( self.P5_len.value() ) self.p5_length = self.add_ns( pl ) def p6_len(self): """ A function to change a pulse 6 length """ self.p6_length = self.P6_len.value() if self.p6_length % 2 != 0: self.p6_length = self.p6_length + 1 self.P6_len.setValue( self.p6_length ) pl = self.check_length( self.P6_len.value() ) self.p6_length = self.add_ns( pl ) def p7_len(self): """ A function to change a pulse 7 length """ self.p7_length = self.P7_len.value() if self.p7_length % 2 != 0: self.p7_length = self.p7_length + 1 self.P7_len.setValue( self.p7_length ) pl = self.check_length( self.P7_len.value() ) self.p7_length = self.add_ns( pl ) def p1_type(self): """ A function to change a pulse 1 type """ self.p1_typ = str( self.P1_type.currentText() ) def p2_type(self): """ A function to change a pulse 2 type """ self.p2_typ = str( self.P2_type.currentText() ) if self.p2_typ == 'LASER': self.laser_flag = 1 else: self.laser_flag = 0 def p3_type(self): """ A function to change a pulse 3 type """ self.p3_typ = str( self.P3_type.currentText() ) def p4_type(self): """ A function to change a pulse 4 type """ self.p4_typ = str( self.P4_type.currentText() ) def p5_type(self): """ A function to change a pulse 5 type """ self.p5_typ = str( self.P5_type.currentText() ) def p6_type(self): """ A function to change a pulse 6 type """ self.p6_typ = str( self.P6_type.currentText() ) def p7_type(self): """ A function to change a pulse 7 type """ self.p7_typ = str( self.P7_type.currentText() ) def rep_rate(self): """ A function to change a repetition rate """ self.repetition_rate = str( self.Rep_rate.value() ) + ' Hz' if self.laser_flag != 1: self.pb.pulser_repetition_rate( self.repetition_rate ) ###self.update() else: self.repetition_rate = '10 Hz' self.pb.pulser_repetition_rate( self.repetition_rate ) self.Rep_rate.setValue(10) ###self.update() self.errors.appendPlainText( '10 Hz is a maximum repetiton rate with LASER pulse' ) try: self.parent_conn_dig.send( 'RR' + str( self.repetition_rate.split(' ')[0] ) ) except AttributeError: self.message('Digitizer is not running') def field(self): """ A function to change a magnetic field """ self.mag_field = float( self.Field.value() ) ###self.bh15.magnet_field( self.mag_field ) try: self.errors.appendPlainText( str( self.mag_field ) ) self.parent_conn_dig.send( 'FI' + str( self.mag_field ) ) except AttributeError: self.message('Digitizer is not running') def pulse_sequence(self): """ Pulse sequence from defined pulses """ if self.laser_flag != 1: self.pb.pulser_repetition_rate( self.repetition_rate ) if int( self.p1_length.split(' ')[0] ) != 0: self.pb.pulser_pulse( name = 'P0', channel = self.p1_typ, start = self.p1_start, length = self.p1_length, \ phase_list = self.ph_1 ) if int( self.p2_length.split(' ')[0] ) != 0: self.pb.pulser_pulse( name = 'P1', channel = self.p2_typ, start = self.p2_start, length = self.p2_length, \ phase_list = self.ph_2 ) if int( self.p3_length.split(' ')[0] ) != 0: self.pb.pulser_pulse( name = 'P2', channel = self.p3_typ, start = self.p3_start, length = self.p3_length, \ phase_list = self.ph_3 ) if int( self.p4_length.split(' ')[0] ) != 0: self.pb.pulser_pulse( name = 'P3', channel = self.p4_typ, start = self.p4_start, length = self.p4_length, \ phase_list = self.ph_4 ) if int( self.p5_length.split(' ')[0] ) != 0: self.pb.pulser_pulse( name = 'P4', channel = self.p5_typ, start = self.p5_start, length = self.p5_length, \ phase_list = self.ph_5 ) if int( self.p6_length.split(' ')[0] ) != 0: self.pb.pulser_pulse( name = 'P5', channel = self.p6_typ, start = self.p6_start, length = self.p6_length, \ phase_list = self.ph_6 ) if int( self.p7_length.split(' ')[0] ) != 0: self.pb.pulser_pulse( name = 'P6', channel = self.p7_typ, start = self.p7_start, length = self.p7_length, \ phase_list = self.ph_7 ) else: self.pb.pulser_repetition_rate( '10 Hz' ) self.Rep_rate.setValue(10) # add q_switch_delay self.p1_start = self.add_ns( int( self.remove_ns( self.p1_start ) ) + self.laser_q_switch_delay ) self.p3_start = self.add_ns( int( self.remove_ns( self.p3_start ) ) + self.laser_q_switch_delay ) self.p4_start = self.add_ns( int( self.remove_ns( self.p4_start ) ) + self.laser_q_switch_delay ) self.p5_start = self.add_ns( int( self.remove_ns( self.p5_start ) ) + self.laser_q_switch_delay ) self.p6_start = self.add_ns( int( self.remove_ns( self.p6_start ) ) + self.laser_q_switch_delay ) self.p7_start = self.add_ns( int( self.remove_ns( self.p7_start ) ) + self.laser_q_switch_delay ) if int( self.p1_length.split(' ')[0] ) != 0: self.pb.pulser_pulse( name = 'P0', channel = self.p1_typ, start = self.p1_start, length = self.p1_length, \ phase_list = self.ph_1 ) if int( self.p2_length.split(' ')[0] ) != 0: self.pb.pulser_pulse( name = 'P1', channel = self.p2_typ, start = self.p2_start, length = self.p2_length, \ phase_list = self.ph_2 ) if int( self.p3_length.split(' ')[0] ) != 0: self.pb.pulser_pulse( name = 'P2', channel = self.p3_typ, start = self.p3_start, length = self.p3_length, \ phase_list = self.ph_3 ) if int( self.p4_length.split(' ')[0] ) != 0: self.pb.pulser_pulse( name = 'P3', channel = self.p4_typ, start = self.p4_start, length = self.p4_length, \ phase_list = self.ph_4 ) if int( self.p5_length.split(' ')[0] ) != 0: self.pb.pulser_pulse( name = 'P4', channel = self.p5_typ, start = self.p5_start, length = self.p5_length, \ phase_list = self.ph_5 ) if int( self.p6_length.split(' ')[0] ) != 0: self.pb.pulser_pulse( name = 'P5', channel = self.p6_typ, start = self.p6_start, length = self.p6_length, \ phase_list = self.ph_6 ) if int( self.p7_length.split(' ')[0] ) != 0: self.pb.pulser_pulse( name = 'P6', channel = self.p7_typ, start = self.p7_start, length = self.p7_length, \ phase_list = self.ph_7 ) self.errors.appendPlainText( '165 us is added to all the pulses except the LASER pulse' ) self.errors.appendPlainText( self.pb.pulser_pulse_list() ) # before adding pulse phases #self.pb.pulser_update() # ? self.pb.pulser_next_phase() def update(self): """ A function to run pulses """ # TEST RUN self.errors.clear() self.parent_conn, self.child_conn = Pipe() # a process for running test self.test_process = Process( target = self.pulser_test, args = ( self.child_conn, 'test', ) ) self.test_process.start() # in order to finish a test time.sleep( 0.1 ) #print( self.test_process.exitcode ) if self.test_process.exitcode == 0: self.test_process.join() # RUN # ? # can be problem here: # maybe it should be moved to pulser_test() # and deleted from here #self.pb.pulser_clear() #self.pulse_sequence() #self.errors.appendPlainText( self.pb.pulser_pulse_list() ) #self.pb.pulser_test_flag('None') self.dig_start() else: self.test_process.join() self.pb.pulser_stop() self.errors.appendPlainText( 'Incorrect pulse setting. Check that your pulses:\n' + \ '1. Not overlapped\n' + \ '2. Distance between MW pulses is more than 40 ns\n' + \ '3. Pulses are longer or equal to 12 ns\n' + \ '4. Field Controller is stucked\n' + \ '5. LASER pulse should not be in 208-232; 152-182; 102-126; <76 ns from first MW\n' + \ '6. Phase sequence does not have equal length for all pulses with nonzero length\n' + \ '\nPulser is stopped') def pulser_test(self, conn, flag): """ Test run """ self.pb.pulser_clear() self.pb.pulser_test_flag( flag ) self.pulse_sequence() def dig_stop(self): """ A function to stop digitizer """ path_to_main = os.path.abspath( os.getcwd() ) path_file = os.path.join(path_to_main, 'atomize/control_center/digitizer.param') ###path_file = os.path.join(path_to_main, '../../atomize/control_center/digitizer.param') if self.opened == 0: try: self.parent_conn_dig.send('exit') self.digitizer_process.join() except AttributeError: self.message('Digitizer is not running') #self.opened = 0 file_to_read = open(path_file, 'w') file_to_read.write('Points: ' + str( self.points ) +'\n') file_to_read.write('Sample Rate: ' + str( 500 ) +'\n') file_to_read.write('Posstriger: ' + str( self.posttrigger ) +'\n') file_to_read.write('Range: ' + str( 500 ) +'\n') file_to_read.write('CH0 Offset: ' + str( 0 ) +'\n') file_to_read.write('CH1 Offset: ' + str( 0 ) +'\n') if self.cur_win_right < self.cur_win_left: self.cur_win_left, self.cur_win_right = self.cur_win_right, self.cur_win_left if self.cur_win_right == self.cur_win_left: self.cur_win_right += self.time_per_point file_to_read.write('Window Left: ' + str( int(self.cur_win_left / self.time_per_point) ) +'\n') file_to_read.write('Window Right: ' + str( int(self.cur_win_right / self.time_per_point) ) +'\n') file_to_read.close() self.errors.clear() def dig_start(self): """ Button Start; Run function script(pipe_addres, four parameters of the experimental script) from Worker class in a different thread Create a Pipe for interaction with this thread self.param_i are used as parameters for script function """ p1_list = [ self.p1_typ, self.p1_start, self.p1_length, self.ph_1 ] p2_list = [ self.p2_typ, self.p2_start, self.p2_length, self.ph_2 ] p3_list = [ self.p3_typ, self.p3_start, self.p3_length, self.ph_3 ] p4_list = [ self.p4_typ, self.p4_start, self.p4_length, self.ph_4 ] p5_list = [ self.p5_typ, self.p5_start, self.p5_length, self.ph_5 ] p6_list = [ self.p6_typ, self.p6_start, self.p6_length, self.ph_6 ] p7_list = [ self.p7_typ, self.p7_start, self.p7_length, self.ph_7 ] # prevent running two processes try: if self.digitizer_process.is_alive() == True: return except AttributeError: pass self.parent_conn_dig, self.child_conn_dig = Pipe() # a process for running function script # sending parameters for initial initialization self.digitizer_process = Process( target = self.worker.dig_on, args = ( self.child_conn_dig, self.points, self.posttrigger, self.number_averages, \ self.cur_win_left, self.cur_win_right, p1_list, p2_list, p3_list, p4_list, p5_list, p6_list, p7_list, \ self.laser_flag, self.repetition_rate.split(' ')[0], self.mag_field, self.fft, ) ) self.digitizer_process.start() # send a command in a different thread about the current state self.parent_conn_dig.send('start') def turn_off(self): """ A function to turn off a programm. """ try: self.parent_conn_dig.send('exit') self.digitizer_process.join() except AttributeError: self.message('Digitizer is not running') sys.exit() sys.exit() def help(self): """ A function to open a documentation """ pass def message(*text): sock = socket.socket() sock.connect(('localhost', 9091)) if len(text) == 1: sock.send(str(text[0]).encode()) sock.close() else: sock.send(str(text).encode()) sock.close() def round_to_closest(self, x, y): """ A function to round x to divisible by y """ return int( y * ( ( x // y) + (x % y > 0) ) ) # The worker class that run the digitizer in a different thread class Worker(QWidget): def __init__(self, parent = None): super(Worker, self).__init__(parent) # initialization of the attribute we use to stop the experimental script # when button Stop is pressed #from atomize.main.client import LivePlotClient self.command = 'start' def dig_on(self, conn, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16): """ function that contains updating of the digitizer """ # should be inside dig_on() function; # freezing after digitizer restart otherwise #import time import numpy as np import atomize.general_modules.general_functions as general import atomize.device_modules.Spectrum_M4I_4450_X8 as spectrum import atomize.device_modules.PB_ESR_500_pro as pb_pro import atomize.math_modules.fft as fft_module import atomize.device_modules.BH_15 as bh pb = pb_pro.PB_ESR_500_Pro() fft = fft_module.Fast_Fourier() bh15 = bh.BH_15() bh15.magnet_setup( p15, 0.5 ) process = 'None' dig = spectrum.Spectrum_M4I_4450_X8() dig.digitizer_card_mode('Average') dig.digitizer_clock_mode('External') dig.digitizer_reference_clock(100) # parameters for initial initialization #points_value = p1 dig.digitizer_number_of_points( p1 ) #posstrigger_value = p2 dig.digitizer_posttrigger( p2 ) #num_ave = p3 dig.digitizer_number_of_averages( p3 ) #p4 window left #p5 window right dig.digitizer_setup() if p13 != 1: pb.pulser_repetition_rate( str(p14) + ' Hz' ) if int( p6[2].split(' ')[0] ) != 0: pb.pulser_pulse( name = 'P0', channel = p6[0], start = p6[1], length = p6[2] ) if int( p7[2].split(' ')[0] ) != 0: pb.pulser_pulse( name = 'P1', channel = p7[0], start = p7[1], length = p7[2], phase_list = p7[3] ) if int( p8[2].split(' ')[0] ) != 0: pb.pulser_pulse( name = 'P2', channel = p8[0], start = p8[1], length = p8[2], phase_list = p8[3] ) if int( p9[2].split(' ')[0] ) != 0: pb.pulser_pulse( name = 'P3', channel = p9[0], start = p9[1], length = p9[2], phase_list = p9[3] ) if int( p10[2].split(' ')[0] ) != 0: pb.pulser_pulse( name = 'P4', channel = p10[0], start = p10[1], length = p10[2], phase_list = p10[3] ) if int( p11[2].split(' ')[0] ) != 0: pb.pulser_pulse( name = 'P5', channel = p11[0], start = p11[1], length = p11[2], phase_list = p11[3] ) if int( p12[2].split(' ')[0] ) != 0: pb.pulser_pulse( name = 'P6', channel = p12[0], start = p12[1], length = p12[2], phase_list = p12[3] ) else: pb.pulser_repetition_rate( '10 Hz' ) # add q_switch_delay 165000 ns p7[1] = str( int( p7[1].split(' ')[0] ) + 165000 ) + ' ns' p8[1] = str( int( p8[1].split(' ')[0] ) + 165000 ) + ' ns' p9[1] = str( int( p9[1].split(' ')[0] ) + 165000 ) + ' ns' p10[1] = str( int( p10[1].split(' ')[0] ) + 165000 ) + ' ns' p11[1] = str( int( p11[1].split(' ')[0] ) + 165000 ) + ' ns' p12[1] = str( int( p12[1].split(' ')[0] ) + 165000 ) + ' ns' if int( p6[2].split(' ')[0] ) != 0: pb.pulser_pulse( name = 'P0', channel = p6[0], start = p6[1], length = p6[2] ) if int( p7[2].split(' ')[0] ) != 0: pb.pulser_pulse( name = 'P1', channel = p7[0], start = p7[1], length = p7[2], phase_list = p7[3] ) if int( p8[2].split(' ')[0] ) != 0: pb.pulser_pulse( name = 'P2', channel = p8[0], start = p8[1], length = p8[2], phase_list = p8[3] ) if int( p9[2].split(' ')[0] ) != 0: pb.pulser_pulse( name = 'P3', channel = p9[0], start = p9[1], length = p9[2], phase_list = p9[3] ) if int( p10[2].split(' ')[0] ) != 0: pb.pulser_pulse( name = 'P4', channel = p10[0], start = p10[1], length = p10[2], phase_list = p10[3] ) if int( p11[2].split(' ')[0] ) != 0: pb.pulser_pulse( name = 'P5', channel = p11[0], start = p11[1], length = p11[2], phase_list = p11[3] ) if int( p12[2].split(' ')[0] ) != 0: pb.pulser_pulse( name = 'P6', channel = p12[0], start = p12[1], length = p12[2], phase_list = p12[3] ) cycle_data_x = np.zeros( (len(p6[3]), int(p1)) ) cycle_data_y = np.zeros( (len(p6[3]), int(p1)) ) data_x = np.zeros( p1 ) data_y = np.zeros( p1 ) # the idea of automatic and dynamic changing is # sending a new value of repetition rate via self.command # in each cycle we will check the current value of self.command # self.command = 'exit' will stop the digitizer while self.command != 'exit': # always test our self.command attribute for stopping the script when neccessary if self.command[0:2] == 'PO': points_value = int( self.command[2:] ) dig.digitizer_stop() dig.digitizer_number_of_points( points_value ) #dig.digitizer_setup() cycle_data_x = np.zeros( (len(p6[3]), int(points_value)) ) cycle_data_y = np.zeros( (len(p6[3]), int(points_value)) ) data_x = np.zeros( points_value ) data_y = np.zeros( points_value ) elif self.command[0:2] == 'HO': posstrigger_value = int( self.command[2:] ) dig.digitizer_stop() dig.digitizer_posttrigger( posstrigger_value ) #dig.digitizer_setup() elif self.command[0:2] == 'NA': num_ave = int( self.command[2:] ) dig.digitizer_stop() dig.digitizer_number_of_averages( num_ave ) #dig.digitizer_setup() elif self.command[0:2] == 'WL': p4 = int( self.command[2:] ) elif self.command[0:2] == 'WR': p5 = int( self.command[2:] ) elif self.command[0:2] == 'RR': p14 = int( self.command[2:] ) pb.pulser_repetition_rate( str(p14) + ' Hz' ) elif self.command[0:2] == 'FI': p15 = float( self.command[2:] ) bh15.magnet_field( p15 ) elif self.command[0:2] == 'FF': p16 = int( self.command[2:] ) # phase cycle k = 0 while k < len( p6[3] ): pb.pulser_next_phase() x_axis, cycle_data_x[k], cycle_data_y[k] = dig.digitizer_get_curve() k += 1 if p16 == 0: # acquisition cycle data_x, data_y = pb.pulser_acquisition_cycle(cycle_data_x, cycle_data_y, acq_cycle = p6[3]) process = general.plot_1d('Digitizer Live', x_axis, ( data_x, data_y ), label = 'ch', xscale = 's', yscale = 'V', \ vline = (p4 * 10**-9, p5 * 10**-9), pr = process ) else: process = general.plot_1d('Digitizer Live', x_axis, ( data_x, data_y ), label = 'ch', xscale = 's', yscale = 'V', \ vline = (p4 * 10**-9, p5 * 10**-9), pr = process ) freq_axis, abs_values = fft.fft(x_axis, data_x, data_y, 2) process = general.plot_1d('FFT Analyzer', freq_axis, abs_values, label = 'FFT', xscale = 'MHz', yscale = 'Arb. U.', pr = process) self.command = 'start' pb.pulser_pulse_reset() ###time.sleep( 0.2 ) # poll() checks whether there is data in the Pipe to read # we use it to stop the script if the exit command was sent from the main window # we read data by conn.recv() only when there is the data to read if conn.poll() == True: self.command = conn.recv() if self.command == 'exit': ###print('exit') dig.digitizer_stop() dig.digitizer_close() # ? #pb.pulser_clear() pb.pulser_stop() def main(): """ A function to run the main window of the programm. """ app = QtWidgets.QApplication(sys.argv) main = MainWindow() main.show() sys.exit(app.exec_()) if __name__ == '__main__': main()
[ "atomize.general_modules.general_functions.plot_1d", "atomize.device_modules.BH_15.BH_15", "os.path.abspath", "PyQt5.QtGui.QIcon", "os.getcwd", "socket.socket", "numpy.zeros", "atomize.device_modules.PB_ESR_500_pro.PB_ESR_500_Pro", "PyQt5.uic.loadUi", "time.sleep", "multiprocessing.Pipe", "ato...
[((53148, 53180), 'PyQt5.QtWidgets.QApplication', 'QtWidgets.QApplication', (['sys.argv'], {}), '(sys.argv)\n', (53170, 53180), False, 'from PyQt5 import QtWidgets, uic\n'), ((851, 907), 'os.path.join', 'os.path.join', (['path_to_main', '"""gui/phasing_main_window.ui"""'], {}), "(path_to_main, 'gui/phasing_main_window.ui')\n", (863, 907), False, 'import os\n'), ((927, 975), 'os.path.join', 'os.path.join', (['path_to_main', '"""gui/icon_pulse.png"""'], {}), "(path_to_main, 'gui/icon_pulse.png')\n", (939, 975), False, 'import os\n'), ((1044, 1095), 'os.path.join', 'os.path.join', (['path_to_main', '""".."""', '"""tests/pulse_epr"""'], {}), "(path_to_main, '..', 'tests/pulse_epr')\n", (1056, 1095), False, 'import os\n'), ((1239, 1265), 'PyQt5.uic.loadUi', 'uic.loadUi', (['gui_path', 'self'], {}), '(gui_path, self)\n', (1249, 1265), False, 'from PyQt5 import QtWidgets, uic\n'), ((1340, 1363), 'atomize.device_modules.PB_ESR_500_pro.PB_ESR_500_Pro', 'pb_pro.PB_ESR_500_Pro', ([], {}), '()\n', (1361, 1363), True, 'import atomize.device_modules.PB_ESR_500_pro as pb_pro\n'), ((17984, 18133), 'PyQt5.QtWidgets.QFileDialog', 'QFileDialog', (['self', '"""Open File"""'], {'directory': 'self.path', 'filter': '"""Pulse Phase List (*.phase)"""', 'options': 'QtWidgets.QFileDialog.DontUseNativeDialog'}), "(self, 'Open File', directory=self.path, filter=\n 'Pulse Phase List (*.phase)', options=QtWidgets.QFileDialog.\n DontUseNativeDialog)\n", (17995, 18133), False, 'from PyQt5.QtWidgets import QWidget, QFileDialog\n'), ((18606, 18755), 'PyQt5.QtWidgets.QFileDialog', 'QFileDialog', (['self', '"""Save File"""'], {'directory': 'self.path', 'filter': '"""Pulse Phase List (*.phase)"""', 'options': 'QtWidgets.QFileDialog.DontUseNativeDialog'}), "(self, 'Save File', directory=self.path, filter=\n 'Pulse Phase List (*.phase)', options=QtWidgets.QFileDialog.\n DontUseNativeDialog)\n", (18617, 18755), False, 'from PyQt5.QtWidgets import QWidget, QFileDialog\n'), ((26497, 26507), 'sys.exit', 'sys.exit', ([], {}), '()\n', (26505, 26507), False, 'import sys\n'), ((38609, 38615), 'multiprocessing.Pipe', 'Pipe', ([], {}), '()\n', (38613, 38615), False, 'from multiprocessing import Process, Pipe\n'), ((38681, 38745), 'multiprocessing.Process', 'Process', ([], {'target': 'self.pulser_test', 'args': "(self.child_conn, 'test')"}), "(target=self.pulser_test, args=(self.child_conn, 'test'))\n", (38688, 38745), False, 'from multiprocessing import Process, Pipe\n'), ((38841, 38856), 'time.sleep', 'time.sleep', (['(0.1)'], {}), '(0.1)\n', (38851, 38856), False, 'import time\n'), ((40555, 40623), 'os.path.join', 'os.path.join', (['path_to_main', '"""atomize/control_center/digitizer.param"""'], {}), "(path_to_main, 'atomize/control_center/digitizer.param')\n", (40567, 40623), False, 'import os\n'), ((43035, 43041), 'multiprocessing.Pipe', 'Pipe', ([], {}), '()\n', (43039, 43041), False, 'from multiprocessing import Process, Pipe\n'), ((44056, 44066), 'sys.exit', 'sys.exit', ([], {}), '()\n', (44064, 44066), False, 'import sys\n'), ((44208, 44223), 'socket.socket', 'socket.socket', ([], {}), '()\n', (44221, 44223), False, 'import socket\n'), ((45640, 45663), 'atomize.device_modules.PB_ESR_500_pro.PB_ESR_500_Pro', 'pb_pro.PB_ESR_500_Pro', ([], {}), '()\n', (45661, 45663), True, 'import atomize.device_modules.PB_ESR_500_pro as pb_pro\n'), ((45678, 45703), 'atomize.math_modules.fft.Fast_Fourier', 'fft_module.Fast_Fourier', ([], {}), '()\n', (45701, 45703), True, 'import atomize.math_modules.fft as fft_module\n'), ((45719, 45729), 'atomize.device_modules.BH_15.BH_15', 'bh.BH_15', ([], {}), '()\n', (45727, 45729), True, 'import atomize.device_modules.BH_15 as bh\n'), ((45808, 45839), 'atomize.device_modules.Spectrum_M4I_4450_X8.Spectrum_M4I_4450_X8', 'spectrum.Spectrum_M4I_4450_X8', ([], {}), '()\n', (45837, 45839), True, 'import atomize.device_modules.Spectrum_M4I_4450_X8 as spectrum\n'), ((49380, 49392), 'numpy.zeros', 'np.zeros', (['p1'], {}), '(p1)\n', (49388, 49392), True, 'import numpy as np\n'), ((49412, 49424), 'numpy.zeros', 'np.zeros', (['p1'], {}), '(p1)\n', (49420, 49424), True, 'import numpy as np\n'), ((805, 830), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (820, 830), False, 'import os\n'), ((1004, 1020), 'PyQt5.QtGui.QIcon', 'QIcon', (['icon_path'], {}), '(icon_path)\n', (1009, 1020), False, 'from PyQt5.QtGui import QIcon\n'), ((40521, 40532), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (40530, 40532), False, 'import os\n'), ((44036, 44046), 'sys.exit', 'sys.exit', ([], {}), '()\n', (44044, 44046), False, 'import sys\n'), ((50222, 50244), 'numpy.zeros', 'np.zeros', (['points_value'], {}), '(points_value)\n', (50230, 50244), True, 'import numpy as np\n'), ((50272, 50294), 'numpy.zeros', 'np.zeros', (['points_value'], {}), '(points_value)\n', (50280, 50294), True, 'import numpy as np\n'), ((51748, 51897), 'atomize.general_modules.general_functions.plot_1d', 'general.plot_1d', (['"""Digitizer Live"""', 'x_axis', '(data_x, data_y)'], {'label': '"""ch"""', 'xscale': '"""s"""', 'yscale': '"""V"""', 'vline': '(p4 * 10 ** -9, p5 * 10 ** -9)', 'pr': 'process'}), "('Digitizer Live', x_axis, (data_x, data_y), label='ch',\n xscale='s', yscale='V', vline=(p4 * 10 ** -9, p5 * 10 ** -9), pr=process)\n", (51763, 51897), True, 'import atomize.general_modules.general_functions as general\n'), ((51993, 52142), 'atomize.general_modules.general_functions.plot_1d', 'general.plot_1d', (['"""Digitizer Live"""', 'x_axis', '(data_x, data_y)'], {'label': '"""ch"""', 'xscale': '"""s"""', 'yscale': '"""V"""', 'vline': '(p4 * 10 ** -9, p5 * 10 ** -9)', 'pr': 'process'}), "('Digitizer Live', x_axis, (data_x, data_y), label='ch',\n xscale='s', yscale='V', vline=(p4 * 10 ** -9, p5 * 10 ** -9), pr=process)\n", (52008, 52142), True, 'import atomize.general_modules.general_functions as general\n'), ((52288, 52404), 'atomize.general_modules.general_functions.plot_1d', 'general.plot_1d', (['"""FFT Analyzer"""', 'freq_axis', 'abs_values'], {'label': '"""FFT"""', 'xscale': '"""MHz"""', 'yscale': '"""Arb. U."""', 'pr': 'process'}), "('FFT Analyzer', freq_axis, abs_values, label='FFT', xscale=\n 'MHz', yscale='Arb. U.', pr=process)\n", (52303, 52404), True, 'import atomize.general_modules.general_functions as general\n')]
import numpy as np from keras.layers import Input, Dense from keras.models import Model from keras.optimizers import Adam from sklearn.base import BaseEstimator from .losses import MDNLossLayer, keras_mean_pred_loss class MixtureDensityRegressor(BaseEstimator): """Fit a Mixture Density Network (MDN).""" def __init__( self, shared_units=(8, 8), weight_units=(8, ), mu_units=(8, ), sigma_units=(8, ), activation='relu', n_components=3, lr=0.001, epochs=10, batch_size=100 ): self._model_instance = None self.shared_units = shared_units self.weight_units = weight_units self.mu_units = mu_units self.sigma_units = sigma_units self.activation = activation self.n_components = n_components self.lr = lr self.epochs = epochs self.batch_size = batch_size def _model(self): input_features = Input((1, ), name='X') input_label = Input((1, ), name='y') # append final output intermediate = input_features for idx, units in enumerate(self.shared_units): intermediate = Dense( units=units, activation=self.activation, name=f'dense_{idx}' )(intermediate) weight, mu, sigma = intermediate, intermediate, intermediate for idx, units in enumerate(self.weight_units): weight = Dense(units, activation=self.activation, name=f'weight_dense_{idx}')(weight) weight = Dense(self.n_components, activation='softmax', name='weight_output')(weight) for idx, units in enumerate(self.mu_units): mu = Dense(units, activation=self.activation, name=f'mu_dense_{idx}')(mu) mu = Dense(self.n_components, activation=None, name='mu_output')(mu) for idx, units in enumerate(self.sigma_units): sigma = Dense(units, activation=self.activation, name=f'sigma_dense_{idx}')(sigma) sigma = Dense(self.n_components, activation='relu', name='sigma_output')(sigma) mdn_model = Model(input_features, [weight, mu, sigma], name='MDN') loss_output = MDNLossLayer([input_label, weight, mu, sigma]) loss_model = Model([input_features, input_label], loss_output) loss_model.compile(optimizer=Adam(lr=self.lr), loss=keras_mean_pred_loss) return {'loss': loss_model, 'mdn': mdn_model} def _init_model(self): self._model_instance = self._model() return self._model_instance @property def model(self): return self._model_instance or self._init_model() def fit(self, X, y, **kwargs): self._init_model() fit_kwargs = dict( epochs=self.epochs, batch_size=self.batch_size, ) fit_kwargs.update(kwargs) self.model['loss'].fit([X, y], 0 * y, **fit_kwargs) def evaluate(self, X, y, **kwargs): loss = self.model['loss'].evaluate([X, y], 0 * y, **kwargs) return loss def predict(self, X, **kwargs): predict_kwargs = dict(batch_size=self.batch_size, ) predict_kwargs.update(kwargs) w, mu, sigma = self.model['mdn'].predict(X, **predict_kwargs) return w, mu, sigma @classmethod def compute_mean(cls, w, mu, sigma): mean = (w * mu).sum(axis=1, keepdims=True) return mean @classmethod def compute_sample_indicator(cls, w, num_samples): """Sample indicator variable at each X.""" num_examples = w.shape[0] samples = np.random.rand(num_examples, 1, num_samples) thresholds = w.cumsum(axis=1)[:, :, np.newaxis] col_idx = (thresholds > samples).argmax(axis=1) _, row_idx = np.meshgrid(np.arange(num_samples), np.arange(num_examples)) return row_idx, col_idx @classmethod def compute_samples(cls, w, mu, sigma, num_samples): """Generate samples from the mixture, per row.""" row_idx, col_idx = cls.compute_sample_indicator(w, num_samples) mu = mu[row_idx, col_idx] sigma = sigma[row_idx, col_idx] samples = np.random.randn(w.shape[0], num_samples) return mu + sigma * samples @classmethod def unroll_samples(cls, X, samples): num_samples = samples.shape[1] X = np.repeat(X, num_samples, axis=1).ravel() y = samples.ravel() return X, y def predict_mean(self, X, **kwargs): w, mu, sigma = self.predict(X, **kwargs) return self.compute_mean(w, mu, sigma) def sample(self, X, num_samples=10, **kwargs): w, mu, sigma = self.predict(X, **kwargs) samples = self.compute_samples(w, mu, sigma, num_samples) return samples
[ "numpy.random.randn", "numpy.random.rand", "keras.optimizers.Adam", "keras.models.Model", "keras.layers.Dense", "numpy.arange", "keras.layers.Input", "numpy.repeat" ]
[((975, 996), 'keras.layers.Input', 'Input', (['(1,)'], {'name': '"""X"""'}), "((1,), name='X')\n", (980, 996), False, 'from keras.layers import Input, Dense\n'), ((1020, 1041), 'keras.layers.Input', 'Input', (['(1,)'], {'name': '"""y"""'}), "((1,), name='y')\n", (1025, 1041), False, 'from keras.layers import Input, Dense\n'), ((2105, 2159), 'keras.models.Model', 'Model', (['input_features', '[weight, mu, sigma]'], {'name': '"""MDN"""'}), "(input_features, [weight, mu, sigma], name='MDN')\n", (2110, 2159), False, 'from keras.models import Model\n'), ((2252, 2301), 'keras.models.Model', 'Model', (['[input_features, input_label]', 'loss_output'], {}), '([input_features, input_label], loss_output)\n', (2257, 2301), False, 'from keras.models import Model\n'), ((3576, 3620), 'numpy.random.rand', 'np.random.rand', (['num_examples', '(1)', 'num_samples'], {}), '(num_examples, 1, num_samples)\n', (3590, 3620), True, 'import numpy as np\n'), ((4144, 4184), 'numpy.random.randn', 'np.random.randn', (['w.shape[0]', 'num_samples'], {}), '(w.shape[0], num_samples)\n', (4159, 4184), True, 'import numpy as np\n'), ((1550, 1618), 'keras.layers.Dense', 'Dense', (['self.n_components'], {'activation': '"""softmax"""', 'name': '"""weight_output"""'}), "(self.n_components, activation='softmax', name='weight_output')\n", (1555, 1618), False, 'from keras.layers import Input, Dense\n'), ((1780, 1839), 'keras.layers.Dense', 'Dense', (['self.n_components'], {'activation': 'None', 'name': '"""mu_output"""'}), "(self.n_components, activation=None, name='mu_output')\n", (1785, 1839), False, 'from keras.layers import Input, Dense\n'), ((2012, 2076), 'keras.layers.Dense', 'Dense', (['self.n_components'], {'activation': '"""relu"""', 'name': '"""sigma_output"""'}), "(self.n_components, activation='relu', name='sigma_output')\n", (2017, 2076), False, 'from keras.layers import Input, Dense\n'), ((3766, 3788), 'numpy.arange', 'np.arange', (['num_samples'], {}), '(num_samples)\n', (3775, 3788), True, 'import numpy as np\n'), ((3790, 3813), 'numpy.arange', 'np.arange', (['num_examples'], {}), '(num_examples)\n', (3799, 3813), True, 'import numpy as np\n'), ((1195, 1262), 'keras.layers.Dense', 'Dense', ([], {'units': 'units', 'activation': 'self.activation', 'name': 'f"""dense_{idx}"""'}), "(units=units, activation=self.activation, name=f'dense_{idx}')\n", (1200, 1262), False, 'from keras.layers import Input, Dense\n'), ((1455, 1523), 'keras.layers.Dense', 'Dense', (['units'], {'activation': 'self.activation', 'name': 'f"""weight_dense_{idx}"""'}), "(units, activation=self.activation, name=f'weight_dense_{idx}')\n", (1460, 1523), False, 'from keras.layers import Input, Dense\n'), ((1697, 1761), 'keras.layers.Dense', 'Dense', (['units'], {'activation': 'self.activation', 'name': 'f"""mu_dense_{idx}"""'}), "(units, activation=self.activation, name=f'mu_dense_{idx}')\n", (1702, 1761), False, 'from keras.layers import Input, Dense\n'), ((1920, 1987), 'keras.layers.Dense', 'Dense', (['units'], {'activation': 'self.activation', 'name': 'f"""sigma_dense_{idx}"""'}), "(units, activation=self.activation, name=f'sigma_dense_{idx}')\n", (1925, 1987), False, 'from keras.layers import Input, Dense\n'), ((2339, 2355), 'keras.optimizers.Adam', 'Adam', ([], {'lr': 'self.lr'}), '(lr=self.lr)\n', (2343, 2355), False, 'from keras.optimizers import Adam\n'), ((4331, 4364), 'numpy.repeat', 'np.repeat', (['X', 'num_samples'], {'axis': '(1)'}), '(X, num_samples, axis=1)\n', (4340, 4364), True, 'import numpy as np\n')]
import csv import logging import os import pickle import sys from typing import Optional, Union import h5py # type: ignore import numpy as np import torch from probing_project.constants import TEXT_MODELS from probing_project.data.probing_dataset import ProbingDataset from probing_project.tasks import TaskBase from probing_project.utils import track # type: ignore from pytorch_pretrained_bert import BertModel, BertTokenizer # type: ignore sys.path.append("../volta") sys.path.append("volta") from volta.config import BertConfig # type: ignore from volta.encoders import BertForVLPreTraining # type: ignore from .base_module import ProbingModuleBase logger = logging.getLogger(__name__) os.environ["HDF5_USE_FILE_LOCKING"] = "FALSE" csv.field_size_limit(sys.maxsize) class ProbingModuleText(ProbingModuleBase): def __init__( self, *args, **kwargs, # important, since the entire argparse dict is given. But we never use them ) -> None: """ Args: task: one of the TASK_CLASSES. Defines which labels to use and what should be predicted data_dir: The root directory where all data is stored dataset: Which dataset to use, options in DATASETS literal embeddings_model: Which BERT embeddings model to use: Basic 'bert' or a 'multimodal_bert' bert_model: What is the initial bert model: 'base' or 'large' bert_cased: use cased 'True' or uncased 'False' bert. bert_model_layer: Which layer are we using to train our probe on. """ super().__init__(*args, **kwargs) # DATASET CREATION AND FILE CREATION def _check_and_create_embedding_features_file(self): """ First determines if the given embbedding based model is impemented to be used. Next checks for each split if the needed hdf5 file is created """ if self.embeddings_model not in TEXT_MODELS: logger.error( f"Given Embedding type for 'embeddings_model' not implemented. " f"for current datamodule class. Available options: {TEXT_MODELS}." ) raise ValueError() for split in ["train", "dev", "test"]: # check if the saved embeddings hdf5 files exist. # Otherwise extract the embeddings. TAKES LONG! outfile = self.unformatted_emb_h5_file.format(split) if not os.path.isfile(outfile): logger.info(f"Creating embeddings h5 file for split {split}") self._convert_conllx_to_bert( input_conllx_pkl=self.unformatted_conllx_pickle.format(split), output_file=outfile, model_name=self.model_name, bert_cased=self.bert_cased, bert_model=self.bert_model, ) else: logger.info( f"embeddings file '{os.path.basename(outfile)}' already exist." ) logger.info("All embedding h5 files ready!") @staticmethod def _convert_conllx_to_bert( input_conllx_pkl: str, output_file: str, model_name: str, bert_cased: bool, bert_model: str, *_, **__, ) -> None: """ Converts the raw file into a HDF5 file with embeddings create by BERT and BERT-Tokenizer. Crucially, do not do basic tokenization; PTB is tokenized. Just do wordpiece tokenization. Args: input_conllx_pkl: The filepath to the conllx file output_file: the filepath for where to store the hdf5 features model_name: the complete model_name as defined by 'pretrained_transformers' bert_cased: If the model should use cased (True) tokens or uncased (False) tokens, default = False bert_model: whether to use BERT 'base' or 'large' Returns: None """ logger.info( f"from: {os.path.basename(input_conllx_pkl)}, " f"creating hdf5: {'/'.join(output_file.split('/')[-2:])}" ) logger.info("making use of the bert model: {model_name.lower()}") tokenizer = BertTokenizer.from_pretrained( model_name.lower(), do_lower_case=not bert_cased, cache_dir="../pytorch_pretrained_bert/", ) model = BertModel.from_pretrained( model_name.lower(), cache_dir="../pytorch_pretrained_bert/" ) def forward_hook(module, input_, output): nonlocal baseline_embs baseline_embs = output _ = model.embeddings.register_forward_hook(forward_hook) layer_count, feature_count = ProbingModuleText.get_bert_info(bert_model) model.eval() # find some statistics for creating the h5 datasets with open(input_conllx_pkl, "rb") as in_pkl: conllx_observations: dict = pickle.load(in_pkl) num_lines = len(conllx_observations) max_label_len = max(len(ob.index) for ob in conllx_observations.values()) # start creating the hdf5 os.makedirs(os.path.dirname(output_file), exist_ok=True) with h5py.File(output_file, "w", libver="latest") as f_out: layer_sets = [] for layer in range(layer_count): layer_sets.append( f_out.create_dataset( name=str(layer), shape=(num_lines, max_label_len, feature_count), fillvalue=0, chunks=(1, max_label_len, feature_count), compression=9, shuffle=True, ) ) text_baseline = f_out.create_dataset( name="text_baseline", shape=(num_lines, max_label_len, feature_count), fillvalue=0, dtype="f", chunks=(1, max_label_len, feature_count), compression=9, shuffle=True, ) # start filling the hdf5 for index, ob in track(conllx_observations.items(), description="raw2bert"): baseline_embs: Union[torch.Tensor, None] = None line = "[CLS] " + " ".join(ob.sentence) + " [SEP]" tokenized_text = tokenizer.wordpiece_tokenizer.tokenize(line) indexed_tokens = tokenizer.convert_tokens_to_ids(tokenized_text) segment_ids = [1 for _ in tokenized_text] # Convert inputs to PyTorch tensors tokens_tensor = torch.tensor([indexed_tokens]) segments_tensors = torch.tensor([segment_ids]) with torch.no_grad(): encoded_layers, _ = model(tokens_tensor, segments_tensors) # place output into the datasets per layer untokenized_sent = ob.sentence untok_tok_mapping = ProbingModuleText._match_tokenized_to_untokenized( tokenized_text, untokenized_sent ) for layer in range(layer_count): single_layer_features = ( encoded_layers[layer].squeeze(0).detach().cpu().numpy() ) # WE WANT TO PROBE FOR THE TREE FOR COMPLETE WORDS. # THERFORE WE FIND HOW MANY SUBTOKENS MAP TO COMPLETE WORDS. # NOW WE TAKE THE AVERAGE OF THE EMBEDDINGS FOR THE SUBTOKENS, # TO GET A SINGLE EMBEDDING FOR EVERY WORD. for token_idx in range(len(untokenized_sent)): layer_sets[layer][index, token_idx, :] = np.mean( single_layer_features[ untok_tok_mapping[token_idx][0] : untok_tok_mapping[ token_idx ][-1] + 1, :, ], axis=0, ) # also store the raw baseline embeddings assert baseline_embs is not None baseline_embs = baseline_embs.squeeze(0).detach().cpu().numpy() for token_idx in range(len(untokenized_sent)): text_baseline[index, token_idx, :] = np.mean( baseline_embs[ # type: ignore untok_tok_mapping[token_idx][0] : untok_tok_mapping[ token_idx ][-1] + 1, :, ], axis=0, ) def prepare_data(self, *args, **kwargs) -> None: """ Checks if all necesary data is created and downloaded. If something is missing, it will create it. If it is some file that cannot be created by the datamodule, it will provide instructions on what to do. """ super().prepare_data(*args, **kwargs) # CHECK FOR LABEL HDF5 self._create_label_h5( task=self.task, input_conllx_pkl=self.unformatted_conllx_pickle, output_file=self.unformatted_label_h5_file, ) def setup(self, stage: Optional[str] = None) -> None: """ Setups the datamodule with datasets for the different splits Args: stage: If 'None', load train, val, and test split. If 'fit', load only the train and val split. if 'test', load only the test split. Returns: None """ logger.debug("Setting up Data") assert ( self.task is not None ), "Preparing can be done without task, for setup it must be set" # Assign Train/val split(s) for use in Dataloaders if stage == "fit" or stage is None: self.train_dataset = ProbingDataset( h5_embeddings_file=self.unformatted_emb_h5_file.format("train"), h5_labels_file=self.unformatted_label_h5_file.format("train"), h5_label_length_file=self.unformatted_length_label_h5_file.format( "train" ), mm_vision_layer="Visual" in self.task.__class__.__name__, layer_idx=self.bert_model_layer, task=self.task, ) self.val_dataset = ProbingDataset( h5_embeddings_file=self.unformatted_emb_h5_file.format("dev"), h5_labels_file=self.unformatted_label_h5_file.format("dev"), h5_label_length_file=self.unformatted_length_label_h5_file.format( "dev" ), mm_vision_layer="Visual" in self.task.__class__.__name__, layer_idx=self.bert_model_layer, task=self.task, sentence_file=self.unformatted_conllx_pickle.format("dev"), ) if stage == "test" or stage is None: self.test_dataset = ProbingDataset( h5_embeddings_file=os.path.join( self.unformatted_emb_h5_file.format("test") ), h5_labels_file=self.unformatted_label_h5_file.format("test"), h5_label_length_file=self.unformatted_length_label_h5_file.format( "test" ), mm_vision_layer="Visual" in self.task.__class__.__name__, layer_idx=self.bert_model_layer, task=self.task, sentence_file=self.unformatted_conllx_pickle.format("test"), ) # LABELS COMPUTE def _create_label_h5( self, task: TaskBase, input_conllx_pkl: str, output_file: str, *_, **__ ) -> None: super()._create_label_h5(task, input_conllx_pkl, output_file) self.task.add_task_label_dataset(input_conllx_pkl, output_file)
[ "sys.path.append", "h5py.File", "os.path.basename", "os.path.dirname", "csv.field_size_limit", "os.path.isfile", "pickle.load", "numpy.mean", "torch.tensor", "torch.no_grad", "logging.getLogger" ]
[((448, 475), 'sys.path.append', 'sys.path.append', (['"""../volta"""'], {}), "('../volta')\n", (463, 475), False, 'import sys\n'), ((476, 500), 'sys.path.append', 'sys.path.append', (['"""volta"""'], {}), "('volta')\n", (491, 500), False, 'import sys\n'), ((671, 698), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (688, 698), False, 'import logging\n'), ((745, 778), 'csv.field_size_limit', 'csv.field_size_limit', (['sys.maxsize'], {}), '(sys.maxsize)\n', (765, 778), False, 'import csv\n'), ((5030, 5049), 'pickle.load', 'pickle.load', (['in_pkl'], {}), '(in_pkl)\n', (5041, 5049), False, 'import pickle\n'), ((5232, 5260), 'os.path.dirname', 'os.path.dirname', (['output_file'], {}), '(output_file)\n', (5247, 5260), False, 'import os\n'), ((5290, 5334), 'h5py.File', 'h5py.File', (['output_file', '"""w"""'], {'libver': '"""latest"""'}), "(output_file, 'w', libver='latest')\n", (5299, 5334), False, 'import h5py\n'), ((2488, 2511), 'os.path.isfile', 'os.path.isfile', (['outfile'], {}), '(outfile)\n', (2502, 2511), False, 'import os\n'), ((6731, 6761), 'torch.tensor', 'torch.tensor', (['[indexed_tokens]'], {}), '([indexed_tokens])\n', (6743, 6761), False, 'import torch\n'), ((6797, 6824), 'torch.tensor', 'torch.tensor', (['[segment_ids]'], {}), '([segment_ids])\n', (6809, 6824), False, 'import torch\n'), ((4080, 4114), 'os.path.basename', 'os.path.basename', (['input_conllx_pkl'], {}), '(input_conllx_pkl)\n', (4096, 4114), False, 'import os\n'), ((6846, 6861), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (6859, 6861), False, 'import torch\n'), ((8535, 8643), 'numpy.mean', 'np.mean', (['baseline_embs[untok_tok_mapping[token_idx][0]:untok_tok_mapping[token_idx][\n -1] + 1, :]'], {'axis': '(0)'}), '(baseline_embs[untok_tok_mapping[token_idx][0]:untok_tok_mapping[\n token_idx][-1] + 1, :], axis=0)\n', (8542, 8643), True, 'import numpy as np\n'), ((7835, 7951), 'numpy.mean', 'np.mean', (['single_layer_features[untok_tok_mapping[token_idx][0]:untok_tok_mapping[\n token_idx][-1] + 1, :]'], {'axis': '(0)'}), '(single_layer_features[untok_tok_mapping[token_idx][0]:\n untok_tok_mapping[token_idx][-1] + 1, :], axis=0)\n', (7842, 7951), True, 'import numpy as np\n'), ((3010, 3035), 'os.path.basename', 'os.path.basename', (['outfile'], {}), '(outfile)\n', (3026, 3035), False, 'import os\n')]
'''' Motion History Image (MHI) is used to calculate the movement coefficient. It shows recent motion in the image. ''' import imutils import numpy as np import sys import cv2 __this = sys.modules[__name__] __this.is_initialized = False __this.mhi_duration = None __this.min_time_delta, __this.max_time_delta = None, None __this.motion_history = None __this.hsv = None __this.timestamp = None __this.prev_frame = None def initialze_mhi(first_frame): if __this.is_initialized is False: # frame = imutils.resize(first_frame, width=500) frame = first_frame h, w = frame.shape[:2] __this.mhi_duration = 10 # 0.5 # __this.min_time_delta, __this.max_time_delta = 0.05, 0.25 __this.motion_history = np.zeros((h, w), np.float32) __this.hsv = np.zeros((h, w, 3), np.uint8) __this.hsv[:,:,1] = 255 __this.timestamp = 0 __this.prev_frame = frame.copy() __this.is_initialized = True else: msg = "MHI is already initialized." raise RuntimeError(msg) def calculate_mhi_frame(fgmask, frame): # 1 calculate & normalize new mhi frame cv2.motempl.updateMotionHistory(fgmask, __this.motion_history, __this.timestamp, __this.mhi_duration) mhi = np.uint8(np.clip((__this.motion_history-(__this.timestamp-__this.mhi_duration)) / __this.mhi_duration, 0, 1)*255) __this.prev_frame = frame.copy() __this.timestamp += 1 return mhi def calculate_movement_coeff(contour, current_frame, previous_frame, test=False): current = current_frame.copy() if __check_if_frame_is_not_white(previous_frame): difference = cv2.absdiff(current_frame, previous_frame) sum_difference = sum(sum(difference)) cnt_area = cv2.contourArea(contour) frm_area = current_frame.shape[0] * current_frame.shape[1] # print(sum_difference, ' * ', cnt_area, ' / ', frm_area) normalised = (sum_difference * cnt_area) / (frm_area * 1000) textName = "test motion coeff " + str(test) cv2.imshow(textName, difference) return round(normalised, 3) else: return 0 def __check_if_frame_is_not_white(frame): return False if sum(sum(frame % 255)) == 0 else True
[ "cv2.contourArea", "cv2.absdiff", "numpy.zeros", "numpy.clip", "cv2.motempl.updateMotionHistory", "cv2.imshow" ]
[((1146, 1252), 'cv2.motempl.updateMotionHistory', 'cv2.motempl.updateMotionHistory', (['fgmask', '__this.motion_history', '__this.timestamp', '__this.mhi_duration'], {}), '(fgmask, __this.motion_history, __this.\n timestamp, __this.mhi_duration)\n', (1177, 1252), False, 'import cv2\n'), ((750, 778), 'numpy.zeros', 'np.zeros', (['(h, w)', 'np.float32'], {}), '((h, w), np.float32)\n', (758, 778), True, 'import numpy as np\n'), ((800, 829), 'numpy.zeros', 'np.zeros', (['(h, w, 3)', 'np.uint8'], {}), '((h, w, 3), np.uint8)\n', (808, 829), True, 'import numpy as np\n'), ((1654, 1696), 'cv2.absdiff', 'cv2.absdiff', (['current_frame', 'previous_frame'], {}), '(current_frame, previous_frame)\n', (1665, 1696), False, 'import cv2\n'), ((1762, 1786), 'cv2.contourArea', 'cv2.contourArea', (['contour'], {}), '(contour)\n', (1777, 1786), False, 'import cv2\n'), ((2049, 2081), 'cv2.imshow', 'cv2.imshow', (['textName', 'difference'], {}), '(textName, difference)\n', (2059, 2081), False, 'import cv2\n'), ((1267, 1374), 'numpy.clip', 'np.clip', (['((__this.motion_history - (__this.timestamp - __this.mhi_duration)) /\n __this.mhi_duration)', '(0)', '(1)'], {}), '((__this.motion_history - (__this.timestamp - __this.mhi_duration)) /\n __this.mhi_duration, 0, 1)\n', (1274, 1374), True, 'import numpy as np\n')]
import os from skimage import io from skimage.color import rgb2gray import numpy as np import dlib import argparse import collections from tqdm import tqdm import cv2 import matplotlib.pyplot as plt IMG_EXTENSIONS = ['.png'] def is_image_file(filename): return any(filename.endswith(extension) for extension in IMG_EXTENSIONS) def get_image_paths_dict(dir): # Returns dict: {name: [path1, path2, ...], ...} image_files = {} assert os.path.isdir(dir), '%s is not a valid directory' % dir for root, _, fnames in sorted(os.walk(dir)): for fname in fnames: if is_image_file(fname) and '/images/' in root: path = os.path.join(root, fname) seq_name = os.path.basename(root).split('_')[0] if seq_name not in image_files: image_files[seq_name] = [path] else: image_files[seq_name].append(path) # Sort paths for each sequence for k, v in image_files.items(): image_files[k] = sorted(v) # Return directory sorted for keys (identity names) return collections.OrderedDict(sorted(image_files.items())) def mkdir(path): if not os.path.exists(path): os.makedirs(path) def save_landmarks(image_pths, landmarks): # Make dirs landmark_pths = [p.replace('/images/', '/landmarks70/') for p in image_pths] out_paths = set(os.path.dirname(landmark_pth) for landmark_pth in landmark_pths) for out_path in out_paths: mkdir(out_path) print('Saving results') for landmark, image_pth in tqdm(zip(landmarks, image_pths), total=len(image_pths)): landmark_file = os.path.splitext(image_pth.replace('/images/', '/landmarks70/'))[0] + '.txt' np.savetxt(landmark_file, landmark) def dirs_exist(image_pths): nmfc_pths = [p.replace('/images/', '/landmarks70/') for p in image_pths] out_paths = set(os.path.dirname(nmfc_pth) for nmfc_pth in nmfc_pths) return all([os.path.exists(out_path) for out_path in out_paths]) def get_mass_center(points, gray): im = np.zeros_like(gray) cv2.fillPoly(im, [points], 1) eyes_image = np.multiply(gray, im) inverse_intensity = np.divide(np.ones_like(eyes_image), eyes_image, out=np.zeros_like(eyes_image), where=eyes_image!=0) max = np.max(inverse_intensity) inverse_intensity = inverse_intensity / max coordinates_grid = np.indices((gray.shape[0], gray.shape[1])) nom = np.sum(np.multiply(coordinates_grid, np.expand_dims(inverse_intensity, axis=0)), axis=(1,2)) denom = np.sum(inverse_intensity) mass_center = np.flip(nom / denom) return mass_center def add_eye_pupils_landmarks(points, image): I = rgb2gray(image) left_eye_points = points[36:42,:] right_eye_points = points[42:48,:] left_pupil = get_mass_center(left_eye_points, I).astype(np.int32) right_pupil = get_mass_center(right_eye_points, I).astype(np.int32) points[68, :] = left_pupil points[69, :] = right_pupil return points def detect_landmarks(img_paths, detector, predictor): landmarks = [] prev_points = None for i in tqdm(range(len(img_paths))): img = io.imread(img_paths[i]) dets = detector(img, 1) if len(dets) > 0: shape = predictor(img, dets[0]) points = np.empty([70, 2], dtype=int) for b in range(68): points[b,0] = shape.part(b).x points[b,1] = shape.part(b).y points = add_eye_pupils_landmarks(points, img) prev_points = points landmarks.append(points) else: print('No face detected, using previous landmarks') landmarks.append(prev_points) return landmarks def main(): print('---------- 70 landmarks detector --------- \n') parser = argparse.ArgumentParser() parser.add_argument('--dataset_name', type=str, default='head2headDataset', help='Path to the dataset directory.') args = parser.parse_args() predictor_path = 'preprocessing/files/shape_predictor_68_face_landmarks.dat' detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor(predictor_path) args.dataset_path = os.path.join('datasets', args.dataset_name, 'dataset') images_dict = get_image_paths_dict(args.dataset_path) n_image_dirs = len(images_dict) print('Number of identities for landmark detection: %d \n' % n_image_dirs) # Iterate through the images_dict n_completed = 0 for name, image_pths in images_dict.items(): n_completed += 1 if not dirs_exist(image_pths): landmarks = detect_landmarks(image_pths, detector, predictor) save_landmarks(image_pths, landmarks) print('(%d/%d) %s [SUCCESS]' % (n_completed, n_image_dirs, name)) else: print('(%d/%d) %s already processed!' % (n_completed, n_image_dirs, name)) if __name__=='__main__': main()
[ "numpy.sum", "argparse.ArgumentParser", "numpy.empty", "os.walk", "cv2.fillPoly", "dlib.shape_predictor", "os.path.join", "numpy.zeros_like", "numpy.multiply", "skimage.color.rgb2gray", "os.path.dirname", "numpy.savetxt", "os.path.exists", "numpy.max", "skimage.io.imread", "numpy.ones_...
[((450, 468), 'os.path.isdir', 'os.path.isdir', (['dir'], {}), '(dir)\n', (463, 468), False, 'import os\n'), ((2072, 2091), 'numpy.zeros_like', 'np.zeros_like', (['gray'], {}), '(gray)\n', (2085, 2091), True, 'import numpy as np\n'), ((2096, 2125), 'cv2.fillPoly', 'cv2.fillPoly', (['im', '[points]', '(1)'], {}), '(im, [points], 1)\n', (2108, 2125), False, 'import cv2\n'), ((2143, 2164), 'numpy.multiply', 'np.multiply', (['gray', 'im'], {}), '(gray, im)\n', (2154, 2164), True, 'import numpy as np\n'), ((2299, 2324), 'numpy.max', 'np.max', (['inverse_intensity'], {}), '(inverse_intensity)\n', (2305, 2324), True, 'import numpy as np\n'), ((2396, 2438), 'numpy.indices', 'np.indices', (['(gray.shape[0], gray.shape[1])'], {}), '((gray.shape[0], gray.shape[1]))\n', (2406, 2438), True, 'import numpy as np\n'), ((2554, 2579), 'numpy.sum', 'np.sum', (['inverse_intensity'], {}), '(inverse_intensity)\n', (2560, 2579), True, 'import numpy as np\n'), ((2598, 2618), 'numpy.flip', 'np.flip', (['(nom / denom)'], {}), '(nom / denom)\n', (2605, 2618), True, 'import numpy as np\n'), ((2696, 2711), 'skimage.color.rgb2gray', 'rgb2gray', (['image'], {}), '(image)\n', (2704, 2711), False, 'from skimage.color import rgb2gray\n'), ((3820, 3845), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (3843, 3845), False, 'import argparse\n'), ((4093, 4125), 'dlib.get_frontal_face_detector', 'dlib.get_frontal_face_detector', ([], {}), '()\n', (4123, 4125), False, 'import dlib\n'), ((4142, 4178), 'dlib.shape_predictor', 'dlib.shape_predictor', (['predictor_path'], {}), '(predictor_path)\n', (4162, 4178), False, 'import dlib\n'), ((4204, 4258), 'os.path.join', 'os.path.join', (['"""datasets"""', 'args.dataset_name', '"""dataset"""'], {}), "('datasets', args.dataset_name, 'dataset')\n", (4216, 4258), False, 'import os\n'), ((540, 552), 'os.walk', 'os.walk', (['dir'], {}), '(dir)\n', (547, 552), False, 'import os\n'), ((1189, 1209), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (1203, 1209), False, 'import os\n'), ((1219, 1236), 'os.makedirs', 'os.makedirs', (['path'], {}), '(path)\n', (1230, 1236), False, 'import os\n'), ((1743, 1778), 'numpy.savetxt', 'np.savetxt', (['landmark_file', 'landmark'], {}), '(landmark_file, landmark)\n', (1753, 1778), True, 'import numpy as np\n'), ((2199, 2223), 'numpy.ones_like', 'np.ones_like', (['eyes_image'], {}), '(eyes_image)\n', (2211, 2223), True, 'import numpy as np\n'), ((3165, 3188), 'skimage.io.imread', 'io.imread', (['img_paths[i]'], {}), '(img_paths[i])\n', (3174, 3188), False, 'from skimage import io\n'), ((1398, 1427), 'os.path.dirname', 'os.path.dirname', (['landmark_pth'], {}), '(landmark_pth)\n', (1413, 1427), False, 'import os\n'), ((1905, 1930), 'os.path.dirname', 'os.path.dirname', (['nmfc_pth'], {}), '(nmfc_pth)\n', (1920, 1930), False, 'import os\n'), ((1974, 1998), 'os.path.exists', 'os.path.exists', (['out_path'], {}), '(out_path)\n', (1988, 1998), False, 'import os\n'), ((2241, 2266), 'numpy.zeros_like', 'np.zeros_like', (['eyes_image'], {}), '(eyes_image)\n', (2254, 2266), True, 'import numpy as np\n'), ((2486, 2527), 'numpy.expand_dims', 'np.expand_dims', (['inverse_intensity'], {'axis': '(0)'}), '(inverse_intensity, axis=0)\n', (2500, 2527), True, 'import numpy as np\n'), ((3312, 3340), 'numpy.empty', 'np.empty', (['[70, 2]'], {'dtype': 'int'}), '([70, 2], dtype=int)\n', (3320, 3340), True, 'import numpy as np\n'), ((667, 692), 'os.path.join', 'os.path.join', (['root', 'fname'], {}), '(root, fname)\n', (679, 692), False, 'import os\n'), ((720, 742), 'os.path.basename', 'os.path.basename', (['root'], {}), '(root)\n', (736, 742), False, 'import os\n')]
import numpy as np import matplotlib.pyplot as plt import pandas as pd import h5pyd import dateutil from pyproj import Proj from operational_analysis.toolkits import timeseries from operational_analysis.toolkits import filters from operational_analysis.toolkits import power_curve from operational_analysis import logged_method_call from operational_analysis import logging logger = logging.getLogger(__name__) class WindToolKitQualityControlDiagnosticSuite(object): """This class defines key analytical procedures in a quality check process for turbine data. After analyzing the data for missing and duplicate timestamps, timezones, Daylight Savings Time corrections, and extrema values, the user can make informed decisions about how to handle the data. """ @logged_method_call def __init__(self,df, ws_field='wmet_wdspd_avg', power_field= 'wtur_W_avg', time_field= 'datetime', id_field= None, freq = '10T', lat_lon= (0,0), dst_subset = 'American', check_tz = False): """ Initialize QCAuto object with data and parameters. Args: df(:obj:`DataFrame object`): DataFrame object that contains data ws_field(:obj: 'String'): String name of the windspeed field to df power_field(:obj: 'String'): String name of the power field to df time_field(:obj: 'String'): String name of the time field to df id_field(:obj: 'String'): String name of the id field to df freq(:obj: 'String'): String representation of the resolution for the time field to df lat_lon(:obj: 'tuple'): latitude and longitude of farm represented as a tuple dst_subset(:obj: 'String'): Set of Daylight Savings Time transitions to use (currently American or France) check_tz(:obj: 'boolean'): Boolean on whether to use WIND Toolkit data to assess timezone of data """ logger.info("Initializing QC_Automation Object") self._df = df self._ws = ws_field self._w = power_field self._t = time_field self._id = id_field self._freq = freq self._lat_lon = lat_lon self._dst_subset = dst_subset self._check_tz = check_tz if self._id==None: self._id = 'ID' self._df['ID'] = 'Data' @logged_method_call def run(self): """ Run the QC analysis functions in order by calling this function. Args: (None) Returns: (None) """ logger.info("Identifying Time Duplications") self.dup_time_identification() logger.info("Identifying Time Gaps") self.gap_time_identification() logger.info('Grabbing DST Transition Times') self.create_dst_df() if self._check_tz: logger.info("Evaluating timezone deviation from UTC") self.ws_diurnal_prep() self.corr_df_calc() logger.info("Isolating Extrema Values") self.max_min() logger.info("QC Diagnostic Complete") def dup_time_identification(self): """ This function identifies any time duplications in the dataset. Args: (None) Returns: (None) """ self._time_duplications = self._df.loc[self._df.duplicated(subset= [self._id, self._t]), self._t] def gap_time_identification(self): """ This function identifies any time gaps in the dataset. Args: (None) Returns: (None) """ self._time_gaps = timeseries.find_time_gaps(self._df[self._t], freq=self._freq) def indicesForCoord(self,f): """ This function finds the nearest x/y indices for a given lat/lon. Rather than fetching the entire coordinates database, which is 500+ MB, this uses the Proj4 library to find a nearby point and then converts to x/y indices. This function relies on the Wind Toolkit HSDS API. Args: f (h5 file): file to be read in Returns: x and y coordinates corresponding to a given lat/lon as a tuple """ dset_coords = f['coordinates'] projstring = """+proj=lcc +lat_1=30 +lat_2=60 +lat_0=38.47240422490422 +lon_0=-96.0 +x_0=0 +y_0=0 +ellps=sphere +units=m +no_defs """ projectLcc = Proj(projstring) origin_ll = reversed(dset_coords[0][0]) # Grab origin directly from database origin = projectLcc(*origin_ll) lat, lon = self._lat_lon coords = (lon, lat) coords = projectLcc(*coords) delta = np.subtract(coords, origin) ij = [int(round(x/2000)) for x in delta] return tuple(reversed(ij)) def ws_diurnal_prep(self, start_date = '2007-01-01', end_date = '2013-12-31'): """ This method links into Wind Toolkit data on AWS as a data source, grabs wind speed data, and calculates diurnal hourly averages. These diurnal hourly averages are returned as a Pandas series. Args: start_date(:obj:'String'): start date to diurnal analysis (optional) end_date(:obj:'String'): end date to diurnal analysis (optional) Returns: ws_diurnal (Pandas Series): Series where each index corresponds to a different hour of the day and each value corresponds to the average windspeed """ f = h5pyd.File("/nrel/wtk-us.h5", 'r') # Setup date and time dt = f["datetime"] dt = pd.DataFrame({"datetime": dt[:]},index=range(0,dt.shape[0])) dt['datetime'] = dt['datetime'].apply(dateutil.parser.parse) project_idx = self.indicesForCoord(f) print("y,x indices for project: \t\t {}".format(project_idx)) print("Coordinates of project: \t {}".format(self._lat_lon)) print("Coordinates of project: \t {}".format(f["coordinates"][project_idx[0]][project_idx[1]])) # Get wind speed at 80m from the specified lat/lon ws = f['windspeed_80m'] t_range = dt.loc[(dt.datetime >= start_date) & (dt.datetime < end_date)].index # Convert to dataframe ws_tseries = ws[min(t_range):max(t_range)+1, project_idx[0], project_idx[1]] ws_df=pd.DataFrame(index=dt.loc[t_range,'datetime'],data={'ws':ws_tseries}) # Calculate diurnal profile of wind speed ws_diurnal=ws_df.groupby(ws_df.index.hour).mean() self._wtk_ws_diurnal= ws_diurnal def wtk_diurnal_plot(self): """ This method plots the WTK diurnal plot alongisde the hourly power averages of the df across all turbines Args: (None) Returns: (None) """ sum_df = self._df.groupby(self._df[self._t])[self._w].sum().to_frame() #df_temp = sum_df.copy() #df_temp[self._t] = df_temp.index #df_diurnal = df_temp.groupby(df_temp[self._t].dt.hour)[self._w].mean() df_diurnal = sum_df.groupby(sum_df.index.hour)[self._w].mean() ws_norm = self._wtk_ws_diurnal/self._wtk_ws_diurnal.mean() df_norm = df_diurnal/df_diurnal.mean() plt.figure(figsize=(8,5)) plt.plot(ws_norm, label = 'WTK wind speed (UTC)') plt.plot(df_norm, label = 'QC power') plt.grid() plt.xlabel('Hour of day') plt.ylabel('Normalized values') plt.title('WTK and QC Timezone Comparison') plt.legend() plt.show() def corr_df_calc(self): """ This method creates a correlation series that compares the current power data (with different shift thresholds) to wind speed data from the WTK with hourly resolution. Args: (None) Returns: (None) """ self._df_diurnal = self._df.groupby(self._df[self._t].dt.hour)[self._w].mean() return_corr = np.empty((24)) for i in np.arange(24): return_corr[i] = np.corrcoef(self._wtk_ws_diurnal['ws'], np.roll(self._df_diurnal,i))[0,1] self._hour_shift = pd.DataFrame(index = np.arange(24), data = {'corr_by_hour': return_corr}) def create_dst_df(self): if self._dst_subset == 'American': # American DST Transition Dates (Local Time) self._dst_dates = pd.DataFrame() self._dst_dates['year'] = [2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019] self._dst_dates['start'] = ['3/9/08 2:00', '3/8/09 2:00', '3/14/10 2:00', '3/13/11 2:00', '3/11/12 2:00', '3/10/13 2:00', '3/9/14 2:00', '3/8/15 2:00', '3/13/16 2:00', '3/12/17 2:00', '3/11/18 2:00' , '3/10/19 2:00'] self._dst_dates['end'] = ['11/2/08 2:00', '11/1/09 2:00', '11/7/10 2:00', '11/6/11 2:00', '11/4/12 2:00', '11/3/13 2:00', '11/2/14 2:00', '11/1/15 2:00', '11/6/16 2:00', '11/5/17 2:00', '11/4/18 2:00', '11/3/19 2:00'] else: # European DST Transition Dates (Local Time) self._dst_dates = pd.DataFrame() self._dst_dates['year'] = [2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019] self._dst_dates['start'] = ['3/30/08 2:00', '3/29/09 2:00', '3/28/10 2:00', '3/27/11 2:00', '3/25/12 2:00', '3/31/13 2:00', '3/30/14 2:00', '3/29/15 2:00', '3/27/16 2:00', '3/26/17 2:00', '3/25/18 2:00' , '3/31/19 2:00'] self._dst_dates['end'] = ['10/26/08 3:00', '10/25/09 3:00', '10/31/10 3:00', '10/30/11 3:00', '10/28/12 3:00', '10/27/13 3:00', '10/26/14 3:00', '10/25/15 3:00', '10/30/16 3:00', '10/29/17 3:00', '10/28/18 3:00', '10/27/19 3:00'] def daylight_savings_plot(self, hour_window = 3): """ Produce a timeseries plot showing daylight savings events for each year using the passed data. Args: hour_window(:obj: 'int'): number of hours outside of the Daylight Savings Time transitions to view in the plot (optional) Returns: (None) """ self._df_dst = self._df.loc[self._df[self._id]==self._df[self._id].unique()[0], :] df_full = timeseries.gap_fill_data_frame(self._df_dst, self._t, self._freq) # Gap fill so spring ahead is visible df_full.set_index(self._t, inplace=True) self._df_full = df_full years = df_full.index.year.unique() # Years in data record num_years = len(years) plt.figure(figsize = (12,20)) for y in np.arange(num_years): dst_data = self._dst_dates.loc[self._dst_dates['year'] == years[y]] # Set spring ahead window to plot spring_start = pd.to_datetime(dst_data['start']) - pd.Timedelta(hours = hour_window) spring_end = pd.to_datetime(dst_data['start']) + pd.Timedelta(hours = hour_window) # Set fall back window to plot fall_start = pd.to_datetime(dst_data['end']) - pd.Timedelta(hours = hour_window) fall_end = pd.to_datetime(dst_data['end']) + pd.Timedelta(hours = hour_window) # Get data corresponding to each data_spring = df_full.loc[(df_full.index > spring_start.values[0]) & (df_full.index < spring_end.values[0])] data_fall = df_full.loc[(df_full.index > fall_start.values[0]) & (df_full.index < fall_end.values[0])] # Plot each as side-by-side subplots plt.subplot(num_years, 2, 2*y + 1) if np.sum(~np.isnan(data_spring[self._w])) > 0: plt.plot(data_spring[self._w]) plt.title(str(years[y]) + ', Spring') plt.ylabel('Power') plt.xlabel('Date') plt.subplot(num_years, 2, 2*y + 2) if np.sum(~np.isnan(data_fall[self._w])) > 0: plt.plot(data_fall[self._w]) plt.title(str(years[y]) + ', Fall') plt.ylabel('Power') plt.xlabel('Date') plt.tight_layout() plt.show() def max_min(self): """ This function creates a DataFrame that contains the max and min values for each column Args: (None) Returns: (None) """ self._max_min = pd.DataFrame(index = self._df.columns, columns = {'max', 'min'}) self._max_min['max'] = self._df.max() self._max_min['min'] = self._df.min() def plot_by_id(self, x_axis = None, y_axis = None): """ This is generalized function that allows the user to plot any two fields against each other with unique plots for each unique ID. For scada data, this function produces turbine plots and for meter data, this will return a single plot. Args: x_axis(:obj:'String'): Independent variable to plot (default is windspeed field) y_axis(:obj:'String'): Dependent variable to plot (default is power field) Returns: (None) """ if x_axis is None: x_axis = self._ws if y_axis is None: y_axis = self._w turbs = self._df[self._id].unique() num_turbs = len(turbs) num_rows = np.ceil(num_turbs/4.) plt.figure(figsize = (15,num_rows * 5)) n = 1 for t in turbs: plt.subplot(num_rows, 4, n) scada_sub = self._df.loc[self._df[self._id] == t, :] plt.scatter(scada_sub[x_axis], scada_sub[y_axis], s = 5) n = n + 1 plt.title(t) plt.xlabel(x_axis) plt.ylabel(y_axis) plt.tight_layout() plt.show() def column_histograms(self): """ Produces histogram plot for each numeric column. Args: (None) Returns: (None) """ for c in self._df.columns: if (self._df[c].dtype==float) | (self._df[c].dtype==int): #plt.subplot(2,2,n) plt.figure(figsize=(8,6)) plt.hist(self._df[c].dropna(), 40) #n = n + 1 plt.title(c) plt.ylabel('Count') plt.show()
[ "matplotlib.pyplot.title", "numpy.empty", "numpy.isnan", "matplotlib.pyplot.figure", "numpy.arange", "h5pyd.File", "matplotlib.pyplot.tight_layout", "pandas.DataFrame", "pandas.Timedelta", "operational_analysis.toolkits.timeseries.gap_fill_data_frame", "matplotlib.pyplot.show", "numpy.ceil", ...
[((385, 412), 'operational_analysis.logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (402, 412), False, 'from operational_analysis import logging\n'), ((3592, 3653), 'operational_analysis.toolkits.timeseries.find_time_gaps', 'timeseries.find_time_gaps', (['self._df[self._t]'], {'freq': 'self._freq'}), '(self._df[self._t], freq=self._freq)\n', (3617, 3653), False, 'from operational_analysis.toolkits import timeseries\n'), ((4450, 4466), 'pyproj.Proj', 'Proj', (['projstring'], {}), '(projstring)\n', (4454, 4466), False, 'from pyproj import Proj\n'), ((4708, 4735), 'numpy.subtract', 'np.subtract', (['coords', 'origin'], {}), '(coords, origin)\n', (4719, 4735), True, 'import numpy as np\n'), ((5501, 5535), 'h5pyd.File', 'h5pyd.File', (['"""/nrel/wtk-us.h5"""', '"""r"""'], {}), "('/nrel/wtk-us.h5', 'r')\n", (5511, 5535), False, 'import h5pyd\n'), ((6338, 6410), 'pandas.DataFrame', 'pd.DataFrame', ([], {'index': "dt.loc[t_range, 'datetime']", 'data': "{'ws': ws_tseries}"}), "(index=dt.loc[t_range, 'datetime'], data={'ws': ws_tseries})\n", (6350, 6410), True, 'import pandas as pd\n'), ((7248, 7274), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 5)'}), '(figsize=(8, 5))\n', (7258, 7274), True, 'import matplotlib.pyplot as plt\n'), ((7282, 7329), 'matplotlib.pyplot.plot', 'plt.plot', (['ws_norm'], {'label': '"""WTK wind speed (UTC)"""'}), "(ws_norm, label='WTK wind speed (UTC)')\n", (7290, 7329), True, 'import matplotlib.pyplot as plt\n'), ((7340, 7375), 'matplotlib.pyplot.plot', 'plt.plot', (['df_norm'], {'label': '"""QC power"""'}), "(df_norm, label='QC power')\n", (7348, 7375), True, 'import matplotlib.pyplot as plt\n'), ((7386, 7396), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (7394, 7396), True, 'import matplotlib.pyplot as plt\n'), ((7405, 7430), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Hour of day"""'], {}), "('Hour of day')\n", (7415, 7430), True, 'import matplotlib.pyplot as plt\n'), ((7439, 7470), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Normalized values"""'], {}), "('Normalized values')\n", (7449, 7470), True, 'import matplotlib.pyplot as plt\n'), ((7479, 7522), 'matplotlib.pyplot.title', 'plt.title', (['"""WTK and QC Timezone Comparison"""'], {}), "('WTK and QC Timezone Comparison')\n", (7488, 7522), True, 'import matplotlib.pyplot as plt\n'), ((7531, 7543), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (7541, 7543), True, 'import matplotlib.pyplot as plt\n'), ((7552, 7562), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (7560, 7562), True, 'import matplotlib.pyplot as plt\n'), ((7973, 7985), 'numpy.empty', 'np.empty', (['(24)'], {}), '(24)\n', (7981, 7985), True, 'import numpy as np\n'), ((8006, 8019), 'numpy.arange', 'np.arange', (['(24)'], {}), '(24)\n', (8015, 8019), True, 'import numpy as np\n'), ((10152, 10217), 'operational_analysis.toolkits.timeseries.gap_fill_data_frame', 'timeseries.gap_fill_data_frame', (['self._df_dst', 'self._t', 'self._freq'], {}), '(self._df_dst, self._t, self._freq)\n', (10182, 10217), False, 'from operational_analysis.toolkits import timeseries\n'), ((10445, 10473), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(12, 20)'}), '(figsize=(12, 20))\n', (10455, 10473), True, 'import matplotlib.pyplot as plt\n'), ((10493, 10513), 'numpy.arange', 'np.arange', (['num_years'], {}), '(num_years)\n', (10502, 10513), True, 'import numpy as np\n'), ((11932, 11950), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (11948, 11950), True, 'import matplotlib.pyplot as plt\n'), ((11959, 11969), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (11967, 11969), True, 'import matplotlib.pyplot as plt\n'), ((12202, 12262), 'pandas.DataFrame', 'pd.DataFrame', ([], {'index': 'self._df.columns', 'columns': "{'max', 'min'}"}), "(index=self._df.columns, columns={'max', 'min'})\n", (12214, 12262), True, 'import pandas as pd\n'), ((13133, 13157), 'numpy.ceil', 'np.ceil', (['(num_turbs / 4.0)'], {}), '(num_turbs / 4.0)\n', (13140, 13157), True, 'import numpy as np\n'), ((13164, 13202), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(15, num_rows * 5)'}), '(figsize=(15, num_rows * 5))\n', (13174, 13202), True, 'import matplotlib.pyplot as plt\n'), ((13533, 13551), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (13549, 13551), True, 'import matplotlib.pyplot as plt\n'), ((13560, 13570), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (13568, 13570), True, 'import matplotlib.pyplot as plt\n'), ((8383, 8397), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (8395, 8397), True, 'import pandas as pd\n'), ((9070, 9084), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (9082, 9084), True, 'import pandas as pd\n'), ((11406, 11442), 'matplotlib.pyplot.subplot', 'plt.subplot', (['num_years', '(2)', '(2 * y + 1)'], {}), '(num_years, 2, 2 * y + 1)\n', (11417, 11442), True, 'import matplotlib.pyplot as plt\n'), ((11610, 11629), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Power"""'], {}), "('Power')\n", (11620, 11629), True, 'import matplotlib.pyplot as plt\n'), ((11642, 11660), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Date"""'], {}), "('Date')\n", (11652, 11660), True, 'import matplotlib.pyplot as plt\n'), ((11674, 11710), 'matplotlib.pyplot.subplot', 'plt.subplot', (['num_years', '(2)', '(2 * y + 2)'], {}), '(num_years, 2, 2 * y + 2)\n', (11685, 11710), True, 'import matplotlib.pyplot as plt\n'), ((11872, 11891), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Power"""'], {}), "('Power')\n", (11882, 11891), True, 'import matplotlib.pyplot as plt\n'), ((11904, 11922), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Date"""'], {}), "('Date')\n", (11914, 11922), True, 'import matplotlib.pyplot as plt\n'), ((13254, 13281), 'matplotlib.pyplot.subplot', 'plt.subplot', (['num_rows', '(4)', 'n'], {}), '(num_rows, 4, n)\n', (13265, 13281), True, 'import matplotlib.pyplot as plt\n'), ((13359, 13413), 'matplotlib.pyplot.scatter', 'plt.scatter', (['scada_sub[x_axis]', 'scada_sub[y_axis]'], {'s': '(5)'}), '(scada_sub[x_axis], scada_sub[y_axis], s=5)\n', (13370, 13413), True, 'import matplotlib.pyplot as plt\n'), ((13450, 13462), 'matplotlib.pyplot.title', 'plt.title', (['t'], {}), '(t)\n', (13459, 13462), True, 'import matplotlib.pyplot as plt\n'), ((13475, 13493), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['x_axis'], {}), '(x_axis)\n', (13485, 13493), True, 'import matplotlib.pyplot as plt\n'), ((13506, 13524), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['y_axis'], {}), '(y_axis)\n', (13516, 13524), True, 'import matplotlib.pyplot as plt\n'), ((8173, 8186), 'numpy.arange', 'np.arange', (['(24)'], {}), '(24)\n', (8182, 8186), True, 'import numpy as np\n'), ((10669, 10702), 'pandas.to_datetime', 'pd.to_datetime', (["dst_data['start']"], {}), "(dst_data['start'])\n", (10683, 10702), True, 'import pandas as pd\n'), ((10705, 10736), 'pandas.Timedelta', 'pd.Timedelta', ([], {'hours': 'hour_window'}), '(hours=hour_window)\n', (10717, 10736), True, 'import pandas as pd\n'), ((10764, 10797), 'pandas.to_datetime', 'pd.to_datetime', (["dst_data['start']"], {}), "(dst_data['start'])\n", (10778, 10797), True, 'import pandas as pd\n'), ((10800, 10831), 'pandas.Timedelta', 'pd.Timedelta', ([], {'hours': 'hour_window'}), '(hours=hour_window)\n', (10812, 10831), True, 'import pandas as pd\n'), ((10903, 10934), 'pandas.to_datetime', 'pd.to_datetime', (["dst_data['end']"], {}), "(dst_data['end'])\n", (10917, 10934), True, 'import pandas as pd\n'), ((10937, 10968), 'pandas.Timedelta', 'pd.Timedelta', ([], {'hours': 'hour_window'}), '(hours=hour_window)\n', (10949, 10968), True, 'import pandas as pd\n'), ((10994, 11025), 'pandas.to_datetime', 'pd.to_datetime', (["dst_data['end']"], {}), "(dst_data['end'])\n", (11008, 11025), True, 'import pandas as pd\n'), ((11028, 11059), 'pandas.Timedelta', 'pd.Timedelta', ([], {'hours': 'hour_window'}), '(hours=hour_window)\n', (11040, 11059), True, 'import pandas as pd\n'), ((11517, 11547), 'matplotlib.pyplot.plot', 'plt.plot', (['data_spring[self._w]'], {}), '(data_spring[self._w])\n', (11525, 11547), True, 'import matplotlib.pyplot as plt\n'), ((11783, 11811), 'matplotlib.pyplot.plot', 'plt.plot', (['data_fall[self._w]'], {}), '(data_fall[self._w])\n', (11791, 11811), True, 'import matplotlib.pyplot as plt\n'), ((13923, 13949), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 6)'}), '(figsize=(8, 6))\n', (13933, 13949), True, 'import matplotlib.pyplot as plt\n'), ((14043, 14055), 'matplotlib.pyplot.title', 'plt.title', (['c'], {}), '(c)\n', (14052, 14055), True, 'import matplotlib.pyplot as plt\n'), ((14072, 14091), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Count"""'], {}), "('Count')\n", (14082, 14091), True, 'import matplotlib.pyplot as plt\n'), ((14108, 14118), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (14116, 14118), True, 'import matplotlib.pyplot as plt\n'), ((8090, 8118), 'numpy.roll', 'np.roll', (['self._df_diurnal', 'i'], {}), '(self._df_diurnal, i)\n', (8097, 8118), True, 'import numpy as np\n'), ((11464, 11494), 'numpy.isnan', 'np.isnan', (['data_spring[self._w]'], {}), '(data_spring[self._w])\n', (11472, 11494), True, 'import numpy as np\n'), ((11732, 11760), 'numpy.isnan', 'np.isnan', (['data_fall[self._w]'], {}), '(data_fall[self._w])\n', (11740, 11760), True, 'import numpy as np\n')]
import time from collections import defaultdict import math import torch from data_tools.data_interface import GraphContainer from model_wrapper import ModelWrapper from models.HiLi.model import Model from models.tgn.utils import get_neighbor_finder, EarlyStopMonitor, MLP import torch.nn.functional as F import evaluation import numpy as np import os class HiliWrapper(ModelWrapper): default_arg_config = { "data": "wikipedia", "emb_dim": 128, "size": 3, "item_max": 3, "item_pow": 0.75, "user_max": 4, "user_pow": 0.75, "uniform": True, "lr": 3e-4, "lr_decoder": 3e-4, "n_epoch": 1, 'patience':5, "drop_out": 0.1, 'n_degree':10, } def __init__(self, config=None, model_id=None): self.config = {**self.default_arg_config} if not (config is None): self.new_config = config self.config = {**self.config, **self.new_config} if model_id is None: self.model_id = f'hili_at_{time.ctime()}' else: self.model_id = f'{model_id} at {time.ctime()}' self.model_id = self.model_id.replace(':', '_') self.logger = self.prepare_logger(self.model_id) # self.history = { # 'user_history': defaultdict(lambda: Queue(self.default_arg_config['size'])), # 'item_history': defaultdict(lambda: Queue(self.default_arg_config['size'])), # } def initialize_model(self, full_data: GraphContainer, train_data, node_features, edge_features, batch_params, data_setting_mode='transductive'): self.device = f'cuda:{self.config["gpu"]}' if torch.cuda.is_available() and not self.config[ 'force_cpu'] else 'cpu' self.edge_features = edge_features self.num_feats = edge_features.edge_table.shape[1] self.num_users = len(set(full_data.edge_table[:, 2])) self.num_items = len(set(full_data.edge_table[:, 3])) self.not_bipartite = self.config["data"] not in ["wikipedia", "reddit"] self.eth_flg = "eth" in self.config["data"] if self.not_bipartite: self.num_users = full_data.n_unique_nodes self.num_items = full_data.n_unique_nodes self.model = Model(self.config["emb_dim"], self.config["emb_dim"], self.num_users, self.num_items, self.num_feats, self.config["size"]) self.model = self.model.to(self.device) self.max_idx = max(full_data.unique_nodes) self.train_ngh_finder = get_neighbor_finder(train_data, uniform=self.config['uniform'], max_node_idx=self.max_idx) self.full_ngh_finder = get_neighbor_finder(full_data, uniform=self.config['uniform']) self.criterion = torch.nn.BCELoss() self.optimizer = torch.optim.Adam(self.model.parameters(), lr=self.config['lr']) self.batch_params = batch_params self.dyn_user_emb = F.normalize(torch.rand((self.num_users, self.config["emb_dim"])), dim=1) self.stat_user_emb = torch.eye(self.num_users) if not self.eth_flg: self.dyn_item_emb = F.normalize(torch.rand((self.num_items, self.config["emb_dim"])), dim=1) self.stat_item_emb = torch.eye(self.num_items) * self.config["item_max"] def compute_clf_probability( self, data, eval_mode, data_setting_mode, **kwargs): self.decoder.eval() self.model.eval() self.process_batch(data) return self.decoder(self.dyn_user_emb[data[0]]).sigmoid() def compute_edge_probabilities(self, batch, negatives, eval_mode, data_setting_mode, **model_params): _, pos, neg = self.process_batch(batch, negatives) return -pos, -neg def load_model(self, model_path): if not (model_path is None) and os.path.isfile(model_path): self.model.load_state_dict(torch.load(model_path)) is_trained = True else: is_trained = False return is_trained def train_model(self, train_data, val_data, train_sampler, val_sampler, do_clf): train_metrics_1 = self.train_self_supervised(train_data, val_data, train_sampler, val_sampler ) if do_clf: train_metrics_2 = self.train_supervised(train_data, val_data, train_sampler, val_sampler) else: train_metrics_2 = {} return {'train_unsupervised':train_metrics_1, 'train_supervised':train_metrics_2} def train_supervised(self, train_data, val_data, train_sampler, val_sampler): num_instance = train_data.edge_table.shape[0] # num_batch = math.ceil(num_instance / self.batch_params['train']["batch_size"]) self.logger.debug('Num of training instances: {}'.format(num_instance)) self.model.eval() self.logger.info('TGN models loaded') self.logger.info('Start training node classification task') self.decoder = self.get_decoder(self.config["emb_dim"]) self.decoder_optimizer = torch.optim.Adam(self.decoder.parameters(), lr=self.config['lr_decoder']) self.decoder = self.decoder.to(self.device) self.decoder_loss_criterion = torch.nn.BCELoss() train_metrics = defaultdict(list) early_stopper = EarlyStopMonitor(max_round=self.config['patience']) for epoch in range(self.config['n_epoch']): start_epoch = time.time() self.model = self.model.train() self.decoder = self.decoder.train() self.dyn_user_emb = F.normalize(torch.rand((self.num_users, self.config["emb_dim"])), dim=1) self.stat_user_emb = torch.eye(self.num_users) if not self.eth_flg: self.dyn_item_emb = F.normalize(torch.rand((self.num_items, self.config["emb_dim"])), dim=1) self.stat_item_emb = torch.eye(self.num_items) * self.config["item_max"] loss = 0 for i, batch in enumerate(train_data(**self.batch_params['train'])): self.decoder_optimizer.zero_grad() enc_loss, _, _ = self.process_batch(batch) labels_batch_torch = torch.from_numpy(batch[4]).float().to(self.device) pred = self.decoder(self.dyn_user_emb[batch[0]]).sigmoid() decoder_loss = self.decoder_loss_criterion(pred, labels_batch_torch) + enc_loss decoder_loss.backward() self.decoder_optimizer.step() loss += decoder_loss.item() train_metrics['train_losses'].append(loss / i+1) val_auc = evaluation.eval_node_bin_classification( model=self, data=val_data, data_setting_mode='transductive', batch_params=self.batch_params['val'], eval_mode='val', n_neighbors=self.config['n_degree']) train_metrics['val_aucs'].append(val_auc['AUC ROC']) train_metrics['epoch_times'].append(time.time() - start_epoch) self.logger.info( f'Epoch {epoch}: train loss: {train_metrics["train_losses"][-1]}, val auc: {train_metrics["val_aucs"][-1]}, time: {train_metrics["epoch_times"][-1]}') if early_stopper.early_stop_check(val_auc['AUC ROC']): self.logger.info('No improvement over {} epochs, stop training'.format(early_stopper.max_round)) break else: torch.save(self.decoder.state_dict(), self.get_checkpoint_path(epoch, 'decoder')) self.logger.info(f'Loading the best model at epoch {early_stopper.best_epoch}') best_model_path = self.get_checkpoint_path(early_stopper.best_epoch, 'decoder') self.decoder.load_state_dict(torch.load(best_model_path)) torch.save(self.decoder.state_dict(), self.get_checkpoint_path(-1, 'decoder')) self.logger.info(f'Loaded the best model at epoch {early_stopper.best_epoch} for inference') self.decoder.eval() return train_metrics def train_self_supervised(self, train_data, val_data, train_sampler, val_sampler): num_instance = len(train_data.edge_table) # num_batch = math.ceil(num_instance / self.batch_params['train']["batch_size"]) self.logger.info('num of training instances: {}'.format(num_instance)) # self.logger.info('num of batches per epoch: {}'.format(num_batch)) train_metrics = defaultdict(list) self.early_stopper = EarlyStopMonitor(max_round=self.config['patience']) for epoch in range(self.config['n_epoch']): self.logger.info('start {} epoch'.format(epoch)) start_epoch = time.time() m_loss = [] start = None training_data = train_data(**self.batch_params['train']) self.dyn_user_emb = F.normalize(torch.rand((self.num_users, self.config["emb_dim"])), dim=1) self.stat_user_emb = torch.eye(self.num_users) if not self.eth_flg: self.dyn_item_emb = F.normalize(torch.rand((self.num_items, self.config["emb_dim"])), dim=1) self.stat_item_emb = torch.eye(self.num_items) * self.config["item_max"] for i, batch in enumerate(training_data): self.optimizer.zero_grad() if i % 100 == 0: print(f'{i}/{training_data.num_batches} batches passed ... It took {round(time.time() - start if start else 0, 2)} seconds') start = time.time() self.model = self.model.train() loss, _, _ = self.process_batch(batch) loss.backward() self.optimizer.step() m_loss.append(loss.item()) epoch_time = time.time() - start_epoch train_metrics['epoch_times'].append(epoch_time) transductive_val = evaluation.eval_edge_prediction(model=self, data=val_data, negative_edge_sampler=val_sampler, data_setting_mode='transductive', batch_params=self.batch_params['val'], eval_mode='val', n_neighbors=self.config['n_degree'], ) train_metrics['val_aps'].append(transductive_val['AP']) train_metrics['train_losses'].append(np.mean(m_loss)) total_epoch_time = time.time() - start_epoch # train_metrics['total_epoch_times'].append(total_epoch_time) self.logger.info('epoch: {} took {:.2f}s'.format(epoch, total_epoch_time)) self.logger.info(f'Epoch mean loss: {np.mean(m_loss)}') self.logger.info(f'val auc: {transductive_val["AUC"]}') self.logger.info(f'val ap: {transductive_val["AP"]} ') # Early stopping if self.early_stopper.early_stop_check(transductive_val['AP']): self.logger.info(f'No improvement over {self.early_stopper.max_round} epochs, stop training') self.logger.info(f'Loading the best model at epoch {self.early_stopper.best_epoch}') best_model_path = self.get_checkpoint_path(self.early_stopper.best_epoch) self.model.load_state_dict(torch.load(best_model_path)) torch.save(self.model.state_dict(), self.get_checkpoint_path(-1, 'graph')) self.logger.info(f'Loaded the best model at epoch {self.early_stopper.best_epoch} for inference') self.model.eval() break elif (epoch+1==self.config['n_epoch']): self.model.eval() torch.save(self.model.state_dict(), self.get_checkpoint_path(epoch, 'graph')) return train_metrics def process_batch(self, batch, negatives=None): ( sources_batch, destinations_batch, timestamps_batch, edge_idxs_batch, labels, ) = batch self.dyn_user_emb.detach_() if not self.eth_flg: self.dyn_item_emb.detach_() loss = 0 sources_batch = torch.Tensor(sources_batch).type(torch.LongTensor) destinations_batch = torch.Tensor(destinations_batch).type(torch.LongTensor) timestamps_batch = torch.Tensor(timestamps_batch) src_neighbors, src_edge_idxs, src_edge_times = (self.full_ngh_finder if negatives is not None else self.train_ngh_finder).get_temporal_neighbor( sources_batch,timestamps_batch, n_neighbors=self.config["size"]) src_neighbors = torch.Tensor(src_neighbors).type(torch.LongTensor) src_edge_times = torch.Tensor(src_edge_times) dst_neighbors, dst_edge_idxs, dst_edge_times = (self.full_ngh_finder if negatives is not None else self.train_ngh_finder).get_temporal_neighbor( destinations_batch, timestamps_batch, n_neighbors=self.config["size"]) dst_edge_times = torch.Tensor(dst_edge_times) src_neighbors = torch.where(src_neighbors == 0, 0, src_neighbors - self.num_users) if self.config["data"] in ["wikipedia", "reddit"] else src_neighbors destinations_batch = torch.where(destinations_batch == 0, 0, destinations_batch - self.num_users) if self.config["data"] in ["wikipedia", "reddit"] else destinations_batch user_emb = self.dyn_user_emb[sources_batch] if not self.eth_flg: item_emb = self.dyn_item_emb[destinations_batch] prev_emb = self.dyn_item_emb[src_neighbors] else: item_emb = self.dyn_user_emb[destinations_batch] prev_emb = self.dyn_user_emb[src_neighbors] # TODO think about window normalizations item_prev_sum = self.model( prev_emb, mode='prev', freq=torch.ones_like(src_neighbors).type(torch.FloatTensor), item_max=self.config["item_max"], item_pow=self.config["item_pow"]) item_stat = self.model(mode='stat', freq=torch.ones_like(src_neighbors).type(torch.FloatTensor), item_stat=self.stat_item_emb[src_neighbors] if not self.eth_flg else self.stat_user_emb[src_neighbors], item_max=self.config["item_max"], item_pow=self.config["item_pow"]) item_pred_emb = self.model( torch.cat([user_emb, item_prev_sum], dim=1).detach(), mode='pred', item_stat=item_stat, user_stat=self.stat_user_emb[sources_batch], freq=torch.ones(item_prev_sum.size(0)), user_max=self.config["user_max"], user_pow=self.config["user_pow"] ) pos_probs = None neg_probs = None if negatives is not None: if not self.eth_flg: pos_dyn = self.dyn_item_emb[destinations_batch] pos_stat = self.stat_item_emb[destinations_batch] else: pos_dyn = self.dyn_user_emb[destinations_batch] pos_stat = self.stat_user_emb[destinations_batch] negatives = torch.Tensor(negatives).type(torch.LongTensor) negatives = torch.where(negatives == 0, 0, negatives - self.num_users) if self.config["data"] in ["wikipedia", "reddit"] else negatives if not self.eth_flg: neg_dyn = self.dyn_item_emb[negatives] neg_stat = self.stat_item_emb[negatives] else: neg_dyn = self.dyn_user_emb[negatives] neg_stat = self.stat_user_emb[negatives] pos_probs = ((torch.cat([pos_dyn, pos_stat], dim=1) - item_pred_emb)**2).sum(1).detach() neg_probs = ((torch.cat([neg_dyn, neg_stat], dim=1) - item_pred_emb)**2).sum(1).detach() loss += ((item_pred_emb - torch.cat([item_emb, self.stat_item_emb[destinations_batch]] if not self.eth_flg else self.stat_user_emb[destinations_batch], dim = 1 ).detach()) ** 2).sum(dim=1).mean() edge_feats = torch.Tensor(self.edge_features.edge_table[edge_idxs_batch]) user_emb_nxt = self.model(user_emb, torch.cat([item_emb, (timestamps_batch - src_edge_times[:, -1]).reshape(-1,1), edge_feats], dim=1 ).detach(), mode='user' ) item_emb_nxt = self.model(torch.cat([user_emb, (timestamps_batch - dst_edge_times[:, -1]).reshape(-1,1), edge_feats], dim=1 ).detach(), item_emb, mode='item' ) item_emb_pre = self.model(item_emb, prev_emb, mode='addi', freq=torch.ones_like(src_neighbors).type(torch.FloatTensor), item_max=self.config["item_max"], item_pow=self.config["item_pow"]) loss += ((user_emb_nxt - user_emb) ** 2).sum(dim=1).mean() loss += ((item_emb_nxt - item_emb) ** 2).sum(dim=1).mean() self.dyn_user_emb[sources_batch] = user_emb_nxt if not self.eth_batch: self.dyn_item_emb[destinations_batch] = item_emb_nxt self.dyn_item_emb[src_neighbors] = item_emb_pre else: self.dyn_user_emb[destinations_batch] = item_emb_nxt self.dyn_user_emb[src_neighbors] = item_emb_pre return loss, pos_probs, neg_probs def get_inference_params(self): return {'n_neighbors':self.config['n_degree']} def get_decoder(self, emb_dim): return MLP(emb_dim, drop = self.config['drop_out']) def get_results_path(self,): return os.path.join(f'./logs/{self.model_id}.pkl') def get_checkpoint_path(self,epoch, part='graph', final=False): """ If epoch<0, the training is done and we want path to final model """ if not os.path.isdir('./saved_checkpoints'): os.mkdir('./saved_checkpoints') if epoch<0: return f'./saved_checkpoints/HiLi-{self.model_id}-{part}-final.pth' else: return f'./saved_checkpoints/HiLi-{self.model_id}-{part}-{epoch}.pth'
[ "os.mkdir", "torch.eye", "models.tgn.utils.EarlyStopMonitor", "time.ctime", "torch.cat", "collections.defaultdict", "os.path.isfile", "numpy.mean", "models.tgn.utils.MLP", "os.path.join", "models.HiLi.model.Model", "evaluation.eval_edge_prediction", "torch.nn.BCELoss", "torch.load", "mod...
[((2335, 2462), 'models.HiLi.model.Model', 'Model', (["self.config['emb_dim']", "self.config['emb_dim']", 'self.num_users', 'self.num_items', 'self.num_feats', "self.config['size']"], {}), "(self.config['emb_dim'], self.config['emb_dim'], self.num_users, self.\n num_items, self.num_feats, self.config['size'])\n", (2340, 2462), False, 'from models.HiLi.model import Model\n'), ((2591, 2685), 'models.tgn.utils.get_neighbor_finder', 'get_neighbor_finder', (['train_data'], {'uniform': "self.config['uniform']", 'max_node_idx': 'self.max_idx'}), "(train_data, uniform=self.config['uniform'],\n max_node_idx=self.max_idx)\n", (2610, 2685), False, 'from models.tgn.utils import get_neighbor_finder, EarlyStopMonitor, MLP\n'), ((2765, 2827), 'models.tgn.utils.get_neighbor_finder', 'get_neighbor_finder', (['full_data'], {'uniform': "self.config['uniform']"}), "(full_data, uniform=self.config['uniform'])\n", (2784, 2827), False, 'from models.tgn.utils import get_neighbor_finder, EarlyStopMonitor, MLP\n'), ((2854, 2872), 'torch.nn.BCELoss', 'torch.nn.BCELoss', ([], {}), '()\n', (2870, 2872), False, 'import torch\n'), ((3134, 3159), 'torch.eye', 'torch.eye', (['self.num_users'], {}), '(self.num_users)\n', (3143, 3159), False, 'import torch\n'), ((5310, 5328), 'torch.nn.BCELoss', 'torch.nn.BCELoss', ([], {}), '()\n', (5326, 5328), False, 'import torch\n'), ((5362, 5379), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (5373, 5379), False, 'from collections import defaultdict\n'), ((5413, 5464), 'models.tgn.utils.EarlyStopMonitor', 'EarlyStopMonitor', ([], {'max_round': "self.config['patience']"}), "(max_round=self.config['patience'])\n", (5429, 5464), False, 'from models.tgn.utils import get_neighbor_finder, EarlyStopMonitor, MLP\n'), ((8649, 8666), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (8660, 8666), False, 'from collections import defaultdict\n'), ((8696, 8747), 'models.tgn.utils.EarlyStopMonitor', 'EarlyStopMonitor', ([], {'max_round': "self.config['patience']"}), "(max_round=self.config['patience'])\n", (8712, 8747), False, 'from models.tgn.utils import get_neighbor_finder, EarlyStopMonitor, MLP\n'), ((12930, 12960), 'torch.Tensor', 'torch.Tensor', (['timestamps_batch'], {}), '(timestamps_batch)\n', (12942, 12960), False, 'import torch\n'), ((13301, 13329), 'torch.Tensor', 'torch.Tensor', (['src_edge_times'], {}), '(src_edge_times)\n', (13313, 13329), False, 'import torch\n'), ((13600, 13628), 'torch.Tensor', 'torch.Tensor', (['dst_edge_times'], {}), '(dst_edge_times)\n', (13612, 13628), False, 'import torch\n'), ((17101, 17161), 'torch.Tensor', 'torch.Tensor', (['self.edge_features.edge_table[edge_idxs_batch]'], {}), '(self.edge_features.edge_table[edge_idxs_batch])\n', (17113, 17161), False, 'import torch\n'), ((19118, 19160), 'models.tgn.utils.MLP', 'MLP', (['emb_dim'], {'drop': "self.config['drop_out']"}), "(emb_dim, drop=self.config['drop_out'])\n", (19121, 19160), False, 'from models.tgn.utils import get_neighbor_finder, EarlyStopMonitor, MLP\n'), ((19221, 19264), 'os.path.join', 'os.path.join', (['f"""./logs/{self.model_id}.pkl"""'], {}), "(f'./logs/{self.model_id}.pkl')\n", (19233, 19264), False, 'import os\n'), ((3044, 3096), 'torch.rand', 'torch.rand', (["(self.num_users, self.config['emb_dim'])"], {}), "((self.num_users, self.config['emb_dim']))\n", (3054, 3096), False, 'import torch\n'), ((3937, 3963), 'os.path.isfile', 'os.path.isfile', (['model_path'], {}), '(model_path)\n', (3951, 3963), False, 'import os\n'), ((5543, 5554), 'time.time', 'time.time', ([], {}), '()\n', (5552, 5554), False, 'import time\n'), ((5798, 5823), 'torch.eye', 'torch.eye', (['self.num_users'], {}), '(self.num_users)\n', (5807, 5823), False, 'import torch\n'), ((6765, 6966), 'evaluation.eval_node_bin_classification', 'evaluation.eval_node_bin_classification', ([], {'model': 'self', 'data': 'val_data', 'data_setting_mode': '"""transductive"""', 'batch_params': "self.batch_params['val']", 'eval_mode': '"""val"""', 'n_neighbors': "self.config['n_degree']"}), "(model=self, data=val_data,\n data_setting_mode='transductive', batch_params=self.batch_params['val'],\n eval_mode='val', n_neighbors=self.config['n_degree'])\n", (6804, 6966), False, 'import evaluation\n'), ((7939, 7966), 'torch.load', 'torch.load', (['best_model_path'], {}), '(best_model_path)\n', (7949, 7966), False, 'import torch\n'), ((8888, 8899), 'time.time', 'time.time', ([], {}), '()\n', (8897, 8899), False, 'import time\n'), ((9170, 9195), 'torch.eye', 'torch.eye', (['self.num_users'], {}), '(self.num_users)\n', (9179, 9195), False, 'import torch\n'), ((10166, 10399), 'evaluation.eval_edge_prediction', 'evaluation.eval_edge_prediction', ([], {'model': 'self', 'data': 'val_data', 'negative_edge_sampler': 'val_sampler', 'data_setting_mode': '"""transductive"""', 'batch_params': "self.batch_params['val']", 'eval_mode': '"""val"""', 'n_neighbors': "self.config['n_degree']"}), "(model=self, data=val_data,\n negative_edge_sampler=val_sampler, data_setting_mode='transductive',\n batch_params=self.batch_params['val'], eval_mode='val', n_neighbors=\n self.config['n_degree'])\n", (10197, 10399), False, 'import evaluation\n'), ((13654, 13720), 'torch.where', 'torch.where', (['(src_neighbors == 0)', '(0)', '(src_neighbors - self.num_users)'], {}), '(src_neighbors == 0, 0, src_neighbors - self.num_users)\n', (13665, 13720), False, 'import torch\n'), ((13819, 13895), 'torch.where', 'torch.where', (['(destinations_batch == 0)', '(0)', '(destinations_batch - self.num_users)'], {}), '(destinations_batch == 0, 0, destinations_batch - self.num_users)\n', (13830, 13895), False, 'import torch\n'), ((19447, 19483), 'os.path.isdir', 'os.path.isdir', (['"""./saved_checkpoints"""'], {}), "('./saved_checkpoints')\n", (19460, 19483), False, 'import os\n'), ((19497, 19528), 'os.mkdir', 'os.mkdir', (['"""./saved_checkpoints"""'], {}), "('./saved_checkpoints')\n", (19505, 19528), False, 'import os\n'), ((1711, 1736), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (1734, 1736), False, 'import torch\n'), ((3233, 3285), 'torch.rand', 'torch.rand', (["(self.num_items, self.config['emb_dim'])"], {}), "((self.num_items, self.config['emb_dim']))\n", (3243, 3285), False, 'import torch\n'), ((3327, 3352), 'torch.eye', 'torch.eye', (['self.num_items'], {}), '(self.num_items)\n', (3336, 3352), False, 'import torch\n'), ((4004, 4026), 'torch.load', 'torch.load', (['model_path'], {}), '(model_path)\n', (4014, 4026), False, 'import torch\n'), ((5704, 5756), 'torch.rand', 'torch.rand', (["(self.num_users, self.config['emb_dim'])"], {}), "((self.num_users, self.config['emb_dim']))\n", (5714, 5756), False, 'import torch\n'), ((9076, 9128), 'torch.rand', 'torch.rand', (["(self.num_users, self.config['emb_dim'])"], {}), "((self.num_users, self.config['emb_dim']))\n", (9086, 9128), False, 'import torch\n'), ((10036, 10047), 'time.time', 'time.time', ([], {}), '()\n', (10045, 10047), False, 'import time\n'), ((10939, 10954), 'numpy.mean', 'np.mean', (['m_loss'], {}), '(m_loss)\n', (10946, 10954), True, 'import numpy as np\n'), ((11000, 11011), 'time.time', 'time.time', ([], {}), '()\n', (11009, 11011), False, 'import time\n'), ((12767, 12794), 'torch.Tensor', 'torch.Tensor', (['sources_batch'], {}), '(sources_batch)\n', (12779, 12794), False, 'import torch\n'), ((12847, 12879), 'torch.Tensor', 'torch.Tensor', (['destinations_batch'], {}), '(destinations_batch)\n', (12859, 12879), False, 'import torch\n'), ((13225, 13252), 'torch.Tensor', 'torch.Tensor', (['src_neighbors'], {}), '(src_neighbors)\n', (13237, 13252), False, 'import torch\n'), ((16190, 16248), 'torch.where', 'torch.where', (['(negatives == 0)', '(0)', '(negatives - self.num_users)'], {}), '(negatives == 0, 0, negatives - self.num_users)\n', (16201, 16248), False, 'import torch\n'), ((1058, 1070), 'time.ctime', 'time.ctime', ([], {}), '()\n', (1068, 1070), False, 'import time\n'), ((1132, 1144), 'time.ctime', 'time.ctime', ([], {}), '()\n', (1142, 1144), False, 'import time\n'), ((5905, 5957), 'torch.rand', 'torch.rand', (["(self.num_items, self.config['emb_dim'])"], {}), "((self.num_items, self.config['emb_dim']))\n", (5915, 5957), False, 'import torch\n'), ((6003, 6028), 'torch.eye', 'torch.eye', (['self.num_items'], {}), '(self.num_items)\n', (6012, 6028), False, 'import torch\n'), ((7182, 7193), 'time.time', 'time.time', ([], {}), '()\n', (7191, 7193), False, 'import time\n'), ((9277, 9329), 'torch.rand', 'torch.rand', (["(self.num_items, self.config['emb_dim'])"], {}), "((self.num_items, self.config['emb_dim']))\n", (9287, 9329), False, 'import torch\n'), ((9375, 9400), 'torch.eye', 'torch.eye', (['self.num_items'], {}), '(self.num_items)\n', (9384, 9400), False, 'import torch\n'), ((9731, 9742), 'time.time', 'time.time', ([], {}), '()\n', (9740, 9742), False, 'import time\n'), ((11854, 11881), 'torch.load', 'torch.load', (['best_model_path'], {}), '(best_model_path)\n', (11864, 11881), False, 'import torch\n'), ((15216, 15259), 'torch.cat', 'torch.cat', (['[user_emb, item_prev_sum]'], {'dim': '(1)'}), '([user_emb, item_prev_sum], dim=1)\n', (15225, 15259), False, 'import torch\n'), ((16119, 16142), 'torch.Tensor', 'torch.Tensor', (['negatives'], {}), '(negatives)\n', (16131, 16142), False, 'import torch\n'), ((11237, 11252), 'numpy.mean', 'np.mean', (['m_loss'], {}), '(m_loss)\n', (11244, 11252), True, 'import numpy as np\n'), ((14544, 14574), 'torch.ones_like', 'torch.ones_like', (['src_neighbors'], {}), '(src_neighbors)\n', (14559, 14574), False, 'import torch\n'), ((14818, 14848), 'torch.ones_like', 'torch.ones_like', (['src_neighbors'], {}), '(src_neighbors)\n', (14833, 14848), False, 'import torch\n'), ((18230, 18260), 'torch.ones_like', 'torch.ones_like', (['src_neighbors'], {}), '(src_neighbors)\n', (18245, 18260), False, 'import torch\n'), ((6317, 6343), 'torch.from_numpy', 'torch.from_numpy', (['batch[4]'], {}), '(batch[4])\n', (6333, 6343), False, 'import torch\n'), ((16628, 16665), 'torch.cat', 'torch.cat', (['[pos_dyn, pos_stat]'], {'dim': '(1)'}), '([pos_dyn, pos_stat], dim=1)\n', (16637, 16665), False, 'import torch\n'), ((16729, 16766), 'torch.cat', 'torch.cat', (['[neg_dyn, neg_stat]'], {'dim': '(1)'}), '([neg_dyn, neg_stat], dim=1)\n', (16738, 16766), False, 'import torch\n'), ((16847, 16984), 'torch.cat', 'torch.cat', (['([item_emb, self.stat_item_emb[destinations_batch]] if not self.eth_flg else\n self.stat_user_emb[destinations_batch])'], {'dim': '(1)'}), '([item_emb, self.stat_item_emb[destinations_batch]] if not self.\n eth_flg else self.stat_user_emb[destinations_batch], dim=1)\n', (16856, 16984), False, 'import torch\n'), ((9652, 9663), 'time.time', 'time.time', ([], {}), '()\n', (9661, 9663), False, 'import time\n')]
#!/usr/bin/env python import cv2 import numpy as np #detecting contours around img def detectContours(image): greyImage = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) edges = cv2.Canny(greyImage, (30, 200)) _,contours,_ = cv2.findContours(edges,cv2.RETR_EXTERNAL) cv2.drawContours(image,contours,-1,(0,255,0),2) return image #get the videocamera from videocapture capture = cv2.VideoCapture(0) #funcion code during while true to read and output images while True: ret, frame = capture.read() greyImage = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) # ret, frame = capture.read() # cv2.imshow('Orig.', bitwise_and.detectContours(frame)) # cv2.imshow('Detection', bitwise_and.detectContours(frame)) lower_range = np.array([0,172,172]) upper_range = np.array([30,255,255]) mask = cv2.inRange(greyImage, lower_range, upper_range) wisebit = cv2.bitwise_and(frame, frame,mask=mask) cv2.imshow('bitwise', wisebit) cv2.imshow('kappa', mask) if cv2.waitKey(1) == 13: break capture.release() cv2.destoryALlWindows()
[ "cv2.Canny", "cv2.bitwise_and", "cv2.cvtColor", "cv2.waitKey", "cv2.VideoCapture", "numpy.array", "cv2.drawContours", "cv2.destoryALlWindows", "cv2.imshow", "cv2.inRange", "cv2.findContours" ]
[((386, 405), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (402, 405), False, 'import cv2\n'), ((1018, 1041), 'cv2.destoryALlWindows', 'cv2.destoryALlWindows', ([], {}), '()\n', (1039, 1041), False, 'import cv2\n'), ((129, 168), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_BGR2GRAY'], {}), '(image, cv2.COLOR_BGR2GRAY)\n', (141, 168), False, 'import cv2\n'), ((177, 208), 'cv2.Canny', 'cv2.Canny', (['greyImage', '(30, 200)'], {}), '(greyImage, (30, 200))\n', (186, 208), False, 'import cv2\n'), ((225, 267), 'cv2.findContours', 'cv2.findContours', (['edges', 'cv2.RETR_EXTERNAL'], {}), '(edges, cv2.RETR_EXTERNAL)\n', (241, 267), False, 'import cv2\n'), ((268, 321), 'cv2.drawContours', 'cv2.drawContours', (['image', 'contours', '(-1)', '(0, 255, 0)', '(2)'], {}), '(image, contours, -1, (0, 255, 0), 2)\n', (284, 321), False, 'import cv2\n'), ((524, 563), 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_BGR2GRAY'], {}), '(frame, cv2.COLOR_BGR2GRAY)\n', (536, 563), False, 'import cv2\n'), ((728, 751), 'numpy.array', 'np.array', (['[0, 172, 172]'], {}), '([0, 172, 172])\n', (736, 751), True, 'import numpy as np\n'), ((765, 789), 'numpy.array', 'np.array', (['[30, 255, 255]'], {}), '([30, 255, 255])\n', (773, 789), True, 'import numpy as np\n'), ((797, 845), 'cv2.inRange', 'cv2.inRange', (['greyImage', 'lower_range', 'upper_range'], {}), '(greyImage, lower_range, upper_range)\n', (808, 845), False, 'import cv2\n'), ((859, 899), 'cv2.bitwise_and', 'cv2.bitwise_and', (['frame', 'frame'], {'mask': 'mask'}), '(frame, frame, mask=mask)\n', (874, 899), False, 'import cv2\n'), ((901, 931), 'cv2.imshow', 'cv2.imshow', (['"""bitwise"""', 'wisebit'], {}), "('bitwise', wisebit)\n", (911, 931), False, 'import cv2\n'), ((933, 958), 'cv2.imshow', 'cv2.imshow', (['"""kappa"""', 'mask'], {}), "('kappa', mask)\n", (943, 958), False, 'import cv2\n'), ((966, 980), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (977, 980), False, 'import cv2\n')]
import numpy as np import spikeextractors as se class OutputRecordingExtractor(se.RecordingExtractor): def __init__(self, *, base_recording, block_size): super().__init__() self._base_recording = base_recording self._block_size = block_size self.copy_channel_properties(recording=self._base_recording) self._blocks = [] def add_block(self, traces: np.ndarray): """Add a block of output traces Parameters ---------- traces : np.ndarray The block of output traces """ if traces.shape[1] == self._block_size: self._blocks.append(traces) else: if traces.shape[1] >= self._block_size * 2: raise Exception( 'Unexpected error adding block to OutputRecordingExtractor.') # pragma: no cover if len(self._blocks) * self._block_size + traces.shape[1] != self.get_num_frames(): raise Exception(f'Problem adding final block. Unexpected size: {traces.shape[1]}. Block size is {self._block_size}. Number of frames is {self.get_num_frames()}.') # pragma: no cover if traces.shape[1] > self._block_size: self._blocks.append(traces[:, :self._block_size]) self._blocks.append(traces[:, self._block_size:]) else: self._blocks.append(traces) def get_channel_ids(self): """Return the channel ids """ return self._base_recording.get_channel_ids() def get_num_frames(self): """Return number of frames in the recording """ return self._base_recording.get_num_frames() def get_sampling_frequency(self): """Return sampling frequency """ return self._base_recording.get_sampling_frequency() def get_traces(self, channel_ids=None, start_frame=None, end_frame=None, return_scaled=False): if start_frame is None: start_frame = 0 if end_frame is None: end_frame = self.get_num_frames() if channel_ids is None: channel_ids = self.get_channel_ids() channel_indices = [] aa = self.get_channel_ids() for ch in channel_ids: channel_indices.append(np.nonzero(np.array(aa) == ch)[0][0]) ib1 = int(start_frame / self._block_size) ib2 = int((end_frame-1) / self._block_size) assert ib2 < len(self._blocks), f'Block {ib2} not found in OutputRecordingExtractor (num blocks is {len(self._blocks)})' trace_blocks = [] if ib1 == ib2: trace_blocks.append( self._blocks[ib1][channel_indices][:, start_frame - ib1 * self._block_size:end_frame - ib1 * self._block_size] ) else: trace_blocks.append( self._blocks[ib1][channel_indices][:, start_frame - ib1 * self._block_size:] ) for ii in range(ib1 + 1, ib2): trace_blocks.append( self._blocks[ii][channel_indices, :] ) trace_blocks.append( self._blocks[ib2][channel_indices][:, :end_frame - ib2 * self._block_size] ) return np.concatenate(trace_blocks, axis=1) @staticmethod def write_recording(recording, save_path): raise Exception('write_recording not implemented for this recording extractor')
[ "numpy.array", "numpy.concatenate" ]
[((3338, 3374), 'numpy.concatenate', 'np.concatenate', (['trace_blocks'], {'axis': '(1)'}), '(trace_blocks, axis=1)\n', (3352, 3374), True, 'import numpy as np\n'), ((2290, 2302), 'numpy.array', 'np.array', (['aa'], {}), '(aa)\n', (2298, 2302), True, 'import numpy as np\n')]
#!/usr/bin/env python # coding: utf-8 import json import logging import os import sys import warnings from collections import namedtuple import fiona import geopandas import numpy import pandas import rasterio from shapely.geometry import mapping, shape from shapely.ops import linemerge, polygonize from snail.intersections import get_cell_indices, split_linestring, split_polygon from tqdm import tqdm def load_config(): """Read config.json""" config_path = os.path.join(os.path.dirname(__file__), "..", "..", "config.json") with open(config_path, "r") as config_fh: config = json.load(config_fh) return config def main(data_path, networks_csv, hazards_csv): # read transforms, record with hazards hazards = pandas.read_csv(hazards_csv) hazard_slug = os.path.basename(hazards_csv).replace(".csv", "") hazard_transforms, transforms = read_transforms(hazards, data_path) hazard_transforms.to_csv(hazards_csv.replace(".csv", "__with_transforms.csv"), index=False) # read networks networks = pandas.read_csv(networks_csv) for network_path in networks.path: fname = os.path.join(data_path, network_path) out_fname = os.path.join( data_path, "..", "results", "hazard_asset_intersection", os.path.basename(network_path).replace(".gpkg", f"_splits__{hazard_slug}.gpkg") ) pq_fname_nodes = out_fname.replace(".gpkg","__nodes.geoparquet") pq_fname_edges = out_fname.replace(".gpkg","__edges.geoparquet") pq_fname_areas = out_fname.replace(".gpkg","__areas.geoparquet") # skip if output is there already (not using gpkg currently) # if os.path.exists(out_fname): # logging.info("Skipping %s. Already exists: %s", os.path.basename(fname), out_fname) # continue logging.info("Processing %s", os.path.basename(fname)) layers = fiona.listlayers(fname) logging.info("Layers: %s", layers) if "nodes" in layers: # skip if output is there already if os.path.exists(pq_fname_nodes): logging.info("Skipping %s. Already exists: %s", os.path.basename(fname), pq_fname_nodes) else: # look up nodes cell index nodes = geopandas.read_file(fname, layer="nodes") logging.info("Node CRS %s", nodes.crs) nodes = process_nodes(nodes, transforms, hazard_transforms, data_path) # nodes.to_file(out_fname, driver="GPKG", layer="nodes") nodes.to_parquet(pq_fname_nodes) if "edges" in layers: # skip if output is there already if os.path.exists(pq_fname_edges): logging.info("Skipping %s. Already exists: %s", os.path.basename(fname), pq_fname_edges) else: # split lines edges = geopandas.read_file(fname, layer="edges") logging.info("Edge CRS %s", edges.crs) edges = process_edges(edges, transforms, hazard_transforms, data_path) # edges.to_file(out_fname, driver="GPKG", layer="edges") edges.to_parquet(pq_fname_edges) if "areas" in layers: # skip if output is there already if os.path.exists(pq_fname_areas): logging.info("Skipping %s. Already exists: %s", os.path.basename(fname), pq_fname_areas) else: # split polygons areas = geopandas.read_file(fname, layer="areas") logging.info("Area CRS %s", areas.crs) areas = explode_multi(areas) areas = process_areas(areas, transforms, hazard_transforms, data_path) # areas.to_file(out_fname, driver="GPKG", layer="areas") areas.to_parquet(pq_fname_areas) # Helper class to store a raster transform and CRS Transform = namedtuple('Transform', ['crs', 'width', 'height', 'transform']) def associate_raster(df, key, fname, cell_index_col='cell_index', band_number=1): with rasterio.open(fname) as dataset: band_data = dataset.read(band_number) df[key] = df[cell_index_col].apply(lambda i: band_data[i[1], i[0]]) def read_transforms(hazards, data_path): transforms = [] transform_id = 0 hazard_transforms = [] for hazard in hazards.itertuples(): hazard_path = hazard.path with rasterio.open(os.path.join(data_path, hazard_path)) as dataset: crs = dataset.crs width = dataset.width height = dataset.height transform = Transform(crs, width, height, tuple(dataset.transform)) # add transform to list if not present if transform not in transforms: transforms.append(transform) transform_id = transform_id + 1 # record hazard/transform details hazard_transform_id = transforms.index(transform) hazard_transform = hazard._asdict() del hazard_transform['Index'] hazard_transform['transform_id'] = hazard_transform_id hazard_transform['width'] = transform.width hazard_transform['height'] = transform.height hazard_transform['crs'] = str(transform.crs) hazard_transform['transform_0'] = transform.transform[0] hazard_transform['transform_1'] = transform.transform[1] hazard_transform['transform_2'] = transform.transform[2] hazard_transform['transform_3'] = transform.transform[3] hazard_transform['transform_4'] = transform.transform[4] hazard_transform['transform_5'] = transform.transform[5] hazard_transforms.append(hazard_transform) hazard_transforms = pandas.DataFrame(hazard_transforms) return hazard_transforms, transforms def process_nodes(nodes, transforms, hazard_transforms, data_path): # lookup per transform for i, t in enumerate(transforms): # transform to grid crs_df = nodes.to_crs(t.crs) # save cell index for fast lookup of raster values crs_df[f'cell_index_{i}'] = crs_df.geometry.progress_apply(lambda geom: get_indices(geom, t)) # transform back nodes = crs_df.to_crs(nodes.crs) # associate hazard values for hazard in hazard_transforms.itertuples(): logging.info("Hazard %s transform %s", hazard.key, hazard.transform_id) fname = os.path.join(data_path, hazard.path) cell_index_col = f'cell_index_{hazard.transform_id}' associate_raster(nodes, hazard.key, fname, cell_index_col) # split and drop tuple columns so GPKG can save for i, t in enumerate(transforms): nodes = split_index_column(nodes, f'cell_index_{i}') nodes.drop(columns=f'cell_index_{i}', inplace=True) return nodes def try_merge(geom): if geom.geom_type =='MultiLineString': geom = linemerge(geom) return geom def process_edges(edges, transforms, hazard_transforms, data_path): # handle multilinestrings edges.geometry = edges.geometry.apply(try_merge) geom_types = edges.geometry.apply(lambda g: g.geom_type) logging.info(geom_types.value_counts()) edges = explode_multi(edges) # split edges per transform for i, t in enumerate(transforms): # transform to grid crs_df = edges.to_crs(t.crs) crs_df = split_df(crs_df, t) # save cell index for fast lookup of raster values crs_df[f'cell_index_{i}'] = crs_df.geometry.progress_apply(lambda geom: get_indices(geom, t)) # transform back edges = crs_df.to_crs(edges.crs) # associate hazard values for hazard in hazard_transforms.itertuples(): logging.info("Hazard %s transform %s", hazard.key, hazard.transform_id) fname = os.path.join(data_path, hazard.path) cell_index_col = f'cell_index_{hazard.transform_id}' associate_raster(edges, hazard.key, fname, cell_index_col) # split and drop tuple columns so GPKG can save for i, t in enumerate(transforms): edges = split_index_column(edges, f'cell_index_{i}') edges.drop(columns=f'cell_index_{i}', inplace=True) return edges def split_df(df, t): # split core_splits = [] for edge in tqdm(df.itertuples(), total=len(df)): # split edge splits = split_linestring( edge.geometry, t.width, t.height, t.transform ) # add to collection for s in splits: s_dict = edge._asdict() del s_dict['Index'] s_dict['geometry'] = s core_splits.append(s_dict) logging.info(f"Split {len(df)} edges into {len(core_splits)} pieces") sdf = geopandas.GeoDataFrame(core_splits, crs=t.crs, geometry='geometry') return sdf def process_areas(areas, transforms, hazard_transforms, data_path): # split areas per transform for i, t in enumerate(transforms): # transform to grid crs_df = areas.to_crs(t.crs) crs_df = split_area_df(crs_df, t) # save cell index for fast lookup of raster values crs_df[f'cell_index_{i}'] = crs_df.geometry.progress_apply(lambda geom: get_indices(geom, t)) # transform back areas = crs_df.to_crs(areas.crs) # associate hazard values for hazard in hazard_transforms.itertuples(): logging.info("Hazard %s transform %s", hazard.key, hazard.transform_id) fname = os.path.join(data_path, hazard.path) cell_index_col = f'cell_index_{hazard.transform_id}' associate_raster(areas, hazard.key, fname, cell_index_col) # split and drop tuple columns so GPKG can save for i, t in enumerate(transforms): areas = split_index_column(areas, f'cell_index_{i}') areas.drop(columns=f'cell_index_{i}', inplace=True) return areas def explode_multi(df): items = [] geoms = [] for item in df.itertuples(index=False): if item.geometry.geom_type in ('MultiPoint', 'MultiLineString', 'MultiPolygon'): for part in item.geometry: items.append(item._asdict()) geoms.append(part) else: items.append(item._asdict()) geoms.append(item.geometry) df = geopandas.GeoDataFrame(items, crs=df.crs, geometry=geoms) return df def set_precision(geom, precision): """Set geometry precision""" geom_mapping = mapping(geom) geom_mapping["coordinates"] = numpy.round( numpy.array(geom_mapping["coordinates"]), precision) return shape(geom_mapping) def split_area_df(df, t): # split core_splits = [] for area in tqdm(df.itertuples(), total=len(df)): # split area splits = split_polygon( area.geometry, t.width, t.height, t.transform ) # round to high precision (avoid floating point errors) splits = [set_precision(s, 9) for s in splits] # to polygons splits = list(polygonize(splits)) # add to collection for s in splits: s_dict = area._asdict() del s_dict['Index'] s_dict['geometry'] = s core_splits.append(s_dict) logging.info(f" Split {len(df)} areas into {len(core_splits)} pieces") sdf = geopandas.GeoDataFrame(core_splits) sdf.crs = t.crs return sdf def get_indices(geom, t): x, y = get_cell_indices( geom, t.width, t.height, t.transform) # wrap around to handle edge cases x = x % t.width y = y % t.height return (x, y) def split_index_column(df, prefix): df[f'{prefix}_x'] = df[prefix].apply(lambda i: i[0]) df[f'{prefix}_y'] = df[prefix].apply(lambda i: i[1]) return df if __name__ == '__main__': # Load config CONFIG = load_config() # Save splits, attribute data later data_path = CONFIG["paths"]["data"] try: networks_csv = sys.argv[1] hazards_csv = sys.argv[2] except IndexError: logging.error( "Error. Please provide networks and hazards as CSV.\n", f"Usage: python {__file__} networks/network_files.csv hazards/hazard_layers.csv") # Ignore writing-to-parquet warnings warnings.filterwarnings('ignore', message='.*initial implementation of Parquet.*') # Ignore reading-geopackage warnings warnings.filterwarnings('ignore', message='.*Sequential read of iterator was interrupted.*') # Enable progress_apply tqdm.pandas() # Enable info logging logging.basicConfig(format='%(asctime)s %(message)s', level=logging.INFO) logging.info("Start.") main(data_path, networks_csv, hazards_csv) logging.info("Done.")
[ "pandas.read_csv", "tqdm.tqdm.pandas", "os.path.join", "shapely.geometry.shape", "pandas.DataFrame", "logging.error", "os.path.dirname", "os.path.exists", "fiona.listlayers", "geopandas.GeoDataFrame", "geopandas.read_file", "os.path.basename", "shapely.ops.polygonize", "shapely.ops.linemer...
[((3924, 3988), 'collections.namedtuple', 'namedtuple', (['"""Transform"""', "['crs', 'width', 'height', 'transform']"], {}), "('Transform', ['crs', 'width', 'height', 'transform'])\n", (3934, 3988), False, 'from collections import namedtuple\n'), ((749, 777), 'pandas.read_csv', 'pandas.read_csv', (['hazards_csv'], {}), '(hazards_csv)\n', (764, 777), False, 'import pandas\n'), ((1050, 1079), 'pandas.read_csv', 'pandas.read_csv', (['networks_csv'], {}), '(networks_csv)\n', (1065, 1079), False, 'import pandas\n'), ((5721, 5756), 'pandas.DataFrame', 'pandas.DataFrame', (['hazard_transforms'], {}), '(hazard_transforms)\n', (5737, 5756), False, 'import pandas\n'), ((8726, 8793), 'geopandas.GeoDataFrame', 'geopandas.GeoDataFrame', (['core_splits'], {'crs': 't.crs', 'geometry': '"""geometry"""'}), "(core_splits, crs=t.crs, geometry='geometry')\n", (8748, 8793), False, 'import geopandas\n'), ((10268, 10325), 'geopandas.GeoDataFrame', 'geopandas.GeoDataFrame', (['items'], {'crs': 'df.crs', 'geometry': 'geoms'}), '(items, crs=df.crs, geometry=geoms)\n', (10290, 10325), False, 'import geopandas\n'), ((10430, 10443), 'shapely.geometry.mapping', 'mapping', (['geom'], {}), '(geom)\n', (10437, 10443), False, 'from shapely.geometry import mapping, shape\n'), ((10563, 10582), 'shapely.geometry.shape', 'shape', (['geom_mapping'], {}), '(geom_mapping)\n', (10568, 10582), False, 'from shapely.geometry import mapping, shape\n'), ((11319, 11354), 'geopandas.GeoDataFrame', 'geopandas.GeoDataFrame', (['core_splits'], {}), '(core_splits)\n', (11341, 11354), False, 'import geopandas\n'), ((11429, 11483), 'snail.intersections.get_cell_indices', 'get_cell_indices', (['geom', 't.width', 't.height', 't.transform'], {}), '(geom, t.width, t.height, t.transform)\n', (11445, 11483), False, 'from snail.intersections import get_cell_indices, split_linestring, split_polygon\n'), ((12267, 12354), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'message': '""".*initial implementation of Parquet.*"""'}), "('ignore', message=\n '.*initial implementation of Parquet.*')\n", (12290, 12354), False, 'import warnings\n'), ((12395, 12492), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'message': '""".*Sequential read of iterator was interrupted.*"""'}), "('ignore', message=\n '.*Sequential read of iterator was interrupted.*')\n", (12418, 12492), False, 'import warnings\n'), ((12521, 12534), 'tqdm.tqdm.pandas', 'tqdm.pandas', ([], {}), '()\n', (12532, 12534), False, 'from tqdm import tqdm\n'), ((12566, 12639), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)s %(message)s"""', 'level': 'logging.INFO'}), "(format='%(asctime)s %(message)s', level=logging.INFO)\n", (12585, 12639), False, 'import logging\n'), ((12644, 12666), 'logging.info', 'logging.info', (['"""Start."""'], {}), "('Start.')\n", (12656, 12666), False, 'import logging\n'), ((12718, 12739), 'logging.info', 'logging.info', (['"""Done."""'], {}), "('Done.')\n", (12730, 12739), False, 'import logging\n'), ((486, 511), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (501, 511), False, 'import os\n'), ((603, 623), 'json.load', 'json.load', (['config_fh'], {}), '(config_fh)\n', (612, 623), False, 'import json\n'), ((1136, 1173), 'os.path.join', 'os.path.join', (['data_path', 'network_path'], {}), '(data_path, network_path)\n', (1148, 1173), False, 'import os\n'), ((1910, 1933), 'fiona.listlayers', 'fiona.listlayers', (['fname'], {}), '(fname)\n', (1926, 1933), False, 'import fiona\n'), ((1942, 1976), 'logging.info', 'logging.info', (['"""Layers: %s"""', 'layers'], {}), "('Layers: %s', layers)\n", (1954, 1976), False, 'import logging\n'), ((4082, 4102), 'rasterio.open', 'rasterio.open', (['fname'], {}), '(fname)\n', (4095, 4102), False, 'import rasterio\n'), ((6316, 6387), 'logging.info', 'logging.info', (['"""Hazard %s transform %s"""', 'hazard.key', 'hazard.transform_id'], {}), "('Hazard %s transform %s', hazard.key, hazard.transform_id)\n", (6328, 6387), False, 'import logging\n'), ((6404, 6440), 'os.path.join', 'os.path.join', (['data_path', 'hazard.path'], {}), '(data_path, hazard.path)\n', (6416, 6440), False, 'import os\n'), ((6880, 6895), 'shapely.ops.linemerge', 'linemerge', (['geom'], {}), '(geom)\n', (6889, 6895), False, 'from shapely.ops import linemerge, polygonize\n'), ((7693, 7764), 'logging.info', 'logging.info', (['"""Hazard %s transform %s"""', 'hazard.key', 'hazard.transform_id'], {}), "('Hazard %s transform %s', hazard.key, hazard.transform_id)\n", (7705, 7764), False, 'import logging\n'), ((7781, 7817), 'os.path.join', 'os.path.join', (['data_path', 'hazard.path'], {}), '(data_path, hazard.path)\n', (7793, 7817), False, 'import os\n'), ((8325, 8388), 'snail.intersections.split_linestring', 'split_linestring', (['edge.geometry', 't.width', 't.height', 't.transform'], {}), '(edge.geometry, t.width, t.height, t.transform)\n', (8341, 8388), False, 'from snail.intersections import get_cell_indices, split_linestring, split_polygon\n'), ((9373, 9444), 'logging.info', 'logging.info', (['"""Hazard %s transform %s"""', 'hazard.key', 'hazard.transform_id'], {}), "('Hazard %s transform %s', hazard.key, hazard.transform_id)\n", (9385, 9444), False, 'import logging\n'), ((9461, 9497), 'os.path.join', 'os.path.join', (['data_path', 'hazard.path'], {}), '(data_path, hazard.path)\n', (9473, 9497), False, 'import os\n'), ((10499, 10539), 'numpy.array', 'numpy.array', (["geom_mapping['coordinates']"], {}), "(geom_mapping['coordinates'])\n", (10510, 10539), False, 'import numpy\n'), ((10736, 10796), 'snail.intersections.split_polygon', 'split_polygon', (['area.geometry', 't.width', 't.height', 't.transform'], {}), '(area.geometry, t.width, t.height, t.transform)\n', (10749, 10796), False, 'from snail.intersections import get_cell_indices, split_linestring, split_polygon\n'), ((796, 825), 'os.path.basename', 'os.path.basename', (['hazards_csv'], {}), '(hazards_csv)\n', (812, 825), False, 'import os\n'), ((1868, 1891), 'os.path.basename', 'os.path.basename', (['fname'], {}), '(fname)\n', (1884, 1891), False, 'import os\n'), ((2069, 2099), 'os.path.exists', 'os.path.exists', (['pq_fname_nodes'], {}), '(pq_fname_nodes)\n', (2083, 2099), False, 'import os\n'), ((2689, 2719), 'os.path.exists', 'os.path.exists', (['pq_fname_edges'], {}), '(pq_fname_edges)\n', (2703, 2719), False, 'import os\n'), ((3296, 3326), 'os.path.exists', 'os.path.exists', (['pq_fname_areas'], {}), '(pq_fname_areas)\n', (3310, 3326), False, 'import os\n'), ((11018, 11036), 'shapely.ops.polygonize', 'polygonize', (['splits'], {}), '(splits)\n', (11028, 11036), False, 'from shapely.ops import linemerge, polygonize\n'), ((12044, 12204), 'logging.error', 'logging.error', (['"""Error. Please provide networks and hazards as CSV.\n"""', 'f"""Usage: python {__file__} networks/network_files.csv hazards/hazard_layers.csv"""'], {}), "('Error. Please provide networks and hazards as CSV.\\n',\n f'Usage: python {__file__} networks/network_files.csv hazards/hazard_layers.csv'\n )\n", (12057, 12204), False, 'import logging\n'), ((2291, 2332), 'geopandas.read_file', 'geopandas.read_file', (['fname'], {'layer': '"""nodes"""'}), "(fname, layer='nodes')\n", (2310, 2332), False, 'import geopandas\n'), ((2349, 2387), 'logging.info', 'logging.info', (['"""Node CRS %s"""', 'nodes.crs'], {}), "('Node CRS %s', nodes.crs)\n", (2361, 2387), False, 'import logging\n'), ((2898, 2939), 'geopandas.read_file', 'geopandas.read_file', (['fname'], {'layer': '"""edges"""'}), "(fname, layer='edges')\n", (2917, 2939), False, 'import geopandas\n'), ((2956, 2994), 'logging.info', 'logging.info', (['"""Edge CRS %s"""', 'edges.crs'], {}), "('Edge CRS %s', edges.crs)\n", (2968, 2994), False, 'import logging\n'), ((3508, 3549), 'geopandas.read_file', 'geopandas.read_file', (['fname'], {'layer': '"""areas"""'}), "(fname, layer='areas')\n", (3527, 3549), False, 'import geopandas\n'), ((3566, 3604), 'logging.info', 'logging.info', (['"""Area CRS %s"""', 'areas.crs'], {}), "('Area CRS %s', areas.crs)\n", (3578, 3604), False, 'import logging\n'), ((4449, 4485), 'os.path.join', 'os.path.join', (['data_path', 'hazard_path'], {}), '(data_path, hazard_path)\n', (4461, 4485), False, 'import os\n'), ((1289, 1319), 'os.path.basename', 'os.path.basename', (['network_path'], {}), '(network_path)\n', (1305, 1319), False, 'import os\n'), ((2165, 2188), 'os.path.basename', 'os.path.basename', (['fname'], {}), '(fname)\n', (2181, 2188), False, 'import os\n'), ((2785, 2808), 'os.path.basename', 'os.path.basename', (['fname'], {}), '(fname)\n', (2801, 2808), False, 'import os\n'), ((3392, 3415), 'os.path.basename', 'os.path.basename', (['fname'], {}), '(fname)\n', (3408, 3415), False, 'import os\n')]
import numpy as np import torch from gwd.eda.kmeans import kmeans from mmdet.core.anchor import AnchorGenerator, build_anchor_generator def main(): anchor_generator_cfg = dict(type="AnchorGenerator", scales=[8], ratios=[0.5, 1.0, 2.0], strides=[4, 8, 16, 32, 64]) anchor_generator: AnchorGenerator = build_anchor_generator(anchor_generator_cfg) multi_level_anchors = anchor_generator.grid_anchors( featmap_sizes=[ torch.Size([256, 256]), torch.Size([128, 128]), torch.Size([64, 64]), torch.Size([32, 32]), torch.Size([16, 16]), ], device="cpu", ) anchors = torch.cat(multi_level_anchors).numpy() widths = anchors[:, 2] - anchors[:, 0] heights = anchors[:, 3] - anchors[:, 1] data = np.stack([heights, widths], axis=1) clusters = kmeans(data, k=50) print(f"aspect rations: {clusters[: 0] / clusters[: 1]}") print(f"sizes: {np.sqrt(clusters[: 0] * clusters[: 1])}") if __name__ == "__main__": main()
[ "numpy.stack", "mmdet.core.anchor.build_anchor_generator", "torch.cat", "torch.Size", "gwd.eda.kmeans.kmeans", "numpy.sqrt" ]
[((311, 355), 'mmdet.core.anchor.build_anchor_generator', 'build_anchor_generator', (['anchor_generator_cfg'], {}), '(anchor_generator_cfg)\n', (333, 355), False, 'from mmdet.core.anchor import AnchorGenerator, build_anchor_generator\n'), ((801, 836), 'numpy.stack', 'np.stack', (['[heights, widths]'], {'axis': '(1)'}), '([heights, widths], axis=1)\n', (809, 836), True, 'import numpy as np\n'), ((852, 870), 'gwd.eda.kmeans.kmeans', 'kmeans', (['data'], {'k': '(50)'}), '(data, k=50)\n', (858, 870), False, 'from gwd.eda.kmeans import kmeans\n'), ((664, 694), 'torch.cat', 'torch.cat', (['multi_level_anchors'], {}), '(multi_level_anchors)\n', (673, 694), False, 'import torch\n'), ((449, 471), 'torch.Size', 'torch.Size', (['[256, 256]'], {}), '([256, 256])\n', (459, 471), False, 'import torch\n'), ((485, 507), 'torch.Size', 'torch.Size', (['[128, 128]'], {}), '([128, 128])\n', (495, 507), False, 'import torch\n'), ((521, 541), 'torch.Size', 'torch.Size', (['[64, 64]'], {}), '([64, 64])\n', (531, 541), False, 'import torch\n'), ((555, 575), 'torch.Size', 'torch.Size', (['[32, 32]'], {}), '([32, 32])\n', (565, 575), False, 'import torch\n'), ((589, 609), 'torch.Size', 'torch.Size', (['[16, 16]'], {}), '([16, 16])\n', (599, 609), False, 'import torch\n'), ((953, 989), 'numpy.sqrt', 'np.sqrt', (['(clusters[:0] * clusters[:1])'], {}), '(clusters[:0] * clusters[:1])\n', (960, 989), True, 'import numpy as np\n')]
import numpy as np import tensorflow as tf import random import dqn # at current directory from collections import deque import gym env = gym.make('CartPole-v0') input_size = env.observation_space.shape[0] # 4 output_size = env.action_space.n # 2 dis = 0.9 REPLAY_MEMORY = 50000 def simple_replay_train(DQN, train_batch): x_stack = np.empty(0).reshape(0, input_size) y_stack = np.empty(0).reshape(0, output_size) for state, action, reward, next_state, done in train_batch: Q = DQN.predict(state) # return act if done: Q[0, action] = reward else: Q[0, action] = reward + dis * np.max(DQN.predict(next_state)) y_stack = np.vstack([y_stack, Q]) x_stack = np.vstack([x_stack, state]) return DQN.update(x_stack, y_stack) def replay_train(mainDQN, targetDQN, train_batch): x_stack = np.empty(0).reshape(0, input_size) y_stack = np.empty(0).reshape(0, output_size) for state, action, reward, next_state, done in train_batch: Q = mainDQN.predict(state) # return act if done: Q[0, action] = reward else: Q[0, action] = reward + (dis * np.max(targetDQN.predict(next_state))) y_stack = np.vstack([y_stack, Q]) x_stack = np.vstack([x_stack, state]) return mainDQN.update(x_stack, y_stack) def bot_play(mainDQN): s = env.reset() reward_sum = 0 while True: env.render() a = np.argmax(mainDQN.predict(s)) s, reward, done, _ = env.step(a) reward_sum += reward if done: print("Total score: {}".format(reward_sum)) break def get_copy_var_ops(*, dest_scope_name="target", src_scope_name="main"): op_holder = [] src_vars = tf.get_collection( tf.GraphKeys.TRAINABLE_VARIABLES, scope=src_scope_name) dest_vars = tf.get_collection( tf.GraphKeys.TRAINABLE_VARIABLES, scope=dest_scope_name) for src_var, dest_var in zip(src_vars, dest_vars): op_holder.append(dest_var.assign(src_var.value())) return op_holder def main(): max_episodes = 5000 replay_buffer = deque() with tf.Session() as sess: mainDQN = dqn.DQN(sess, input_size, output_size, name="main") targetDQN = dqn.DQN(sess, input_size, output_size, name="target") tf.global_variables_initializer().run() copy_ops = get_copy_var_ops(dest_scope_name="target", src_scope_name="main") sess.run(copy_ops) # targetDQN <= mainDQN for episode in range(max_episodes): e = 1. / ((episode // 10) + 1) done = False step_count = 0 state = env.reset() while not done: if np.random.rand(1) < e: action = env.action_space.sample() else: action = np.argmax(mainDQN.predict(state)) next_state, reward, done, _ = env.step(action) if done: reward = -100 # save experience replay_buffer.append((state, action, reward, next_state, done)) if len(replay_buffer) > REPLAY_MEMORY: replay_buffer.popleft() state = next_state step_count += 1 if step_count > 10000: break print ("Episode: {} steps: {}".format(episode, step_count)) if step_count > 10000: pass if episode % 10 == 1: for _ in range(50): # minibatch minibatch = random.sample(replay_buffer, 10) loss, _ = replay_train(mainDQN, targetDQN, minibatch) print("loss: ", loss) sess.run(copy_ops) bot_play(mainDQN) if __name__ == "__main__": main()
[ "gym.make", "tensorflow.get_collection", "numpy.empty", "tensorflow.global_variables_initializer", "collections.deque", "tensorflow.Session", "random.sample", "dqn.DQN", "numpy.random.rand", "numpy.vstack" ]
[((139, 162), 'gym.make', 'gym.make', (['"""CartPole-v0"""'], {}), "('CartPole-v0')\n", (147, 162), False, 'import gym\n'), ((1797, 1870), 'tensorflow.get_collection', 'tf.get_collection', (['tf.GraphKeys.TRAINABLE_VARIABLES'], {'scope': 'src_scope_name'}), '(tf.GraphKeys.TRAINABLE_VARIABLES, scope=src_scope_name)\n', (1814, 1870), True, 'import tensorflow as tf\n'), ((1896, 1970), 'tensorflow.get_collection', 'tf.get_collection', (['tf.GraphKeys.TRAINABLE_VARIABLES'], {'scope': 'dest_scope_name'}), '(tf.GraphKeys.TRAINABLE_VARIABLES, scope=dest_scope_name)\n', (1913, 1970), True, 'import tensorflow as tf\n'), ((2179, 2186), 'collections.deque', 'deque', ([], {}), '()\n', (2184, 2186), False, 'from collections import deque\n'), ((712, 735), 'numpy.vstack', 'np.vstack', (['[y_stack, Q]'], {}), '([y_stack, Q])\n', (721, 735), True, 'import numpy as np\n'), ((754, 781), 'numpy.vstack', 'np.vstack', (['[x_stack, state]'], {}), '([x_stack, state])\n', (763, 781), True, 'import numpy as np\n'), ((1266, 1289), 'numpy.vstack', 'np.vstack', (['[y_stack, Q]'], {}), '([y_stack, Q])\n', (1275, 1289), True, 'import numpy as np\n'), ((1308, 1335), 'numpy.vstack', 'np.vstack', (['[x_stack, state]'], {}), '([x_stack, state])\n', (1317, 1335), True, 'import numpy as np\n'), ((2197, 2209), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (2207, 2209), True, 'import tensorflow as tf\n'), ((2237, 2288), 'dqn.DQN', 'dqn.DQN', (['sess', 'input_size', 'output_size'], {'name': '"""main"""'}), "(sess, input_size, output_size, name='main')\n", (2244, 2288), False, 'import dqn\n'), ((2309, 2362), 'dqn.DQN', 'dqn.DQN', (['sess', 'input_size', 'output_size'], {'name': '"""target"""'}), "(sess, input_size, output_size, name='target')\n", (2316, 2362), False, 'import dqn\n'), ((351, 362), 'numpy.empty', 'np.empty', (['(0)'], {}), '(0)\n', (359, 362), True, 'import numpy as np\n'), ((400, 411), 'numpy.empty', 'np.empty', (['(0)'], {}), '(0)\n', (408, 411), True, 'import numpy as np\n'), ((893, 904), 'numpy.empty', 'np.empty', (['(0)'], {}), '(0)\n', (901, 904), True, 'import numpy as np\n'), ((942, 953), 'numpy.empty', 'np.empty', (['(0)'], {}), '(0)\n', (950, 953), True, 'import numpy as np\n'), ((2371, 2404), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (2402, 2404), True, 'import tensorflow as tf\n'), ((2781, 2798), 'numpy.random.rand', 'np.random.rand', (['(1)'], {}), '(1)\n', (2795, 2798), True, 'import numpy as np\n'), ((3711, 3743), 'random.sample', 'random.sample', (['replay_buffer', '(10)'], {}), '(replay_buffer, 10)\n', (3724, 3743), False, 'import random\n')]
from pynwb.behavior import SpatialSeries, CompassDirection import numpy as np from nwbinspector import InspectorMessage, Importance from nwbinspector.checks.behavior import check_compass_direction_unit, check_spatial_series_dims def test_check_spatial_series_dims(): spatial_series = SpatialSeries( name="SpatialSeries", description="description", data=np.ones((10, 4)), rate=3.0, reference_frame="reference_frame", ) assert check_spatial_series_dims(spatial_series) == InspectorMessage( message="SpatialSeries should have 1 column (x), 2 columns (x, y), or 3 columns (x, y, z).", importance=Importance.CRITICAL, check_function_name="check_spatial_series_dims", object_type="SpatialSeries", object_name="SpatialSeries", location="/", ) def test_pass_check_spatial_series_dims(): spatial_series = SpatialSeries( name="SpatialSeries", description="description", data=np.ones((10, 3)), rate=3.0, reference_frame="reference_frame", ) assert check_spatial_series_dims(spatial_series) is None def test_pass_check_spatial_series_dims_1d(): spatial_series = SpatialSeries( name="SpatialSeries", description="description", data=np.ones((10,)), rate=3.0, reference_frame="reference_frame", ) assert check_spatial_series_dims(spatial_series) is None def test_trigger_check_compass_direction_unit(): obj = CompassDirection( spatial_series=SpatialSeries( name="SpatialSeries", description="description", data=np.ones((10,)), rate=3.0, reference_frame="reference_frame", ) ) assert ( check_compass_direction_unit(obj)[0].message == f"SpatialSeries objects inside a CompassDirection object " f"should be angular and should have a unit of 'degrees' or 'radians', but 'SpatialSeries' has units 'meters'." ) def test_pass_check_compass_direction_unit(): for unit in ("radians", "degrees"): obj = CompassDirection( spatial_series=SpatialSeries( name="SpatialSeries", description="description", data=np.ones((10,)), rate=3.0, reference_frame="reference_frame", unit=unit, ) ) assert check_compass_direction_unit(obj) is None
[ "nwbinspector.InspectorMessage", "nwbinspector.checks.behavior.check_compass_direction_unit", "numpy.ones", "nwbinspector.checks.behavior.check_spatial_series_dims" ]
[((481, 522), 'nwbinspector.checks.behavior.check_spatial_series_dims', 'check_spatial_series_dims', (['spatial_series'], {}), '(spatial_series)\n', (506, 522), False, 'from nwbinspector.checks.behavior import check_compass_direction_unit, check_spatial_series_dims\n'), ((526, 808), 'nwbinspector.InspectorMessage', 'InspectorMessage', ([], {'message': '"""SpatialSeries should have 1 column (x), 2 columns (x, y), or 3 columns (x, y, z)."""', 'importance': 'Importance.CRITICAL', 'check_function_name': '"""check_spatial_series_dims"""', 'object_type': '"""SpatialSeries"""', 'object_name': '"""SpatialSeries"""', 'location': '"""/"""'}), "(message=\n 'SpatialSeries should have 1 column (x), 2 columns (x, y), or 3 columns (x, y, z).'\n , importance=Importance.CRITICAL, check_function_name=\n 'check_spatial_series_dims', object_type='SpatialSeries', object_name=\n 'SpatialSeries', location='/')\n", (542, 808), False, 'from nwbinspector import InspectorMessage, Importance\n'), ((1101, 1142), 'nwbinspector.checks.behavior.check_spatial_series_dims', 'check_spatial_series_dims', (['spatial_series'], {}), '(spatial_series)\n', (1126, 1142), False, 'from nwbinspector.checks.behavior import check_compass_direction_unit, check_spatial_series_dims\n'), ((1409, 1450), 'nwbinspector.checks.behavior.check_spatial_series_dims', 'check_spatial_series_dims', (['spatial_series'], {}), '(spatial_series)\n', (1434, 1450), False, 'from nwbinspector.checks.behavior import check_compass_direction_unit, check_spatial_series_dims\n'), ((385, 401), 'numpy.ones', 'np.ones', (['(10, 4)'], {}), '((10, 4))\n', (392, 401), True, 'import numpy as np\n'), ((1004, 1020), 'numpy.ones', 'np.ones', (['(10, 3)'], {}), '((10, 3))\n', (1011, 1020), True, 'import numpy as np\n'), ((1314, 1328), 'numpy.ones', 'np.ones', (['(10,)'], {}), '((10,))\n', (1321, 1328), True, 'import numpy as np\n'), ((2445, 2478), 'nwbinspector.checks.behavior.check_compass_direction_unit', 'check_compass_direction_unit', (['obj'], {}), '(obj)\n', (2473, 2478), False, 'from nwbinspector.checks.behavior import check_compass_direction_unit, check_spatial_series_dims\n'), ((1789, 1822), 'nwbinspector.checks.behavior.check_compass_direction_unit', 'check_compass_direction_unit', (['obj'], {}), '(obj)\n', (1817, 1822), False, 'from nwbinspector.checks.behavior import check_compass_direction_unit, check_spatial_series_dims\n'), ((1666, 1680), 'numpy.ones', 'np.ones', (['(10,)'], {}), '((10,))\n', (1673, 1680), True, 'import numpy as np\n'), ((2285, 2299), 'numpy.ones', 'np.ones', (['(10,)'], {}), '((10,))\n', (2292, 2299), True, 'import numpy as np\n')]
# library imports import unittest from pathlib import Path from skimage import io import numpy as np import matplotlib.pyplot as plt from sklearn.cluster import KMeans import PIL from PIL import Image from sklearn.metrics import pairwise_distances_argmin from sklearn.utils import shuffle # local imports import context from pyamiimage import octree from pyamiimage._old_image_lib import Quantizer from pyamiimage.ami_image import AmiImage from pyamiimage.ami_util import AmiUtil from resources import Resources interactive = False #interactive = True PYAMI_DIR = Path(__file__).parent.parent TEST_DIR = Path(PYAMI_DIR, "test") PICO_DIR = Path(TEST_DIR, "alex_pico/") RESOURCES_DIR = Path(TEST_DIR, "resources") LONG_TEST = False """Tests both Octree and kmeans color separation""" class TestOctree: def setup_method(self, method=None): pass def test_reading_red_black(self): """old octree""" image_name = "red_black_cv.png" # image_name = "purple_ocimum_basilicum.png" path = Path(Path(__file__).parent.parent, "assets", image_name) assert path.exists() # img = imageio.imread(path) pil_img = Image.open(path) # PIL # img = io.imread(path) # ImageLib.image_show(img) # print(img) out_image, palette, palette_image = octree.quantize(pil_img, size=4) # print(f"image {type(out_image)} ... {out_image}") assert type(out_image) == PIL.Image.Image assert out_image.size == (850, 641) assert type(palette) == list print(f"palette {len(palette)}, {palette[0]}") if interactive: out_image.show() def test_81481_octree_quantize(self): """old octree""" size = 6 path = Path(PICO_DIR, "emss-81481-f001.png") assert path.exists() # img = imageio.imread(path) img = Image.open(path) pil_rgb_image, palette, palette_image = octree.quantize(img, size=size) print(f"\npalette {type(palette)} {palette}") assert type(palette) is list, f"type palette {type(palette)}" assert len(palette) == 36 assert type(pil_rgb_image) is PIL.Image.Image nparray = np.asarray(pil_rgb_image) assert nparray.shape == (555, 572, 3) print(f"image {type(pil_rgb_image)} ... {pil_rgb_image}") print(f"palette image {type(pil_rgb_image)}") palette_array = np.asarray(pil_rgb_image) assert palette_array.shape == (555, 572, 3) path = Path(Resources.TEMP_DIR, "test1.png") print(f"path {path}") pil_rgb_image.save(path, "png") if interactive: pil_rgb_image.show() pil_rgb_image.getcolors(maxcolors=256) def test_81481_octree_new(self): """Image.quantize(colors=256, method=None, kmeans=0, palette=None, dither=1)[source] Convert the image to ‘P’ mode with the specified number of colors. Parameters colors – The desired number of colors, <= 256 method – MEDIANCUT (median cut), MAXCOVERAGE (maximum coverage), FASTOCTREE (fast octree), LIBIMAGEQUANT (libimagequant; check support using PIL.features.check_feature() with feature="libimagequant"). By default, MEDIANCUT will be used. The exception to this is RGBA images. MEDIANCUT and MAXCOVERAGE do not support RGBA images, so FASTOCTREE is used by default instead. kmeans – Integer palette – Quantize to the palette of given PIL.Image.Image. dither – Dithering method, used when converting from mode “RGB” to “P” or from “RGB” or “L” to “1”. Available methods are NONE or FLOYDSTEINBERG (default). Default: 1 (legacy setting) Returns A new image""" quantizer = Quantizer(input_dir=PICO_DIR, root="emss-81481-f001") stream = quantizer.extract_color_streams() print(f"stream {stream}") def test_example_several_color_streams(self): """not yet useful tests""" roots = [ "13068_2019_1355_Fig4_HTML", # "fmicb-09-02460-g001", # "pone.0054762.g004", # "emss-81481-f001", ] quantizer = Quantizer(input_dir=PICO_DIR, num_colors=16) for root in roots: quantizer.root = root stream = quantizer.extract_color_streams() print(f"stream {stream}") def test_green_battery(self): streams = Quantizer( input_dir=Resources.BATTERY_DIR, method="octree", root="green" ).extract_color_streams() print(f"streams {streams}") def test_skimage(self): # Authors: <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # # License: BSD 3 clause """ see https://scikit-learn.org/stable/auto_examples/cluster/plot_color_quantization.html """ import numpy as np import matplotlib.pyplot as plt from sklearn.cluster import KMeans from sklearn.metrics import pairwise_distances_argmin from sklearn.datasets import load_sample_image from sklearn.utils import shuffle from time import time n_colors = 64 n_colors = 8 # Load the Summer Palace photo china = load_sample_image("china.jpg") # Convert to floats instead of the default 8 bits integer coding. Dividing by # 255 is important so that plt.imshow behaves works well on float data (need to # be in the range [0-1]) china = np.array(china, dtype=np.float64) / 255 # Load Image and transform to a 2D numpy array. w, h, d = original_shape = tuple(china.shape) assert d == 3 image_array = np.reshape(china, (w * h, d)) print("Fitting model on a small sub-sample of the data") t0 = time() image_array_sample = shuffle(image_array, random_state=0, n_samples=1_000) kmeans = KMeans(n_clusters=n_colors, random_state=0).fit(image_array_sample) print(f"done in {time() - t0:0.3f}s.") # Get labels for all points print("Predicting color indices on the full image (k-means)") t0 = time() labels = kmeans.predict(image_array) print(f"done in {time() - t0:0.3f}s.") codebook_random = shuffle(image_array, random_state=0, n_samples=n_colors) print("Predicting color indices on the full image (random)") t0 = time() labels_random = pairwise_distances_argmin(codebook_random, image_array, axis=0) print(f"done in {time() - t0:0.3f}s.") def recreate_image(codebook, labels, w, h): """Recreate the (compressed) image from the code book & labels""" return codebook[labels].reshape(w, h, -1) # Display all results, alongside original image plt.figure(1) plt.clf() plt.axis("off") plt.title("Original image (96,615 colors)") plt.imshow(china) plt.figure(2) plt.clf() plt.axis("off") plt.title(f"Quantized image ({n_colors} colors, K-Means)") image_q = recreate_image(kmeans.cluster_centers_, labels, w, h) plt.imshow(image_q) plt.figure(3) plt.clf() plt.axis("off") plt.title(f"Quantized image ({n_colors} colors, Random)") image_qq = recreate_image(codebook_random, labels_random, w, h) plt.imshow(image_qq) if interactive: plt.show() def test_skimage1(self): n_colors = 4 path = Path(Resources.BATTERY_DIR, "green.png") img0 = io.imread(path) img = np.array(img0, dtype=np.float64) / 255 w, h, d = original_shape = tuple(img.shape) image_array = np.reshape(img, (w * h, d)) image_array_sample = shuffle(image_array, random_state=0, n_samples=1_000) kmeans = KMeans(n_clusters=n_colors, random_state=0).fit(image_array_sample) labels = kmeans.predict(image_array) codebook_random = shuffle(image_array, random_state=0, n_samples=n_colors) labels_random = pairwise_distances_argmin(codebook_random, image_array, axis=0) plt.figure(1) plt.clf() plt.axis("off") plt.title("Original image (96,615 colors)") plt.imshow(img) plt.figure(2) plt.clf() plt.axis("off") plt.title(f"Quantized image ({n_colors} colors, K-Means)") image_q = kmeans.cluster_centers_[labels].reshape(w, h, -1) plt.imshow(image_q) plt.figure(3) plt.clf() plt.axis("off") plt.title(f"Quantized image ({n_colors} colors, Random)") image_qq = codebook_random[labels_random].reshape(w, h, -1) plt.imshow(image_qq) if interactive: plt.show() def test_kmeans2(self): """https://stackoverflow.com/questions/48222977/python-converting-an-image-to-use-less-colors""" import numpy as np from skimage import io from sklearn.cluster import KMeans expected = [[222, 227, 219], [16, 16, 17], [95, 96, 97], [253, 149, 75], [1, 235, 29], [254, 254, 254], [20, 15, 196], [162, 187, 176], [240, 17, 23], [0, 118, 19]] background = [255, 255, 255] name = "green" self._means_test_write(name, expected=expected) @unittest.skipUnless(LONG_TEST, "takes too long") def test_kmeans_long(self): for name in [ "pmc8839570", "MED_34909142_3", "Signal_transduction_pathways_wp", "red_black_cv", "prisma" ]: print(f"======{name}======") self._means_test_write(name, background=[255,255, 200], ncolors=10) def _means_test_write(self, name, background=[255, 255, 255], expected=None, ncolors=10): """skimage kmeans""" path = Path(Resources.TEST_RESOURCE_DIR, name + ".png") if not path.exists(): path = Path(Resources.TEST_RESOURCE_DIR, name + ".jpeg") raw_image = io.imread(path) color_delta = 20 labels, color_centers, quantized_images = AmiImage.kmeans(raw_image, ncolors, background) print(color_centers) for i, color in enumerate(color_centers): if AmiUtil.is_white(color, color_delta): print(f"white: {color}") elif AmiUtil.is_black(color, color_delta): print(f"black: {color}") elif AmiUtil.is_gray(color, color_delta): print(f"gray: {color}") continue hexs = ''.join(AmiUtil.int2hex(c)[-2:-1] for c in color) if expected: assert color == expected[i], f"color_centers {color}" dir_path = Path(Resources.TEMP_DIR, name) if not dir_path.exists(): dir_path.mkdir() path = Path(dir_path, f"kmeans_{i}_{hexs}.png") io.imsave(path, quantized_images[i]) # -------- Utility -------- @classmethod def get_py4ami_dir(cls): return Path(__file__).parent.parent """ img_bytes = bytes([R1, G1, B1, R2, G2, B2,..., Rn, Gn, Bn]) im = Image.frombytes("RGB", (width, height), img_bytes)"""
[ "matplotlib.pyplot.title", "matplotlib.pyplot.clf", "pyamiimage.ami_util.AmiUtil.int2hex", "sklearn.datasets.load_sample_image", "pathlib.Path", "matplotlib.pyplot.figure", "matplotlib.pyplot.imshow", "sklearn.cluster.KMeans", "pyamiimage.octree.quantize", "sklearn.metrics.pairwise_distances_argmi...
[((610, 633), 'pathlib.Path', 'Path', (['PYAMI_DIR', '"""test"""'], {}), "(PYAMI_DIR, 'test')\n", (614, 633), False, 'from pathlib import Path\n'), ((645, 673), 'pathlib.Path', 'Path', (['TEST_DIR', '"""alex_pico/"""'], {}), "(TEST_DIR, 'alex_pico/')\n", (649, 673), False, 'from pathlib import Path\n'), ((690, 717), 'pathlib.Path', 'Path', (['TEST_DIR', '"""resources"""'], {}), "(TEST_DIR, 'resources')\n", (694, 717), False, 'from pathlib import Path\n'), ((9382, 9430), 'unittest.skipUnless', 'unittest.skipUnless', (['LONG_TEST', '"""takes too long"""'], {}), "(LONG_TEST, 'takes too long')\n", (9401, 9430), False, 'import unittest\n'), ((570, 584), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (574, 584), False, 'from pathlib import Path\n'), ((1176, 1192), 'PIL.Image.open', 'Image.open', (['path'], {}), '(path)\n', (1186, 1192), False, 'from PIL import Image\n'), ((1334, 1366), 'pyamiimage.octree.quantize', 'octree.quantize', (['pil_img'], {'size': '(4)'}), '(pil_img, size=4)\n', (1349, 1366), False, 'from pyamiimage import octree\n'), ((1766, 1803), 'pathlib.Path', 'Path', (['PICO_DIR', '"""emss-81481-f001.png"""'], {}), "(PICO_DIR, 'emss-81481-f001.png')\n", (1770, 1803), False, 'from pathlib import Path\n'), ((1884, 1900), 'PIL.Image.open', 'Image.open', (['path'], {}), '(path)\n', (1894, 1900), False, 'from PIL import Image\n'), ((1949, 1980), 'pyamiimage.octree.quantize', 'octree.quantize', (['img'], {'size': 'size'}), '(img, size=size)\n', (1964, 1980), False, 'from pyamiimage import octree\n'), ((2212, 2237), 'numpy.asarray', 'np.asarray', (['pil_rgb_image'], {}), '(pil_rgb_image)\n', (2222, 2237), True, 'import numpy as np\n'), ((2428, 2453), 'numpy.asarray', 'np.asarray', (['pil_rgb_image'], {}), '(pil_rgb_image)\n', (2438, 2453), True, 'import numpy as np\n'), ((2521, 2558), 'pathlib.Path', 'Path', (['Resources.TEMP_DIR', '"""test1.png"""'], {}), "(Resources.TEMP_DIR, 'test1.png')\n", (2525, 2558), False, 'from pathlib import Path\n'), ((3777, 3830), 'pyamiimage._old_image_lib.Quantizer', 'Quantizer', ([], {'input_dir': 'PICO_DIR', 'root': '"""emss-81481-f001"""'}), "(input_dir=PICO_DIR, root='emss-81481-f001')\n", (3786, 3830), False, 'from pyamiimage._old_image_lib import Quantizer\n'), ((4197, 4241), 'pyamiimage._old_image_lib.Quantizer', 'Quantizer', ([], {'input_dir': 'PICO_DIR', 'num_colors': '(16)'}), '(input_dir=PICO_DIR, num_colors=16)\n', (4206, 4241), False, 'from pyamiimage._old_image_lib import Quantizer\n'), ((5304, 5334), 'sklearn.datasets.load_sample_image', 'load_sample_image', (['"""china.jpg"""'], {}), "('china.jpg')\n", (5321, 5334), False, 'from sklearn.datasets import load_sample_image\n'), ((5754, 5783), 'numpy.reshape', 'np.reshape', (['china', '(w * h, d)'], {}), '(china, (w * h, d))\n', (5764, 5783), True, 'import numpy as np\n'), ((5863, 5869), 'time.time', 'time', ([], {}), '()\n', (5867, 5869), False, 'from time import time\n'), ((5899, 5951), 'sklearn.utils.shuffle', 'shuffle', (['image_array'], {'random_state': '(0)', 'n_samples': '(1000)'}), '(image_array, random_state=0, n_samples=1000)\n', (5906, 5951), False, 'from sklearn.utils import shuffle\n'), ((6205, 6211), 'time.time', 'time', ([], {}), '()\n', (6209, 6211), False, 'from time import time\n'), ((6331, 6387), 'sklearn.utils.shuffle', 'shuffle', (['image_array'], {'random_state': '(0)', 'n_samples': 'n_colors'}), '(image_array, random_state=0, n_samples=n_colors)\n', (6338, 6387), False, 'from sklearn.utils import shuffle\n'), ((6470, 6476), 'time.time', 'time', ([], {}), '()\n', (6474, 6476), False, 'from time import time\n'), ((6501, 6564), 'sklearn.metrics.pairwise_distances_argmin', 'pairwise_distances_argmin', (['codebook_random', 'image_array'], {'axis': '(0)'}), '(codebook_random, image_array, axis=0)\n', (6526, 6564), False, 'from sklearn.metrics import pairwise_distances_argmin\n'), ((6862, 6875), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {}), '(1)\n', (6872, 6875), True, 'import matplotlib.pyplot as plt\n'), ((6884, 6893), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (6891, 6893), True, 'import matplotlib.pyplot as plt\n'), ((6902, 6917), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (6910, 6917), True, 'import matplotlib.pyplot as plt\n'), ((6926, 6969), 'matplotlib.pyplot.title', 'plt.title', (['"""Original image (96,615 colors)"""'], {}), "('Original image (96,615 colors)')\n", (6935, 6969), True, 'import matplotlib.pyplot as plt\n'), ((6978, 6995), 'matplotlib.pyplot.imshow', 'plt.imshow', (['china'], {}), '(china)\n', (6988, 6995), True, 'import matplotlib.pyplot as plt\n'), ((7005, 7018), 'matplotlib.pyplot.figure', 'plt.figure', (['(2)'], {}), '(2)\n', (7015, 7018), True, 'import matplotlib.pyplot as plt\n'), ((7027, 7036), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (7034, 7036), True, 'import matplotlib.pyplot as plt\n'), ((7045, 7060), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (7053, 7060), True, 'import matplotlib.pyplot as plt\n'), ((7069, 7127), 'matplotlib.pyplot.title', 'plt.title', (['f"""Quantized image ({n_colors} colors, K-Means)"""'], {}), "(f'Quantized image ({n_colors} colors, K-Means)')\n", (7078, 7127), True, 'import matplotlib.pyplot as plt\n'), ((7208, 7227), 'matplotlib.pyplot.imshow', 'plt.imshow', (['image_q'], {}), '(image_q)\n', (7218, 7227), True, 'import matplotlib.pyplot as plt\n'), ((7237, 7250), 'matplotlib.pyplot.figure', 'plt.figure', (['(3)'], {}), '(3)\n', (7247, 7250), True, 'import matplotlib.pyplot as plt\n'), ((7259, 7268), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (7266, 7268), True, 'import matplotlib.pyplot as plt\n'), ((7277, 7292), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (7285, 7292), True, 'import matplotlib.pyplot as plt\n'), ((7301, 7358), 'matplotlib.pyplot.title', 'plt.title', (['f"""Quantized image ({n_colors} colors, Random)"""'], {}), "(f'Quantized image ({n_colors} colors, Random)')\n", (7310, 7358), True, 'import matplotlib.pyplot as plt\n'), ((7439, 7459), 'matplotlib.pyplot.imshow', 'plt.imshow', (['image_qq'], {}), '(image_qq)\n', (7449, 7459), True, 'import matplotlib.pyplot as plt\n'), ((7574, 7614), 'pathlib.Path', 'Path', (['Resources.BATTERY_DIR', '"""green.png"""'], {}), "(Resources.BATTERY_DIR, 'green.png')\n", (7578, 7614), False, 'from pathlib import Path\n'), ((7630, 7645), 'skimage.io.imread', 'io.imread', (['path'], {}), '(path)\n', (7639, 7645), False, 'from skimage import io\n'), ((7773, 7800), 'numpy.reshape', 'np.reshape', (['img', '(w * h, d)'], {}), '(img, (w * h, d))\n', (7783, 7800), True, 'import numpy as np\n'), ((7830, 7882), 'sklearn.utils.shuffle', 'shuffle', (['image_array'], {'random_state': '(0)', 'n_samples': '(1000)'}), '(image_array, random_state=0, n_samples=1000)\n', (7837, 7882), False, 'from sklearn.utils import shuffle\n'), ((8040, 8096), 'sklearn.utils.shuffle', 'shuffle', (['image_array'], {'random_state': '(0)', 'n_samples': 'n_colors'}), '(image_array, random_state=0, n_samples=n_colors)\n', (8047, 8096), False, 'from sklearn.utils import shuffle\n'), ((8121, 8184), 'sklearn.metrics.pairwise_distances_argmin', 'pairwise_distances_argmin', (['codebook_random', 'image_array'], {'axis': '(0)'}), '(codebook_random, image_array, axis=0)\n', (8146, 8184), False, 'from sklearn.metrics import pairwise_distances_argmin\n'), ((8194, 8207), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {}), '(1)\n', (8204, 8207), True, 'import matplotlib.pyplot as plt\n'), ((8216, 8225), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (8223, 8225), True, 'import matplotlib.pyplot as plt\n'), ((8234, 8249), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (8242, 8249), True, 'import matplotlib.pyplot as plt\n'), ((8258, 8301), 'matplotlib.pyplot.title', 'plt.title', (['"""Original image (96,615 colors)"""'], {}), "('Original image (96,615 colors)')\n", (8267, 8301), True, 'import matplotlib.pyplot as plt\n'), ((8310, 8325), 'matplotlib.pyplot.imshow', 'plt.imshow', (['img'], {}), '(img)\n', (8320, 8325), True, 'import matplotlib.pyplot as plt\n'), ((8335, 8348), 'matplotlib.pyplot.figure', 'plt.figure', (['(2)'], {}), '(2)\n', (8345, 8348), True, 'import matplotlib.pyplot as plt\n'), ((8357, 8366), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (8364, 8366), True, 'import matplotlib.pyplot as plt\n'), ((8375, 8390), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (8383, 8390), True, 'import matplotlib.pyplot as plt\n'), ((8399, 8457), 'matplotlib.pyplot.title', 'plt.title', (['f"""Quantized image ({n_colors} colors, K-Means)"""'], {}), "(f'Quantized image ({n_colors} colors, K-Means)')\n", (8408, 8457), True, 'import matplotlib.pyplot as plt\n'), ((8534, 8553), 'matplotlib.pyplot.imshow', 'plt.imshow', (['image_q'], {}), '(image_q)\n', (8544, 8553), True, 'import matplotlib.pyplot as plt\n'), ((8563, 8576), 'matplotlib.pyplot.figure', 'plt.figure', (['(3)'], {}), '(3)\n', (8573, 8576), True, 'import matplotlib.pyplot as plt\n'), ((8585, 8594), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (8592, 8594), True, 'import matplotlib.pyplot as plt\n'), ((8603, 8618), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (8611, 8618), True, 'import matplotlib.pyplot as plt\n'), ((8627, 8684), 'matplotlib.pyplot.title', 'plt.title', (['f"""Quantized image ({n_colors} colors, Random)"""'], {}), "(f'Quantized image ({n_colors} colors, Random)')\n", (8636, 8684), True, 'import matplotlib.pyplot as plt\n'), ((8761, 8781), 'matplotlib.pyplot.imshow', 'plt.imshow', (['image_qq'], {}), '(image_qq)\n', (8771, 8781), True, 'import matplotlib.pyplot as plt\n'), ((9909, 9957), 'pathlib.Path', 'Path', (['Resources.TEST_RESOURCE_DIR', "(name + '.png')"], {}), "(Resources.TEST_RESOURCE_DIR, name + '.png')\n", (9913, 9957), False, 'from pathlib import Path\n'), ((10077, 10092), 'skimage.io.imread', 'io.imread', (['path'], {}), '(path)\n', (10086, 10092), False, 'from skimage import io\n'), ((10168, 10215), 'pyamiimage.ami_image.AmiImage.kmeans', 'AmiImage.kmeans', (['raw_image', 'ncolors', 'background'], {}), '(raw_image, ncolors, background)\n', (10183, 10215), False, 'from pyamiimage.ami_image import AmiImage\n'), ((5559, 5592), 'numpy.array', 'np.array', (['china'], {'dtype': 'np.float64'}), '(china, dtype=np.float64)\n', (5567, 5592), True, 'import numpy as np\n'), ((7496, 7506), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (7504, 7506), True, 'import matplotlib.pyplot as plt\n'), ((7660, 7692), 'numpy.array', 'np.array', (['img0'], {'dtype': 'np.float64'}), '(img0, dtype=np.float64)\n', (7668, 7692), True, 'import numpy as np\n'), ((8818, 8828), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (8826, 8828), True, 'import matplotlib.pyplot as plt\n'), ((10007, 10056), 'pathlib.Path', 'Path', (['Resources.TEST_RESOURCE_DIR', "(name + '.jpeg')"], {}), "(Resources.TEST_RESOURCE_DIR, name + '.jpeg')\n", (10011, 10056), False, 'from pathlib import Path\n'), ((10310, 10346), 'pyamiimage.ami_util.AmiUtil.is_white', 'AmiUtil.is_white', (['color', 'color_delta'], {}), '(color, color_delta)\n', (10326, 10346), False, 'from pyamiimage.ami_util import AmiUtil\n'), ((10791, 10821), 'pathlib.Path', 'Path', (['Resources.TEMP_DIR', 'name'], {}), '(Resources.TEMP_DIR, name)\n', (10795, 10821), False, 'from pathlib import Path\n'), ((10912, 10952), 'pathlib.Path', 'Path', (['dir_path', 'f"""kmeans_{i}_{hexs}.png"""'], {}), "(dir_path, f'kmeans_{i}_{hexs}.png')\n", (10916, 10952), False, 'from pathlib import Path\n'), ((10965, 11001), 'skimage.io.imsave', 'io.imsave', (['path', 'quantized_images[i]'], {}), '(path, quantized_images[i])\n', (10974, 11001), False, 'from skimage import io\n'), ((4449, 4522), 'pyamiimage._old_image_lib.Quantizer', 'Quantizer', ([], {'input_dir': 'Resources.BATTERY_DIR', 'method': '"""octree"""', 'root': '"""green"""'}), "(input_dir=Resources.BATTERY_DIR, method='octree', root='green')\n", (4458, 4522), False, 'from pyamiimage._old_image_lib import Quantizer\n'), ((5970, 6013), 'sklearn.cluster.KMeans', 'KMeans', ([], {'n_clusters': 'n_colors', 'random_state': '(0)'}), '(n_clusters=n_colors, random_state=0)\n', (5976, 6013), False, 'from sklearn.cluster import KMeans\n'), ((7901, 7944), 'sklearn.cluster.KMeans', 'KMeans', ([], {'n_clusters': 'n_colors', 'random_state': '(0)'}), '(n_clusters=n_colors, random_state=0)\n', (7907, 7944), False, 'from sklearn.cluster import KMeans\n'), ((10406, 10442), 'pyamiimage.ami_util.AmiUtil.is_black', 'AmiUtil.is_black', (['color', 'color_delta'], {}), '(color, color_delta)\n', (10422, 10442), False, 'from pyamiimage.ami_util import AmiUtil\n'), ((11096, 11110), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (11100, 11110), False, 'from pathlib import Path\n'), ((1040, 1054), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (1044, 1054), False, 'from pathlib import Path\n'), ((10502, 10537), 'pyamiimage.ami_util.AmiUtil.is_gray', 'AmiUtil.is_gray', (['color', 'color_delta'], {}), '(color, color_delta)\n', (10517, 10537), False, 'from pyamiimage.ami_util import AmiUtil\n'), ((6063, 6069), 'time.time', 'time', ([], {}), '()\n', (6067, 6069), False, 'from time import time\n'), ((6282, 6288), 'time.time', 'time', ([], {}), '()\n', (6286, 6288), False, 'from time import time\n'), ((6590, 6596), 'time.time', 'time', ([], {}), '()\n', (6594, 6596), False, 'from time import time\n'), ((10631, 10649), 'pyamiimage.ami_util.AmiUtil.int2hex', 'AmiUtil.int2hex', (['c'], {}), '(c)\n', (10646, 10649), False, 'from pyamiimage.ami_util import AmiUtil\n')]
#!/usr/bin/env python """Fetch vectors of :term:`counts` at each nucleotide position in one or more regions of interest (ROIs). Output files ------------ Vectors are saved as individual line-delimited files -- one position per line -- in a user-specified output folder. Each file is named for the ROI to which it corresponds. If a :term:`mask file` -- e.g. from :py:mod:`~plastid.bin.crossmap` -- is provided, masked positions will be have value `nan` in output. """ import argparse import inspect import os import warnings import sys import numpy from plastid.util.scriptlib.argparsers import ( AlignmentParser, AnnotationParser, MaskParser, BaseParser, ) from plastid.util.io.openers import get_short_name from plastid.util.io.filters import NameDateWriter from plastid.util.scriptlib.help_formatters import format_module_docstring warnings.simplefilter("once") printer = NameDateWriter(get_short_name(inspect.stack()[-1][1])) def main(args=sys.argv[1:]): """Command-line program Parameters ---------- argv : list, optional A list of command-line arguments, which will be processed as if the script were called from the command line if :func:`main` is called directly. Default: `sys.argv[1:]`. The command-line arguments, if the script is invoked from the command line """ al = AlignmentParser() an = AnnotationParser() mp = MaskParser() bp = BaseParser() alignment_file_parser = al.get_parser(conflict_handler="resolve") annotation_file_parser = an.get_parser(conflict_handler="resolve") mask_file_parser = mp.get_parser() base_parser = bp.get_parser() parser = argparse.ArgumentParser( description = format_module_docstring(__doc__), formatter_class = argparse.RawDescriptionHelpFormatter, conflict_handler = "resolve", parents = [base_parser, alignment_file_parser, annotation_file_parser, mask_file_parser] ) # yapf: disable parser.add_argument("out_folder", type=str, help="Folder in which to save output vectors") parser.add_argument( "--out_prefix", default="", type=str, help="Prefix to prepend to output files (default: no prefix)" ) parser.add_argument( "--format", default="%.8f", type=str, help=r"printf-style format string for output (default: '%%.8f')" ) args = parser.parse_args(args) bp.get_base_ops_from_args(args) # if output folder doesn't exist, create it if not os.path.isdir(args.out_folder): os.mkdir(args.out_folder) # parse args # yapf: disable ga = al.get_genome_array_from_args(args, printer=printer) transcripts = an.get_segmentchains_from_args(args, printer=printer) mask_hash = mp.get_genome_hash_from_args(args, printer=printer) # yapf: enable # evaluate for n, tx in enumerate(transcripts): if n % 1000 == 0: printer.write("Processed %s regions of interest" % n) filename = "%s%s.txt" % (args.out_prefix, tx.get_name()) full_filename = os.path.join(args.out_folder, filename) # mask out overlapping masked regions overlapping = mask_hash.get_overlapping_features(tx) for feature in overlapping: tx.add_masks(*feature.segments) count_vec = tx.get_masked_counts(ga) numpy.savetxt(full_filename, count_vec, fmt=args.format) if __name__ == "__main__": main()
[ "os.mkdir", "inspect.stack", "warnings.simplefilter", "os.path.isdir", "plastid.util.scriptlib.argparsers.AlignmentParser", "numpy.savetxt", "plastid.util.scriptlib.argparsers.MaskParser", "plastid.util.scriptlib.argparsers.BaseParser", "os.path.join", "plastid.util.scriptlib.help_formatters.forma...
[((855, 884), 'warnings.simplefilter', 'warnings.simplefilter', (['"""once"""'], {}), "('once')\n", (876, 884), False, 'import warnings\n'), ((1373, 1390), 'plastid.util.scriptlib.argparsers.AlignmentParser', 'AlignmentParser', ([], {}), '()\n', (1388, 1390), False, 'from plastid.util.scriptlib.argparsers import AlignmentParser, AnnotationParser, MaskParser, BaseParser\n'), ((1400, 1418), 'plastid.util.scriptlib.argparsers.AnnotationParser', 'AnnotationParser', ([], {}), '()\n', (1416, 1418), False, 'from plastid.util.scriptlib.argparsers import AlignmentParser, AnnotationParser, MaskParser, BaseParser\n'), ((1428, 1440), 'plastid.util.scriptlib.argparsers.MaskParser', 'MaskParser', ([], {}), '()\n', (1438, 1440), False, 'from plastid.util.scriptlib.argparsers import AlignmentParser, AnnotationParser, MaskParser, BaseParser\n'), ((1450, 1462), 'plastid.util.scriptlib.argparsers.BaseParser', 'BaseParser', ([], {}), '()\n', (1460, 1462), False, 'from plastid.util.scriptlib.argparsers import AlignmentParser, AnnotationParser, MaskParser, BaseParser\n'), ((2556, 2586), 'os.path.isdir', 'os.path.isdir', (['args.out_folder'], {}), '(args.out_folder)\n', (2569, 2586), False, 'import os\n'), ((2596, 2621), 'os.mkdir', 'os.mkdir', (['args.out_folder'], {}), '(args.out_folder)\n', (2604, 2621), False, 'import os\n'), ((3133, 3172), 'os.path.join', 'os.path.join', (['args.out_folder', 'filename'], {}), '(args.out_folder, filename)\n', (3145, 3172), False, 'import os\n'), ((3415, 3471), 'numpy.savetxt', 'numpy.savetxt', (['full_filename', 'count_vec'], {'fmt': 'args.format'}), '(full_filename, count_vec, fmt=args.format)\n', (3428, 3471), False, 'import numpy\n'), ((1744, 1776), 'plastid.util.scriptlib.help_formatters.format_module_docstring', 'format_module_docstring', (['__doc__'], {}), '(__doc__)\n', (1767, 1776), False, 'from plastid.util.scriptlib.help_formatters import format_module_docstring\n'), ((925, 940), 'inspect.stack', 'inspect.stack', ([], {}), '()\n', (938, 940), False, 'import inspect\n')]
# Author: <NAME> (<EMAIL>) # License: MIT, see LICENSE.md import numpy as np import sys param = {} execfile(sys.argv[1]) def compute_averaged_mag(cat_mag, ind): return np.average([np.average(mag[:, ind]) for mag in cat_mag]) def apply_offset(cat_mag, offset): return [mag-offset for mag in cat_mag] def compute_final_magnitudes(cat_mag, ind): # nightly_avg_mag = [np.average(mag[:, ind]) for mag in cat_mag] nightly_std_mag = [np.std(mag[:, ind]) for mag in cat_mag] night_numbering = [[i+1]*len(mag[:, 0]) for (i, mag) in enumerate(cat_mag)] night_numbering_list = [] [night_numbering_list.extend(n) for n in night_numbering] mag = [mag[:, ind] for mag in cat_mag] mag_list = [] [mag_list.extend(m) for m in mag] frames_per_night = [len(mag[:, ind]) for mag in cat_mag] std_list = [] [std_list.extend([nightly_std_mag[k]]*frames_per_night[k]) for k in xrange(len(frames_per_night))] # Errorbars of the mean divided by sqrt(n) nightly_avg_mag = [np.average(mag[:, ind]) for mag in cat_mag] # nightly_std_mag = [np.std(mag[:, ind])/np.sqrt(np.float(len(mag[:, ind]))) for mag in cat_mag] return mag_list, std_list, nightly_avg_mag, nightly_std_mag, night_numbering_list def compute_final_date(cat_mjd): mjd_list = [] [mjd_list.extend(mjd) for mjd in cat_mjd] mjd = np.asarray([np.average(mjd) for mjd in cat_mjd]) return mjd, mjd_list def add_offset(cat_mag, cat_mjd, ind, offset, compute_offset): if compute_offset: target_obs_mag = param['zero_magnitude'] target_ins_mag = compute_averaged_mag(cat_mag, ind) offset = target_ins_mag-target_obs_mag cat_mag = apply_offset(cat_mag, offset) mag_list, std_list, nightly_avg_mag, nightly_std_mag, night_numbering_list = compute_final_magnitudes(cat_mag, ind) mjd, mjd_list = compute_final_date(cat_mjd) return cat_mag, mag_list, std_list, nightly_avg_mag, nightly_std_mag, mjd, mjd_list, night_numbering_list, offset if __name__ == '__main__': # Testing print('STOP: Testing should be done from analysis.py')
[ "numpy.std", "numpy.average" ]
[((451, 470), 'numpy.std', 'np.std', (['mag[:, ind]'], {}), '(mag[:, ind])\n', (457, 470), True, 'import numpy as np\n'), ((1018, 1041), 'numpy.average', 'np.average', (['mag[:, ind]'], {}), '(mag[:, ind])\n', (1028, 1041), True, 'import numpy as np\n'), ((188, 211), 'numpy.average', 'np.average', (['mag[:, ind]'], {}), '(mag[:, ind])\n', (198, 211), True, 'import numpy as np\n'), ((1370, 1385), 'numpy.average', 'np.average', (['mjd'], {}), '(mjd)\n', (1380, 1385), True, 'import numpy as np\n')]
# Copyright (C) 2018-2022 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import paddle import numpy as np import os import sys from paddle.fluid.proto import framework_pb2 paddle.enable_static() inp_blob = np.random.randn(1, 3, 4, 4).astype(np.float32) print(sys.path) main_program = paddle.static.Program() startup_program = paddle.static.Program() with paddle.static.program_guard(main_program, startup_program): x = paddle.static.data(name='x', shape=[1, 3, 4, 4], dtype='float32') test_layer = paddle.static.nn.conv2d(input=x, num_filters=5, filter_size=(1, 1), stride=(1, 1), padding=(1, 1), dilation=(1, 1), groups=1, bias_attr=False) cpu = paddle.static.cpu_places(1) exe = paddle.static.Executor(cpu[0]) exe.run(startup_program) inp_dict = {'x': inp_blob} var = [test_layer] res_paddle = exe.run(paddle.static.default_main_program(), fetch_list=var, feed=inp_dict) paddle.static.save_inference_model(os.path.join(sys.argv[1], "lower_version/", "lower_version"), [x], [test_layer], exe, program=main_program) fw_model = framework_pb2.ProgramDesc() with open(os.path.join(sys.argv[1], "lower_version", "lower_version.pdmodel"), mode='rb') as file: fw_model.ParseFromString(file.read()) fw_model.version.version = 1800000 print(fw_model.version.version) with open(os.path.join(sys.argv[1], "lower_version", "lower_version.pdmodel"), "wb") as f: f.write(fw_model.SerializeToString())
[ "paddle.fluid.proto.framework_pb2.ProgramDesc", "paddle.static.data", "paddle.static.nn.conv2d", "paddle.static.default_main_program", "paddle.static.cpu_places", "numpy.random.randn", "paddle.enable_static", "paddle.static.Program", "paddle.static.program_guard", "paddle.static.Executor", "os.p...
[((183, 205), 'paddle.enable_static', 'paddle.enable_static', ([], {}), '()\n', (203, 205), False, 'import paddle\n'), ((296, 319), 'paddle.static.Program', 'paddle.static.Program', ([], {}), '()\n', (317, 319), False, 'import paddle\n'), ((338, 361), 'paddle.static.Program', 'paddle.static.Program', ([], {}), '()\n', (359, 361), False, 'import paddle\n'), ((1116, 1143), 'paddle.fluid.proto.framework_pb2.ProgramDesc', 'framework_pb2.ProgramDesc', ([], {}), '()\n', (1141, 1143), False, 'from paddle.fluid.proto import framework_pb2\n'), ((368, 426), 'paddle.static.program_guard', 'paddle.static.program_guard', (['main_program', 'startup_program'], {}), '(main_program, startup_program)\n', (395, 426), False, 'import paddle\n'), ((436, 501), 'paddle.static.data', 'paddle.static.data', ([], {'name': '"""x"""', 'shape': '[1, 3, 4, 4]', 'dtype': '"""float32"""'}), "(name='x', shape=[1, 3, 4, 4], dtype='float32')\n", (454, 501), False, 'import paddle\n'), ((519, 666), 'paddle.static.nn.conv2d', 'paddle.static.nn.conv2d', ([], {'input': 'x', 'num_filters': '(5)', 'filter_size': '(1, 1)', 'stride': '(1, 1)', 'padding': '(1, 1)', 'dilation': '(1, 1)', 'groups': '(1)', 'bias_attr': '(False)'}), '(input=x, num_filters=5, filter_size=(1, 1), stride=\n (1, 1), padding=(1, 1), dilation=(1, 1), groups=1, bias_attr=False)\n', (542, 666), False, 'import paddle\n'), ((710, 737), 'paddle.static.cpu_places', 'paddle.static.cpu_places', (['(1)'], {}), '(1)\n', (734, 737), False, 'import paddle\n'), ((748, 778), 'paddle.static.Executor', 'paddle.static.Executor', (['cpu[0]'], {}), '(cpu[0])\n', (770, 778), False, 'import paddle\n'), ((218, 245), 'numpy.random.randn', 'np.random.randn', (['(1)', '(3)', '(4)', '(4)'], {}), '(1, 3, 4, 4)\n', (233, 245), True, 'import numpy as np\n'), ((887, 923), 'paddle.static.default_main_program', 'paddle.static.default_main_program', ([], {}), '()\n', (921, 923), False, 'import paddle\n'), ((995, 1055), 'os.path.join', 'os.path.join', (['sys.argv[1]', '"""lower_version/"""', '"""lower_version"""'], {}), "(sys.argv[1], 'lower_version/', 'lower_version')\n", (1007, 1055), False, 'import os\n'), ((1154, 1221), 'os.path.join', 'os.path.join', (['sys.argv[1]', '"""lower_version"""', '"""lower_version.pdmodel"""'], {}), "(sys.argv[1], 'lower_version', 'lower_version.pdmodel')\n", (1166, 1221), False, 'import os\n'), ((1363, 1430), 'os.path.join', 'os.path.join', (['sys.argv[1]', '"""lower_version"""', '"""lower_version.pdmodel"""'], {}), "(sys.argv[1], 'lower_version', 'lower_version.pdmodel')\n", (1375, 1430), False, 'import os\n')]
#!/usr/bin/env python3 import sys import soundfile import numpy from scipy.signal import butter, lfilter import argparse import multiprocessing import itertools # bark frequency bands FREQ_BANDS = [ 20, 119, 224, 326, 438, 561, 698, 850, 1021, 1213, 1433, 1685, 1978, 2322, 2731, 3227, 3841, 4619, 5638, 6938, 8492, 10705, 14105, 20000, ] def envelope(x, fs, params): attack = params[0] fast_attack = params[1] slow_attack = params[2] release = params[3] power_mem = params[4] g_fast = numpy.exp(-1.0 / (fs * fast_attack / 1000.0)) g_slow = numpy.exp(-1.0 / (fs * slow_attack / 1000.0)) g_release = numpy.exp(-1.0 / (fs * release / 1000.0)) g_power = numpy.exp(-1.0 / (fs * power_mem / 1000.0)) fb_fast = 0 fb_slow = 0 fb_pow = 0 N = len(x) fast_envelope = numpy.zeros(N) slow_envelope = numpy.zeros(N) attack_gain_curve = numpy.zeros(N) x_power = numpy.zeros(N) x_deriv_power = numpy.zeros(N) for n in range(N): x_power[n] = (1 - g_power) * x[n] * x[n] + g_power * fb_pow fb_pow = x_power[n] x_deriv_power[0] = x_power[0] # simple differentiator filter for n in range(1, N): x_deriv_power[n] = x_power[n] - x_power[n - 1] for n in range(N): if fb_fast > x_deriv_power[n]: fast_envelope[n] = (1 - g_release) * x_deriv_power[n] + g_release * fb_fast else: fast_envelope[n] = (1 - g_fast) * x_deriv_power[n] + g_fast * fb_fast fb_fast = fast_envelope[n] if fb_slow > x_deriv_power[n]: slow_envelope[n] = (1 - g_release) * x_deriv_power[n] + g_release * fb_slow else: slow_envelope[n] = (1 - g_slow) * x_deriv_power[n] + g_slow * fb_slow fb_slow = slow_envelope[n] attack_gain_curve[n] = fast_envelope[n] - slow_envelope[n] attack_gain_curve /= numpy.max(attack_gain_curve) if attack == 1: # normalize to [0, 1.0] return x * attack_gain_curve # sustain curve is the inverse return x * (1 - attack_gain_curve) def single_band_transient_shaper(band, x, fs, shaper_params, order=2): nyq = 0.5 * fs lo = FREQ_BANDS[band] hi = FREQ_BANDS[band + 1] print("band: {0}-{1} Hz".format(lo, hi)) b, a = butter(order, [lo / nyq, hi / nyq], btype="band") y = lfilter(b, a, x) # per bark band, apply a differential envelope attack/transient enhancer y_shaped = envelope(y, fs, shaper_params) return y_shaped def multiband_transient_shaper(x, fs, shaper_params, npool=16): if shaper_params[0] not in [0, 1]: raise ValueError("attack should be 0 (boost sustain) or 1 (boost attacks)") pool = multiprocessing.Pool(npool) # bark band decomposition band_results = list( pool.starmap( single_band_transient_shaper, zip( range(0, len(FREQ_BANDS) - 1, 1), itertools.repeat(x), itertools.repeat(fs), itertools.repeat(shaper_params), ), ) ) y_t = numpy.zeros(len(x)) for banded_attacks in band_results: y_t += banded_attacks return y_t def main(): parser = argparse.ArgumentParser( prog="transient_shaper.py", description="Multiband differential envelope transient shaper", ) parser.add_argument( "--fast-attack-ms", type=int, default=1, help="Fast attack (ms)" ) parser.add_argument( "--slow-attack-ms", type=int, default=15, help="Slow attack (ms)" ) parser.add_argument("--release-ms", type=int, default=20, help="Release (ms)") parser.add_argument( "--power-memory-ms", type=int, default=1, help="Power filter memory (ms)" ) parser.add_argument( "--n-pool", type=int, default=16, help="Size of multiprocessing pool" ) parser.add_argument("file_in", help="input wav file") parser.add_argument("file_out", help="output wav file") parser.add_argument( "attack", type=int, default=1, help="transient shaper: 1 = attack, 0 = sustain" ) args = parser.parse_args() x, fs = soundfile.read(args.file_in) # stereo to mono if necessary if len(x.shape) > 1 and x.shape[1] == 2: x = x.sum(axis=1) / 2 # cast to float x = x.astype(numpy.single) # normalize between -1.0 and 1.0 x /= numpy.max(numpy.abs(x)) y = multiband_transient_shaper( x, fs, ( args.attack, args.fast_attack_ms, args.slow_attack_ms, args.release_ms, args.power_memory_ms, ), npool=args.n_pool, ) soundfile.write(args.file_out, y, fs) return 0 if __name__ == "__main__": sys.exit(main())
[ "soundfile.read", "numpy.abs", "argparse.ArgumentParser", "scipy.signal.lfilter", "numpy.zeros", "soundfile.write", "numpy.max", "numpy.exp", "multiprocessing.Pool", "scipy.signal.butter", "itertools.repeat" ]
[((611, 656), 'numpy.exp', 'numpy.exp', (['(-1.0 / (fs * fast_attack / 1000.0))'], {}), '(-1.0 / (fs * fast_attack / 1000.0))\n', (620, 656), False, 'import numpy\n'), ((670, 715), 'numpy.exp', 'numpy.exp', (['(-1.0 / (fs * slow_attack / 1000.0))'], {}), '(-1.0 / (fs * slow_attack / 1000.0))\n', (679, 715), False, 'import numpy\n'), ((732, 773), 'numpy.exp', 'numpy.exp', (['(-1.0 / (fs * release / 1000.0))'], {}), '(-1.0 / (fs * release / 1000.0))\n', (741, 773), False, 'import numpy\n'), ((788, 831), 'numpy.exp', 'numpy.exp', (['(-1.0 / (fs * power_mem / 1000.0))'], {}), '(-1.0 / (fs * power_mem / 1000.0))\n', (797, 831), False, 'import numpy\n'), ((917, 931), 'numpy.zeros', 'numpy.zeros', (['N'], {}), '(N)\n', (928, 931), False, 'import numpy\n'), ((952, 966), 'numpy.zeros', 'numpy.zeros', (['N'], {}), '(N)\n', (963, 966), False, 'import numpy\n'), ((991, 1005), 'numpy.zeros', 'numpy.zeros', (['N'], {}), '(N)\n', (1002, 1005), False, 'import numpy\n'), ((1021, 1035), 'numpy.zeros', 'numpy.zeros', (['N'], {}), '(N)\n', (1032, 1035), False, 'import numpy\n'), ((1056, 1070), 'numpy.zeros', 'numpy.zeros', (['N'], {}), '(N)\n', (1067, 1070), False, 'import numpy\n'), ((1978, 2006), 'numpy.max', 'numpy.max', (['attack_gain_curve'], {}), '(attack_gain_curve)\n', (1987, 2006), False, 'import numpy\n'), ((2379, 2428), 'scipy.signal.butter', 'butter', (['order', '[lo / nyq, hi / nyq]'], {'btype': '"""band"""'}), "(order, [lo / nyq, hi / nyq], btype='band')\n", (2385, 2428), False, 'from scipy.signal import butter, lfilter\n'), ((2437, 2453), 'scipy.signal.lfilter', 'lfilter', (['b', 'a', 'x'], {}), '(b, a, x)\n', (2444, 2453), False, 'from scipy.signal import butter, lfilter\n'), ((2800, 2827), 'multiprocessing.Pool', 'multiprocessing.Pool', (['npool'], {}), '(npool)\n', (2820, 2827), False, 'import multiprocessing\n'), ((3314, 3434), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'prog': '"""transient_shaper.py"""', 'description': '"""Multiband differential envelope transient shaper"""'}), "(prog='transient_shaper.py', description=\n 'Multiband differential envelope transient shaper')\n", (3337, 3434), False, 'import argparse\n'), ((4249, 4277), 'soundfile.read', 'soundfile.read', (['args.file_in'], {}), '(args.file_in)\n', (4263, 4277), False, 'import soundfile\n'), ((4784, 4821), 'soundfile.write', 'soundfile.write', (['args.file_out', 'y', 'fs'], {}), '(args.file_out, y, fs)\n', (4799, 4821), False, 'import soundfile\n'), ((4497, 4509), 'numpy.abs', 'numpy.abs', (['x'], {}), '(x)\n', (4506, 4509), False, 'import numpy\n'), ((3031, 3050), 'itertools.repeat', 'itertools.repeat', (['x'], {}), '(x)\n', (3047, 3050), False, 'import itertools\n'), ((3068, 3088), 'itertools.repeat', 'itertools.repeat', (['fs'], {}), '(fs)\n', (3084, 3088), False, 'import itertools\n'), ((3106, 3137), 'itertools.repeat', 'itertools.repeat', (['shaper_params'], {}), '(shaper_params)\n', (3122, 3137), False, 'import itertools\n')]
# -*- coding: utf-8 -*- """ Created on Fri Oct 1 18:51:33 2021 @author: kylei """ import numpy as np from keras import layers def unpackage_weights(model): model_weights = model.get_weights() ret_weights = np.empty((1,), float) for i in range(len(model_weights)): layer_weight = model_weights[i].ravel() ret_weights = np.append(ret_weights, layer_weight, axis=0) ret_weights = np.delete(ret_weights, 0, axis=0) return ret_weights def repackage_weights(unpack_weights, shape_list): matrix_weights = [] current_idx = 0 for i in shape_list: # Kind of sucks because non-linear acc = 1 # Accumulator for j in i: acc = acc * j selected_weights = unpack_weights[current_idx : (current_idx + acc)] selected_weights = np.array(selected_weights).reshape(i) matrix_weights.append(selected_weights) current_idx += acc return matrix_weights def get_layer_shapes(model): model_weights = model.get_weights() shapes = [] for i in range(len(model_weights)): layer_weight = model_weights[i] shapes.append(layer_weight.shape) return shapes def weight_dim_change_BIAS(packaged_weights, aux_genes, num_layers): """ NOTE: Not currently implemented. Not worth it to contain bias weights in main population """ # Accounts for only the trainable layers # the output and input are not considered layer_indices = np.arange(1, num_layers * 2, step=2) # Requires specified number of layers (since each layer will have units # and activation) shape_indices = np.arange(num_layers - 1, aux_genes.shape[0]) for i, j in zip(layer_indices, shape_indices): packaged_weights[i - 1] = packaged_weights[i - 1][:, : aux_genes[j]] packaged_weights[i] = packaged_weights[i][: aux_genes[j]] packaged_weights[i + 1] = packaged_weights[i + 1][: aux_genes[j], :] return packaged_weights # Packaged_weights passed by reference def weight_dim_change(packaged_weights, aux_genes, num_layers): # Which layers need to be modified from the packaged perspective layer_indices = np.arange(1, num_layers + 1) # Which genes need to be accessed # Need to access odd numbered genes for shapes gene_indices = np.arange(1, num_layers * 2, step=2) for layer, gene in zip(layer_indices, gene_indices): packaged_weights[layer - 1] = packaged_weights[layer - 1][:,:aux_genes[gene]] packaged_weights[layer] = packaged_weights[layer][:aux_genes[gene], :] return packaged_weights # Packaged_weights passed by reference def rebuild_model(model, shapes, funcs, structure, aux_genes): """ Parameters ---------- model : keras.Sequential An empty keras model. structure : list List of string values that describe the original model architecture. aux_genes : TYPE Genes that detail changes to model architecture. Returns ------- None. """ shape_counter = 1 act_counter = 0 for layer_idx in range(len(structure)): if structure[layer_idx] == "Dense": model.add( layers.Dense( aux_genes[shape_counter], activation=funcs[aux_genes[act_counter]], use_bias=False, kernel_initializer="normal", ) ) shape_counter += 2 # Oddly distributed in aux_population act_counter += 2 # Used for classification models elif structure[layer_idx] == "OutputC": model.add( layers.Dense(shapes[-1][-1], activation="softmax", use_bias=False) ) # Used for regressor models elif structure[layer_idx] == "OutputR": model.add(layers.Dense(shapes[-1][-1], activation="linear", use_bias=False)) elif structure[layer_idx] == "Input": model.add(layers.Input((shapes[0][0],))) else: ValueError(structure[layer_idx]) return None def rebuild_model_CNN(model, shapes, funcs, structure, aux_genes): """ Parameters ---------- model : keras.Sequential An empty keras model. structure : list List of string values that describe the original model architecture. aux_genes : TYPE Genes that detail changes to model architecture. Returns ------- None. """ for layer_idx in range(len(structure)): if structure[layer_idx] == "Conv": model.add( layers.Conv2D( aux_genes[0], (aux_genes[1], aux_genes[1]), activation=funcs[aux_genes[2]], use_bias=False, kernel_initializer="normal", ) ) elif structure[layer_idx] == "Pool": if aux_genes[3] == 1: # MaxPooling model.add( layers.MaxPooling2D( (aux_genes[4], aux_genes[4]), strides=(3,3) ) ) elif aux_genes[3] == 2: # AveragePooling model.add( layers.AveragePooling2D( (aux_genes[4], aux_genes[4]), strides=(3,3) ) ) else: ValueError("Invalid Pool") elif structure[layer_idx] == "Flatten": model.add(layers.Flatten()) elif structure[layer_idx] == "Dense": model.add( layers.Dense( aux_genes[6], activation=funcs[aux_genes[5]], use_bias=False ) ) # Used for classification models elif structure[layer_idx] == "OutputC": model.add( layers.Dense(shapes[-1][-1], activation="softmax", use_bias=False) ) elif structure[layer_idx] == "Input": model.add(layers.Input((28, 28, 1))) # Currently set up for MNIST dataset else: ValueError(structure[layer_idx]) return None
[ "numpy.empty", "keras.layers.MaxPooling2D", "keras.layers.Flatten", "numpy.append", "keras.layers.AveragePooling2D", "keras.layers.Dense", "numpy.array", "numpy.arange", "keras.layers.Conv2D", "keras.layers.Input", "numpy.delete" ]
[((219, 240), 'numpy.empty', 'np.empty', (['(1,)', 'float'], {}), '((1,), float)\n', (227, 240), True, 'import numpy as np\n'), ((416, 449), 'numpy.delete', 'np.delete', (['ret_weights', '(0)'], {'axis': '(0)'}), '(ret_weights, 0, axis=0)\n', (425, 449), True, 'import numpy as np\n'), ((1495, 1531), 'numpy.arange', 'np.arange', (['(1)', '(num_layers * 2)'], {'step': '(2)'}), '(1, num_layers * 2, step=2)\n', (1504, 1531), True, 'import numpy as np\n'), ((1651, 1696), 'numpy.arange', 'np.arange', (['(num_layers - 1)', 'aux_genes.shape[0]'], {}), '(num_layers - 1, aux_genes.shape[0])\n', (1660, 1696), True, 'import numpy as np\n'), ((2193, 2221), 'numpy.arange', 'np.arange', (['(1)', '(num_layers + 1)'], {}), '(1, num_layers + 1)\n', (2202, 2221), True, 'import numpy as np\n'), ((2331, 2367), 'numpy.arange', 'np.arange', (['(1)', '(num_layers * 2)'], {'step': '(2)'}), '(1, num_layers * 2, step=2)\n', (2340, 2367), True, 'import numpy as np\n'), ((352, 396), 'numpy.append', 'np.append', (['ret_weights', 'layer_weight'], {'axis': '(0)'}), '(ret_weights, layer_weight, axis=0)\n', (361, 396), True, 'import numpy as np\n'), ((815, 841), 'numpy.array', 'np.array', (['selected_weights'], {}), '(selected_weights)\n', (823, 841), True, 'import numpy as np\n'), ((3219, 3349), 'keras.layers.Dense', 'layers.Dense', (['aux_genes[shape_counter]'], {'activation': 'funcs[aux_genes[act_counter]]', 'use_bias': '(False)', 'kernel_initializer': '"""normal"""'}), "(aux_genes[shape_counter], activation=funcs[aux_genes[\n act_counter]], use_bias=False, kernel_initializer='normal')\n", (3231, 3349), False, 'from keras import layers\n'), ((4716, 4855), 'keras.layers.Conv2D', 'layers.Conv2D', (['aux_genes[0]', '(aux_genes[1], aux_genes[1])'], {'activation': 'funcs[aux_genes[2]]', 'use_bias': '(False)', 'kernel_initializer': '"""normal"""'}), "(aux_genes[0], (aux_genes[1], aux_genes[1]), activation=funcs[\n aux_genes[2]], use_bias=False, kernel_initializer='normal')\n", (4729, 4855), False, 'from keras import layers\n'), ((3686, 3752), 'keras.layers.Dense', 'layers.Dense', (['shapes[-1][-1]'], {'activation': '"""softmax"""', 'use_bias': '(False)'}), "(shapes[-1][-1], activation='softmax', use_bias=False)\n", (3698, 3752), False, 'from keras import layers\n'), ((3873, 3938), 'keras.layers.Dense', 'layers.Dense', (['shapes[-1][-1]'], {'activation': '"""linear"""', 'use_bias': '(False)'}), "(shapes[-1][-1], activation='linear', use_bias=False)\n", (3885, 3938), False, 'from keras import layers\n'), ((5168, 5233), 'keras.layers.MaxPooling2D', 'layers.MaxPooling2D', (['(aux_genes[4], aux_genes[4])'], {'strides': '(3, 3)'}), '((aux_genes[4], aux_genes[4]), strides=(3, 3))\n', (5187, 5233), False, 'from keras import layers\n'), ((5771, 5787), 'keras.layers.Flatten', 'layers.Flatten', ([], {}), '()\n', (5785, 5787), False, 'from keras import layers\n'), ((4021, 4050), 'keras.layers.Input', 'layers.Input', (['(shapes[0][0],)'], {}), '((shapes[0][0],))\n', (4033, 4050), False, 'from keras import layers\n'), ((5450, 5519), 'keras.layers.AveragePooling2D', 'layers.AveragePooling2D', (['(aux_genes[4], aux_genes[4])'], {'strides': '(3, 3)'}), '((aux_genes[4], aux_genes[4]), strides=(3, 3))\n', (5473, 5519), False, 'from keras import layers\n'), ((5887, 5961), 'keras.layers.Dense', 'layers.Dense', (['aux_genes[6]'], {'activation': 'funcs[aux_genes[5]]', 'use_bias': '(False)'}), '(aux_genes[6], activation=funcs[aux_genes[5]], use_bias=False)\n', (5899, 5961), False, 'from keras import layers\n'), ((6171, 6237), 'keras.layers.Dense', 'layers.Dense', (['shapes[-1][-1]'], {'activation': '"""softmax"""', 'use_bias': '(False)'}), "(shapes[-1][-1], activation='softmax', use_bias=False)\n", (6183, 6237), False, 'from keras import layers\n'), ((6332, 6357), 'keras.layers.Input', 'layers.Input', (['(28, 28, 1)'], {}), '((28, 28, 1))\n', (6344, 6357), False, 'from keras import layers\n')]
import os import sys import argparse import subprocess import torch import numpy as np import time import gym import pybullet import pybullet_envs import matplotlib.pyplot as plt from mpi4py import MPI comm = MPI.COMM_WORLD #from bevodevo.policies.rnns import GatedRNNPolicy from bevodevo.policies.cnns import ImpalaCNNPolicy from bevodevo.policies.mlps import MLPPolicy, CPPNMLPPolicy, CPPNHebbianMLP,\ HebbianMLP, ABCHebbianMLP, HebbianMetaMLP, ABCHebbianMetaMLP from bevodevo.algos.es import ESPopulation from bevodevo.algos.cmaes import CMAESPopulation from bevodevo.algos.pges import PGESPopulation from bevodevo.algos.ga import GeneticPopulation from bevodevo.algos.random_search import RandomSearch #from bevodevo.algos.dqn import DQN def enjoy(argv): # env_name, generations, population_size, if "elite_pop" not in argv.file_path and ".pt" not in argv.file_path: my_dir = os.listdir(argv.file_path) latest_gen = 0 my_file_path = "" for filename in my_dir: if "elite_pop" in filename: current_gen = int(filename.split("_")[5]) if latest_gen < current_gen: latest_gen = current_gen my_file_path = argv.file_path + filename else: my_file_path = argv.file_path print(my_file_path) if "gatedrnn" in argv.policy.lower(): policy_fn = GatedRNNPolicy argv.policy = "GatedRNNPolicy" elif "impala" in argv.policy.lower(): policy_fn = ImpalaCNNPolicy argv.policy = "ImpalaCNNPolicy" elif "cppnmlp" in argv.policy.lower(): policy_fn = CPPNMLPPolicy arg.policy = "CPPNMLPPolicy" elif "abchebbianmlp" in argv.policy.lower(): policy_fn = ABCHebbianMLP argv.policy = "ABCHebbianMLP" elif "abchebbianmetamlp" in argv.policy.lower(): policy_fn = ABCHebbianMetaMLP argv.policy = "ABCHebbianMetaMLP" elif "cppnhebbianmlp" in argv.policy.lower(): policy_fn = CPPNHebbianMLP argv.policy = "CPPNHebbianMLP" elif "hebbianmlp" in argv.policy.lower(): policy_fn = HebbianMLP argv.policy = "HebbianMLP" elif "hebbianmetamlp" in argv.policy.lower(): policy_fn = HebbianMetaMLP argv.policy = "HebbianMetaMLP" elif "mlppolicy" in argv.policy.lower(): policy_fn = MLPPolicy argv.policy = "MLPPolicy" else: assert False, "policy not found, check spelling?" if ".npy" in my_file_path: my_data = np.load(my_file_path, allow_pickle=True)[np.newaxis][0] env_name = my_data["env_name"] else: env_name = argv.env_name env = gym.make(env_name) if argv.no_render: gym_render = False else: if "BulletEnv" in env_name: env.render() gym_render = False else: gym_render = True obs_dim = env.observation_space.shape if len(obs_dim) == 3: obs_dim = obs_dim else: obs_dim = obs_dim[0] hid_dim = 16 #[32,32] try: act_dim = env.action_space.n discrete = True except: act_dim = env.action_space.sample().shape[0] discrete = False no_array = act_dim == 2 and discrete if ".npy" in my_file_path: parameters = np.load(my_file_path, allow_pickle=True)[np.newaxis][0] else: parameters = torch.load(my_file_path) if type(parameters) is dict: elite_keep = len(parameters) else: elite_keep = 1 for agent_idx in range(min([argv.num_agents, elite_keep])): if type(parameters) is dict: agent_args = {"dim_x": obs_dim, "dim_h": hid_dim, \ "dim_y": act_dim, "params": parameters["elite_0"]} my_params = agent_args["params"] agent_args["params"] = None else: agent_args = {"dim_x": obs_dim, "dim_h": hid_dim, \ "dim_y": act_dim, "params": parameters} my_params = agent_args["params"] agent_args["params"] = None if ".pt" in my_file_path: agent_args["params"] = None agent = policy_fn(agent_args, discrete=discrete) if ".pt" in my_file_path: agent.load_state_dict(parameters) agent_args["params"] = agent.get_params() else: agent.set_params(my_params) epd_rewards = [] for episode in range(argv.episodes): obs = env.reset() sum_reward = 0.0 done = False step_count = 0 while not done: action = agent.get_action(obs) if no_array and type(action) == np.ndarray\ or len(action.shape) > 1: action = action[0] obs, reward, done, info = env.step(action) step_count += 1 sum_reward += reward if gym_render: env.render() time.sleep(1e-2) if argv.save_frames: if "BulletEnv" in argv.env_name: env.unwrapped._render_width = 640 env.unwrapped._render_height = 480 img = env.render(mode="rgb_array") plt.figure() plt.imshow(img) plt.savefig("./frames/frame_agent{}_pd{}_step{}.png".format(\ agent_idx, episode, step_count)) plt.close() time.sleep(0.01) if step_count >= argv.max_steps: done = True epd_rewards.append(sum_reward) print("reward stats for elite {} over {} epds:".format(agent_idx, argv.episodes)) print("mean rew: {:.3e}, +/- {:.3e} std. dev.".format(np.mean(epd_rewards), np.std(epd_rewards))) print("max rew: {:.3e}, min rew: {:.3e}".format(np.max(epd_rewards), np.min(epd_rewards))) env.close() if __name__ == "__main__": parser = argparse.ArgumentParser("Experiment parameters") parser.add_argument("-n", "--env_name", type=str, \ help="name of environemt", default="InvertedPendulumBulletEnv-v0") parser.add_argument("-pi", "--policy", type=str,\ help="name of policy architecture", default="MLPPolicy") parser.add_argument("-e", "--episodes", type=int,\ help="number of episodes", default=5) parser.add_argument("-s", "--save_frames", type=bool, \ help="save frames or not", default=False) parser.add_argument("-nr", "--no_render", type=bool,\ help="don't render", default=False) parser.add_argument("-ms", "--max_steps", type=int,\ help="maximum number of steps per episode", default=4000) parser.add_argument("-f", "--file_path", type=str,\ help="file path to model parameters", \ default="./results/test_exp/") parser.add_argument("-a", "--num_agents", type=int,\ help="how many agents to evaluate", \ default=1) args = parser.parse_args() enjoy(args)
[ "numpy.load", "gym.make", "argparse.ArgumentParser", "numpy.std", "matplotlib.pyplot.imshow", "torch.load", "matplotlib.pyplot.close", "time.sleep", "numpy.max", "numpy.mean", "numpy.min", "matplotlib.pyplot.figure", "os.listdir" ]
[((2694, 2712), 'gym.make', 'gym.make', (['env_name'], {}), '(env_name)\n', (2702, 2712), False, 'import gym\n'), ((6118, 6166), 'argparse.ArgumentParser', 'argparse.ArgumentParser', (['"""Experiment parameters"""'], {}), "('Experiment parameters')\n", (6141, 6166), False, 'import argparse\n'), ((921, 947), 'os.listdir', 'os.listdir', (['argv.file_path'], {}), '(argv.file_path)\n', (931, 947), False, 'import os\n'), ((3417, 3441), 'torch.load', 'torch.load', (['my_file_path'], {}), '(my_file_path)\n', (3427, 3441), False, 'import torch\n'), ((2545, 2585), 'numpy.load', 'np.load', (['my_file_path'], {'allow_pickle': '(True)'}), '(my_file_path, allow_pickle=True)\n', (2552, 2585), True, 'import numpy as np\n'), ((3330, 3370), 'numpy.load', 'np.load', (['my_file_path'], {'allow_pickle': '(True)'}), '(my_file_path, allow_pickle=True)\n', (3337, 3370), True, 'import numpy as np\n'), ((5612, 5628), 'time.sleep', 'time.sleep', (['(0.01)'], {}), '(0.01)\n', (5622, 5628), False, 'import time\n'), ((5908, 5928), 'numpy.mean', 'np.mean', (['epd_rewards'], {}), '(epd_rewards)\n', (5915, 5928), True, 'import numpy as np\n'), ((5930, 5949), 'numpy.std', 'np.std', (['epd_rewards'], {}), '(epd_rewards)\n', (5936, 5949), True, 'import numpy as np\n'), ((6008, 6027), 'numpy.max', 'np.max', (['epd_rewards'], {}), '(epd_rewards)\n', (6014, 6027), True, 'import numpy as np\n'), ((6029, 6048), 'numpy.min', 'np.min', (['epd_rewards'], {}), '(epd_rewards)\n', (6035, 6048), True, 'import numpy as np\n'), ((5050, 5066), 'time.sleep', 'time.sleep', (['(0.01)'], {}), '(0.01)\n', (5060, 5066), False, 'import time\n'), ((5371, 5383), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (5381, 5383), True, 'import matplotlib.pyplot as plt\n'), ((5404, 5419), 'matplotlib.pyplot.imshow', 'plt.imshow', (['img'], {}), '(img)\n', (5414, 5419), True, 'import matplotlib.pyplot as plt\n'), ((5583, 5594), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (5592, 5594), True, 'import matplotlib.pyplot as plt\n')]
import json import os import pickle import random import time from pathlib import Path import cv2 import numpy as np from PIL import Image from torch import autograd from yolo import dataset, model, utils COLOR_PALETTE = utils.get_palette(Path(os.path.abspath(__file__)).parents[1] / 'resource' / 'palette') def data_iter(img_dirname): """ iter img_file in directory img_dirname :param img_dirname: :return: """ img_dir = Path(img_dirname) if not img_dir.exists(): raise ValueError(f'{img_dirname} not exist!') if img_dir.is_file(): yield img_dir else: for filename in img_dir.iter(): yield filename def load_classes(filename): """ :param filename: :return: """ with open(filename, 'r', encoding='utf8') as fr: for line in fr.readlines(): s = line.strip() if s: yield s def draw_box(img, bbox, color=None): """ :param img: :param bbox: :param color: :return: """ bbox = bbox.astype(np.int32) pt_0 = (bbox[0], bbox[2]) pt_1 = (bbox[1], bbox[3]) if color is None: c_ind = random.randint(0, len(COLOR_PALETTE)) color = COLOR_PALETTE[c_ind % len(COLOR_PALETTE)] if np.issubdtype(img.dtype, np.floating): color = (color[0] / 255., color[1] / 255., color[2] / 255.) cv2.rectangle(img, pt_0, pt_1, color, 2) def draw_single_prediction(image, prediction, out_filename, input_shape=None): """ :param image: :param prediction: :param out_filename: :param input_shape: :return: """ img = np.ascontiguousarray(image, dtype=np.uint8) original_size = img.shape[:2] for record in prediction: bbox = record[:4] if (bbox[1] - bbox[0] > 0) and (bbox[3] - bbox[2] > 0): if input_shape is not None: bbox = bbox.copy() new_bbox = dataset.resize_bbox(bbox, input_shape, original_size, is_train=False) draw_box(img, new_bbox) else: draw_box(img, bbox) pil_img= Image.fromarray(img) pil_img.save(os.fspath(out_filename)) # cv2.imwrite(os.fspath(out_filename), img[:, :, ::-1]) def get_detect_result(prediction, original_size, input_shape=None): """ :param prediction: :param original_size: :param input_shape: :return: """ for record in prediction: bbox = record[:4] label = int(record[-1]) object_conf = record[4] class_prob = record[5] if (bbox[1] - bbox[0] > 0) and (bbox[3] - bbox[2] > 0): if input_shape is not None: bbox = bbox.copy() new_bbox = dataset.resize_bbox(bbox, input_shape, original_size, is_train=False) yield new_bbox, label, object_conf, class_prob else: yield bbox, label, object_conf, class_prob def get_detection_json(prediction, original_size, name_tuple, input_shape=None): """ :param prediction: :param original_size: :param name_tuple: :param input_shape: :return: """ res = [] for box, label_ind, object_conf, class_prob in get_detect_result(prediction, original_size, input_shape=input_shape): topleft = {'x': int(box[0]), 'y': int(box[2])} bottomright = {'x': int(box[1]), 'y': int(box[3])} data = {'label': name_tuple[label_ind], 'confidence': round(object_conf), 'topleft': topleft, 'bottomright': bottomright} res.append(data) return res def detection(img_filename, config_path, out_dirname): """ :param img_filename: :param config_path: :param out_dirname :return: """ config = utils.parse_config(config_path) max_object_num = config.max_objects confidence_thresh = config.confidence_thresh iou_thresh = config.iou_thresh kwargs = {"confidence_thresh": confidence_thresh, "iou_thresh": iou_thresh} with open(config.anchor_path, 'rb') as fr: train_anchors = pickle.load(fr) cfg_filename = config.net_config weight_file = config.net_weight class_names = config.class_names start_time = time.time() net = model.load_model(cfg_filename, weight_file, anchors=train_anchors, class_names=class_names, use_cuda=True, **kwargs) net.eval() model_load_time = time.time() - start_time predict_start_time = time.time() original_img = dataset.image_loader(img_filename) input_size = (config.image_shape, config.image_shape) img, _ = dataset.transform_image(original_img, input_size=input_size, new_axis=True, augmentation=False) if net.use_cuda: img = img.cuda() with autograd.no_grad(): prediction = net(img) name = Path(img_filename).stem base_dir = Path(out_dirname) out_img = base_dir / (name + '_res.jpg') out_json = base_dir / (name + '_res.json') _, name_tuple = utils.parse_class_names(class_names) original_size = original_img.shape[:2] prediction_result = utils.transform_prediction(prediction, confidence_thresh, iou_thresh, max_object_num) res_dct = get_detection_json(prediction_result[0], original_size, name_tuple, input_size) with open(out_json, 'w', encoding='utf8') as fr: json.dump(res_dct, fr, ensure_ascii=False) draw_single_prediction(original_img, prediction_result[0], out_img, input_shape=input_size) print(f'total_time: {time.time() - start_time},' f' model_load_time = {model_load_time}, ' f'infer_time = {time.time() - predict_start_time}') if __name__ == '__main__': config_path = '../config/config.json' dirname = Path('C:/data/户型识别测试图片') img_name ='1311795183-3-2-御景观澜3室2厅1卫-big.jpg' img_filename = dirname / img_name detection(img_filename, config_path, '../img')
[ "json.dump", "os.path.abspath", "yolo.utils.transform_prediction", "yolo.model.load_model", "yolo.dataset.image_loader", "yolo.dataset.transform_image", "time.time", "yolo.dataset.resize_bbox", "pathlib.Path", "os.fspath", "pickle.load", "yolo.utils.parse_class_names", "cv2.rectangle", "PI...
[((451, 468), 'pathlib.Path', 'Path', (['img_dirname'], {}), '(img_dirname)\n', (455, 468), False, 'from pathlib import Path\n'), ((1391, 1431), 'cv2.rectangle', 'cv2.rectangle', (['img', 'pt_0', 'pt_1', 'color', '(2)'], {}), '(img, pt_0, pt_1, color, 2)\n', (1404, 1431), False, 'import cv2\n'), ((1643, 1686), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['image'], {'dtype': 'np.uint8'}), '(image, dtype=np.uint8)\n', (1663, 1686), True, 'import numpy as np\n'), ((2120, 2140), 'PIL.Image.fromarray', 'Image.fromarray', (['img'], {}), '(img)\n', (2135, 2140), False, 'from PIL import Image\n'), ((3862, 3893), 'yolo.utils.parse_config', 'utils.parse_config', (['config_path'], {}), '(config_path)\n', (3880, 3893), False, 'from yolo import dataset, model, utils\n'), ((4329, 4340), 'time.time', 'time.time', ([], {}), '()\n', (4338, 4340), False, 'import time\n'), ((4351, 4471), 'yolo.model.load_model', 'model.load_model', (['cfg_filename', 'weight_file'], {'anchors': 'train_anchors', 'class_names': 'class_names', 'use_cuda': '(True)'}), '(cfg_filename, weight_file, anchors=train_anchors,\n class_names=class_names, use_cuda=True, **kwargs)\n', (4367, 4471), False, 'from yolo import dataset, model, utils\n'), ((4583, 4594), 'time.time', 'time.time', ([], {}), '()\n', (4592, 4594), False, 'import time\n'), ((4614, 4648), 'yolo.dataset.image_loader', 'dataset.image_loader', (['img_filename'], {}), '(img_filename)\n', (4634, 4648), False, 'from yolo import dataset, model, utils\n'), ((4720, 4819), 'yolo.dataset.transform_image', 'dataset.transform_image', (['original_img'], {'input_size': 'input_size', 'new_axis': '(True)', 'augmentation': '(False)'}), '(original_img, input_size=input_size, new_axis=True,\n augmentation=False)\n', (4743, 4819), False, 'from yolo import dataset, model, utils\n'), ((4973, 4990), 'pathlib.Path', 'Path', (['out_dirname'], {}), '(out_dirname)\n', (4977, 4990), False, 'from pathlib import Path\n'), ((5103, 5139), 'yolo.utils.parse_class_names', 'utils.parse_class_names', (['class_names'], {}), '(class_names)\n', (5126, 5139), False, 'from yolo import dataset, model, utils\n'), ((5207, 5296), 'yolo.utils.transform_prediction', 'utils.transform_prediction', (['prediction', 'confidence_thresh', 'iou_thresh', 'max_object_num'], {}), '(prediction, confidence_thresh, iou_thresh,\n max_object_num)\n', (5233, 5296), False, 'from yolo import dataset, model, utils\n'), ((5840, 5864), 'pathlib.Path', 'Path', (['"""C:/data/户型识别测试图片"""'], {}), "('C:/data/户型识别测试图片')\n", (5844, 5864), False, 'from pathlib import Path\n'), ((1276, 1313), 'numpy.issubdtype', 'np.issubdtype', (['img.dtype', 'np.floating'], {}), '(img.dtype, np.floating)\n', (1289, 1313), True, 'import numpy as np\n'), ((2158, 2181), 'os.fspath', 'os.fspath', (['out_filename'], {}), '(out_filename)\n', (2167, 2181), False, 'import os\n'), ((4184, 4199), 'pickle.load', 'pickle.load', (['fr'], {}), '(fr)\n', (4195, 4199), False, 'import pickle\n'), ((4533, 4544), 'time.time', 'time.time', ([], {}), '()\n', (4542, 4544), False, 'import time\n'), ((4872, 4890), 'torch.autograd.no_grad', 'autograd.no_grad', ([], {}), '()\n', (4888, 4890), False, 'from torch import autograd\n'), ((4934, 4952), 'pathlib.Path', 'Path', (['img_filename'], {}), '(img_filename)\n', (4938, 4952), False, 'from pathlib import Path\n'), ((5449, 5491), 'json.dump', 'json.dump', (['res_dct', 'fr'], {'ensure_ascii': '(False)'}), '(res_dct, fr, ensure_ascii=False)\n', (5458, 5491), False, 'import json\n'), ((1943, 2012), 'yolo.dataset.resize_bbox', 'dataset.resize_bbox', (['bbox', 'input_shape', 'original_size'], {'is_train': '(False)'}), '(bbox, input_shape, original_size, is_train=False)\n', (1962, 2012), False, 'from yolo import dataset, model, utils\n'), ((2733, 2802), 'yolo.dataset.resize_bbox', 'dataset.resize_bbox', (['bbox', 'input_shape', 'original_size'], {'is_train': '(False)'}), '(bbox, input_shape, original_size, is_train=False)\n', (2752, 2802), False, 'from yolo import dataset, model, utils\n'), ((5613, 5624), 'time.time', 'time.time', ([], {}), '()\n', (5622, 5624), False, 'import time\n'), ((5719, 5730), 'time.time', 'time.time', ([], {}), '()\n', (5728, 5730), False, 'import time\n'), ((247, 272), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (262, 272), False, 'import os\n')]
import numpy as np import pylab as pl import scipy.signal as signal fs = 1000 f1 = 45 f2 = 55 scale = 2**12 b = signal.firwin(999,[f1/fs*2,f2/fs*2]) b = b*scale b = b.astype(int) np.savetxt("coeff12bit.dat",b)
[ "scipy.signal.firwin", "numpy.savetxt" ]
[((114, 160), 'scipy.signal.firwin', 'signal.firwin', (['(999)', '[f1 / fs * 2, f2 / fs * 2]'], {}), '(999, [f1 / fs * 2, f2 / fs * 2])\n', (127, 160), True, 'import scipy.signal as signal\n'), ((181, 212), 'numpy.savetxt', 'np.savetxt', (['"""coeff12bit.dat"""', 'b'], {}), "('coeff12bit.dat', b)\n", (191, 212), True, 'import numpy as np\n')]
import json import torch import numpy as np import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from net_utils import run_lstm, col_name_encode class OpPredictor(nn.Module): def __init__(self, N_word, N_h, N_depth, gpu, use_hs): super(OpPredictor, self).__init__() self.N_h = N_h self.gpu = gpu self.use_hs = use_hs self.q_lstm = nn.LSTM(input_size=N_word, hidden_size=N_h/2, num_layers=N_depth, batch_first=True, dropout=0.3, bidirectional=True) self.hs_lstm = nn.LSTM(input_size=N_word, hidden_size=N_h/2, num_layers=N_depth, batch_first=True, dropout=0.3, bidirectional=True) self.col_lstm = nn.LSTM(input_size=N_word, hidden_size=N_h/2, num_layers=N_depth, batch_first=True, dropout=0.3, bidirectional=True) self.q_num_att = nn.Linear(N_h, N_h) self.hs_num_att = nn.Linear(N_h, N_h) self.op_num_out_q = nn.Linear(N_h, N_h) self.op_num_out_hs = nn.Linear(N_h, N_h) self.op_num_out_c = nn.Linear(N_h, N_h) self.op_num_out = nn.Sequential(nn.Tanh(), nn.Linear(N_h, 2)) #for 1-2 op num, could be changed self.q_att = nn.Linear(N_h, N_h) self.hs_att = nn.Linear(N_h, N_h) self.op_out_q = nn.Linear(N_h, N_h) self.op_out_hs = nn.Linear(N_h, N_h) self.op_out_c = nn.Linear(N_h, N_h) self.op_out = nn.Sequential(nn.Tanh(), nn.Linear(N_h, 11)) #for 11 operators self.softmax = nn.Softmax() #dim=1 self.CE = nn.CrossEntropyLoss() self.log_softmax = nn.LogSoftmax() self.mlsml = nn.MultiLabelSoftMarginLoss() self.bce_logit = nn.BCEWithLogitsLoss() self.sigm = nn.Sigmoid() if gpu: self.cuda() def forward(self, q_emb_var, q_len, hs_emb_var, hs_len, col_emb_var, col_len, col_name_len, gt_col): max_q_len = max(q_len) max_hs_len = max(hs_len) max_col_len = max(col_len) B = len(q_len) q_enc, _ = run_lstm(self.q_lstm, q_emb_var, q_len) hs_enc, _ = run_lstm(self.hs_lstm, hs_emb_var, hs_len) col_enc, _ = col_name_encode(col_emb_var, col_name_len, col_len, self.col_lstm) # get target/predicted column's embedding # col_emb: (B, hid_dim) col_emb = [] for b in range(B): col_emb.append(col_enc[b, gt_col[b]]) col_emb = torch.stack(col_emb) # Predict op number att_val_qc_num = torch.bmm(col_emb.unsqueeze(1), self.q_num_att(q_enc).transpose(1, 2)).view(B,-1) for idx, num in enumerate(q_len): if num < max_q_len: att_val_qc_num[idx, num:] = -100 att_prob_qc_num = self.softmax(att_val_qc_num) q_weighted_num = (q_enc * att_prob_qc_num.unsqueeze(2)).sum(1) # Same as the above, compute SQL history embedding weighted by column attentions att_val_hc_num = torch.bmm(col_emb.unsqueeze(1), self.hs_num_att(hs_enc).transpose(1, 2)).view(B,-1) for idx, num in enumerate(hs_len): if num < max_hs_len: att_val_hc_num[idx, num:] = -100 att_prob_hc_num = self.softmax(att_val_hc_num) hs_weighted_num = (hs_enc * att_prob_hc_num.unsqueeze(2)).sum(1) # op_num_score: (B, 2) op_num_score = self.op_num_out(self.op_num_out_q(q_weighted_num) + int(self.use_hs)* self.op_num_out_hs(hs_weighted_num) + self.op_num_out_c(col_emb)) # Compute attention values between selected column and question tokens. # q_enc.transpose(1, 2): (B, hid_dim, max_q_len) # col_emb.unsqueeze(1): (B, 1, hid_dim) # att_val_qc: (B, max_q_len) # print("col_emb {} q_enc {}".format(col_emb.unsqueeze(1).size(),self.q_att(q_enc).transpose(1, 2).size())) att_val_qc = torch.bmm(col_emb.unsqueeze(1), self.q_att(q_enc).transpose(1, 2)).view(B,-1) # assign appended positions values -100 for idx, num in enumerate(q_len): if num < max_q_len: att_val_qc[idx, num:] = -100 # att_prob_qc: (B, max_q_len) att_prob_qc = self.softmax(att_val_qc) # q_enc: (B, max_q_len, hid_dim) # att_prob_qc.unsqueeze(2): (B, max_q_len, 1) # q_weighted: (B, hid_dim) q_weighted = (q_enc * att_prob_qc.unsqueeze(2)).sum(1) # Same as the above, compute SQL history embedding weighted by column attentions att_val_hc = torch.bmm(col_emb.unsqueeze(1), self.hs_att(hs_enc).transpose(1, 2)).view(B,-1) for idx, num in enumerate(hs_len): if num < max_hs_len: att_val_hc[idx, num:] = -100 att_prob_hc = self.softmax(att_val_hc) hs_weighted = (hs_enc * att_prob_hc.unsqueeze(2)).sum(1) # Compute prediction scores # op_score: (B, 10) op_score = self.op_out(self.op_out_q(q_weighted) + int(self.use_hs)* self.op_out_hs(hs_weighted) + self.op_out_c(col_emb)) score = (op_num_score, op_score) return score def loss(self, score, truth): loss = 0 B = len(truth) op_num_score, op_score = score truth = [t if len(t) <= 2 else t[:2] for t in truth] # loss for the op number truth_num = [len(t)-1 for t in truth] #num_score 0 maps to 1 in truth data = torch.from_numpy(np.array(truth_num)) truth_num_var = Variable(data.cuda()) loss += self.CE(op_num_score, truth_num_var) # loss for op T = len(op_score[0]) truth_prob = np.zeros((B, T), dtype=np.float32) for b in range(B): truth_prob[b][truth[b]] = 1 data = torch.from_numpy(np.array(truth_prob)) truth_var = Variable(data.cuda()) #loss += self.mlsml(op_score, truth_var) #loss += self.bce_logit(op_score, truth_var) pred_prob = self.sigm(op_score) bce_loss = -torch.mean( 3*(truth_var * \ torch.log(pred_prob+1e-10)) + \ (1-truth_var) * torch.log(1-pred_prob+1e-10) ) loss += bce_loss return loss def check_acc(self, score, truth): num_err, err, tot_err = 0, 0, 0 B = len(truth) pred = [] op_num_score, op_score = [x.data.cpu().numpy() for x in score] for b in range(B): cur_pred = {} op_num = np.argmax(op_num_score[b]) + 1 #num_score 0 maps to 1 in truth, must have at least one op cur_pred['op_num'] = op_num cur_pred['op'] = np.argsort(-op_score[b])[:op_num] pred.append(cur_pred) for b, (p, t) in enumerate(zip(pred, truth)): op_num, op = p['op_num'], p['op'] flag = True if op_num != len(t): num_err += 1 flag = False if flag and set(op) != set(t): err += 1 flag = False if not flag: tot_err += 1 return np.array((num_err, err, tot_err))
[ "torch.nn.BCEWithLogitsLoss", "torch.stack", "numpy.argmax", "torch.nn.LogSoftmax", "torch.nn.Tanh", "torch.nn.CrossEntropyLoss", "net_utils.run_lstm", "numpy.zeros", "torch.nn.MultiLabelSoftMarginLoss", "numpy.argsort", "net_utils.col_name_encode", "torch.nn.Softmax", "numpy.array", "torc...
[((415, 537), 'torch.nn.LSTM', 'nn.LSTM', ([], {'input_size': 'N_word', 'hidden_size': '(N_h / 2)', 'num_layers': 'N_depth', 'batch_first': '(True)', 'dropout': '(0.3)', 'bidirectional': '(True)'}), '(input_size=N_word, hidden_size=N_h / 2, num_layers=N_depth,\n batch_first=True, dropout=0.3, bidirectional=True)\n', (422, 537), True, 'import torch.nn as nn\n'), ((588, 710), 'torch.nn.LSTM', 'nn.LSTM', ([], {'input_size': 'N_word', 'hidden_size': '(N_h / 2)', 'num_layers': 'N_depth', 'batch_first': '(True)', 'dropout': '(0.3)', 'bidirectional': '(True)'}), '(input_size=N_word, hidden_size=N_h / 2, num_layers=N_depth,\n batch_first=True, dropout=0.3, bidirectional=True)\n', (595, 710), True, 'import torch.nn as nn\n'), ((762, 884), 'torch.nn.LSTM', 'nn.LSTM', ([], {'input_size': 'N_word', 'hidden_size': '(N_h / 2)', 'num_layers': 'N_depth', 'batch_first': '(True)', 'dropout': '(0.3)', 'bidirectional': '(True)'}), '(input_size=N_word, hidden_size=N_h / 2, num_layers=N_depth,\n batch_first=True, dropout=0.3, bidirectional=True)\n', (769, 884), True, 'import torch.nn as nn\n'), ((937, 956), 'torch.nn.Linear', 'nn.Linear', (['N_h', 'N_h'], {}), '(N_h, N_h)\n', (946, 956), True, 'import torch.nn as nn\n'), ((983, 1002), 'torch.nn.Linear', 'nn.Linear', (['N_h', 'N_h'], {}), '(N_h, N_h)\n', (992, 1002), True, 'import torch.nn as nn\n'), ((1031, 1050), 'torch.nn.Linear', 'nn.Linear', (['N_h', 'N_h'], {}), '(N_h, N_h)\n', (1040, 1050), True, 'import torch.nn as nn\n'), ((1080, 1099), 'torch.nn.Linear', 'nn.Linear', (['N_h', 'N_h'], {}), '(N_h, N_h)\n', (1089, 1099), True, 'import torch.nn as nn\n'), ((1128, 1147), 'torch.nn.Linear', 'nn.Linear', (['N_h', 'N_h'], {}), '(N_h, N_h)\n', (1137, 1147), True, 'import torch.nn as nn\n'), ((1274, 1293), 'torch.nn.Linear', 'nn.Linear', (['N_h', 'N_h'], {}), '(N_h, N_h)\n', (1283, 1293), True, 'import torch.nn as nn\n'), ((1316, 1335), 'torch.nn.Linear', 'nn.Linear', (['N_h', 'N_h'], {}), '(N_h, N_h)\n', (1325, 1335), True, 'import torch.nn as nn\n'), ((1360, 1379), 'torch.nn.Linear', 'nn.Linear', (['N_h', 'N_h'], {}), '(N_h, N_h)\n', (1369, 1379), True, 'import torch.nn as nn\n'), ((1405, 1424), 'torch.nn.Linear', 'nn.Linear', (['N_h', 'N_h'], {}), '(N_h, N_h)\n', (1414, 1424), True, 'import torch.nn as nn\n'), ((1449, 1468), 'torch.nn.Linear', 'nn.Linear', (['N_h', 'N_h'], {}), '(N_h, N_h)\n', (1458, 1468), True, 'import torch.nn as nn\n'), ((1578, 1590), 'torch.nn.Softmax', 'nn.Softmax', ([], {}), '()\n', (1588, 1590), True, 'import torch.nn as nn\n'), ((1616, 1637), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {}), '()\n', (1635, 1637), True, 'import torch.nn as nn\n'), ((1665, 1680), 'torch.nn.LogSoftmax', 'nn.LogSoftmax', ([], {}), '()\n', (1678, 1680), True, 'import torch.nn as nn\n'), ((1702, 1731), 'torch.nn.MultiLabelSoftMarginLoss', 'nn.MultiLabelSoftMarginLoss', ([], {}), '()\n', (1729, 1731), True, 'import torch.nn as nn\n'), ((1757, 1779), 'torch.nn.BCEWithLogitsLoss', 'nn.BCEWithLogitsLoss', ([], {}), '()\n', (1777, 1779), True, 'import torch.nn as nn\n'), ((1800, 1812), 'torch.nn.Sigmoid', 'nn.Sigmoid', ([], {}), '()\n', (1810, 1812), True, 'import torch.nn as nn\n'), ((2101, 2140), 'net_utils.run_lstm', 'run_lstm', (['self.q_lstm', 'q_emb_var', 'q_len'], {}), '(self.q_lstm, q_emb_var, q_len)\n', (2109, 2140), False, 'from net_utils import run_lstm, col_name_encode\n'), ((2161, 2203), 'net_utils.run_lstm', 'run_lstm', (['self.hs_lstm', 'hs_emb_var', 'hs_len'], {}), '(self.hs_lstm, hs_emb_var, hs_len)\n', (2169, 2203), False, 'from net_utils import run_lstm, col_name_encode\n'), ((2225, 2291), 'net_utils.col_name_encode', 'col_name_encode', (['col_emb_var', 'col_name_len', 'col_len', 'self.col_lstm'], {}), '(col_emb_var, col_name_len, col_len, self.col_lstm)\n', (2240, 2291), False, 'from net_utils import run_lstm, col_name_encode\n'), ((2491, 2511), 'torch.stack', 'torch.stack', (['col_emb'], {}), '(col_emb)\n', (2502, 2511), False, 'import torch\n'), ((5617, 5651), 'numpy.zeros', 'np.zeros', (['(B, T)'], {'dtype': 'np.float32'}), '((B, T), dtype=np.float32)\n', (5625, 5651), True, 'import numpy as np\n'), ((7040, 7073), 'numpy.array', 'np.array', (['(num_err, err, tot_err)'], {}), '((num_err, err, tot_err))\n', (7048, 7073), True, 'import numpy as np\n'), ((1188, 1197), 'torch.nn.Tanh', 'nn.Tanh', ([], {}), '()\n', (1195, 1197), True, 'import torch.nn as nn\n'), ((1199, 1216), 'torch.nn.Linear', 'nn.Linear', (['N_h', '(2)'], {}), '(N_h, 2)\n', (1208, 1216), True, 'import torch.nn as nn\n'), ((1505, 1514), 'torch.nn.Tanh', 'nn.Tanh', ([], {}), '()\n', (1512, 1514), True, 'import torch.nn as nn\n'), ((1516, 1534), 'torch.nn.Linear', 'nn.Linear', (['N_h', '(11)'], {}), '(N_h, 11)\n', (1525, 1534), True, 'import torch.nn as nn\n'), ((5425, 5444), 'numpy.array', 'np.array', (['truth_num'], {}), '(truth_num)\n', (5433, 5444), True, 'import numpy as np\n'), ((5751, 5771), 'numpy.array', 'np.array', (['truth_prob'], {}), '(truth_prob)\n', (5759, 5771), True, 'import numpy as np\n'), ((6430, 6456), 'numpy.argmax', 'np.argmax', (['op_num_score[b]'], {}), '(op_num_score[b])\n', (6439, 6456), True, 'import numpy as np\n'), ((6589, 6613), 'numpy.argsort', 'np.argsort', (['(-op_score[b])'], {}), '(-op_score[b])\n', (6599, 6613), True, 'import numpy as np\n'), ((6086, 6118), 'torch.log', 'torch.log', (['(1 - pred_prob + 1e-10)'], {}), '(1 - pred_prob + 1e-10)\n', (6095, 6118), False, 'import torch\n'), ((6022, 6050), 'torch.log', 'torch.log', (['(pred_prob + 1e-10)'], {}), '(pred_prob + 1e-10)\n', (6031, 6050), False, 'import torch\n')]
import datetime import numpy as np from icarus_backend.flight.FlightModel import Flight from users.models import IcarusUser as User from icarus_backend.department.DepartmentModel import Department from icarus_backend.department.tasks import DepartmentTasks from django.utils import timezone from django.contrib.gis.geos import Polygon from django.db.models import Q class DepartmentController: @staticmethod def create(name, owner_id, area, airbosses=[], watch_commanders=[]) -> (int, dict): numpy_area = np.asarray(area) if not (len(numpy_area.shape) == 3 and numpy_area.shape[2] == 2): return 400, {'message': 'Area is not properly formatted. Must have shape (-1, -1, 2).'} area = [[x[1],x[0]] for x in area[0]] area = Polygon(area) department = Department.objects.filter(name=name).first() if department: return 400, {'message': 'Department name already taken.'} owner = User.objects.filter(id=owner_id).first() department = Department(name=name, area=area, owner=owner) for airboss in airbosses: department.airbosses.add(airboss) for watch_commander in watch_commanders: department.watchCommanders.add(watch_commander) department.save() return 200, {'message': 'Department created.'} @staticmethod def edit(name, new_name, area) -> (int, dict): area = Polygon(area) department = Department.objects.filter(name=name).first() if not department: return 400, {'message': 'No department with this name exists.'} department.area = area department.name = new_name department.save() return 200, {'message': 'Department edited.'} @staticmethod def get(area=None) -> (int, dict): departments = Department.objects if area: area = Polygon(area) departments = departments.filter(area__intersects=area) departments = departments.all() response_array = [] for department in departments: response_array += [department.as_dict()] return 200, response_array @staticmethod def add_airboss(name, airboss_id) -> (int, dict): department = Department.objects.filter(name=name).first() if not department: return 400, {'message': 'No department of that name exists.'} airboss = User.objects.filter(id=airboss_id).first() if not airboss: return 400, {'message': 'No user of that id exists.'} if department.airbosses.filter(id=airboss_id).exists(): return 400, {'message': 'This user is already an airboss for this department.'} department.airbosses.add(airboss) return 200, {'message': 'Members successfully added.'} @staticmethod def remove_airboss(name, airboss_id) -> (int, dict): department = Department.objects.filter(name=name).first() if not department: return 400, {'message': 'No department of that name exists.'} airboss = User.objects.filter(id=airboss_id).first() if not airboss: return 400, {'message': 'No user of that id exists.'} if not department.airbosses.filter(id=airboss_id).exists(): return 400, {'message': 'This user is not currently an airboss for this department.'} department.airbosses.remove(airboss) return 200, {'message': 'Members successfully removed.'} @staticmethod def add_watch_commander(name, watch_commander_id) -> (int, dict): department = Department.objects.filter(name=name).first() if not department: return 400, {'message': 'No department of that name exists.'} watch_commander = User.objects.filter(id=watch_commander_id).first() if not watch_commander: return 400, {'message': 'No user of that id exists.'} if department.airbosses.filter(id=watch_commander_id).exists(): return 400, {'message': 'This user is already a watch commander for this department.'} department.watchCommanders.add(watch_commander) return 200, {'message': 'Members successfully added.'} @staticmethod def remove_watch_commander(name, watch_commander_id) -> (int, dict): department = Department.objects.filter(name=name).first() if not department: return 400, {'message': 'No department of that name exists.'} watch_commander = User.objects.filter(id=watch_commander_id).first() if not watch_commander: return 400, {'message': 'No user of that id exists.'} if not department.watchCommanders.filter(id=watch_commander_id).exists(): return 400, {'message': 'This user is not currently an airboss for this department.'} department.watchCommanders.remove(watch_commander) return 200, {'message': 'Members successfully added.'} @staticmethod def flight_histogram(department_id, start_day, end_day, user) -> (int, dict): number_of_days = (end_day-start_day).days + 1 histogram = [] department = Department.objects.filter(id=department_id).first() if not department: return 400, {'message': 'No department with that id exists.'} for index in range(0, number_of_days): starts_at = start_day + datetime.timedelta(days=index) ends_at = start_day + datetime.timedelta(days=index+1) num_flights = Flight.objects.filter(area__intersects=department.area, starts_at__gt=starts_at, ends_at__lt=ends_at).count() histogram += [num_flights] return 200, histogram @staticmethod def message_pilots(department_name, message): _now = timezone.now() department = Department.objects.filter(name=department_name).first() local_pilots = User.objects.filter(flight__area__intersects=department.area, flight__ends_at__gt=_now)\ .distinct() for pilot in local_pilots: DepartmentTasks.email_jurisdiction.delay(pilot.username, pilot.email, department.name, message) @staticmethod def get_user_department_query(user): return Department.objects.filter(Q(airbosses__in=[user]) | Q(watchCommanders__in=[user])).distinct() @staticmethod def get_user_department(user) -> (int, dict): departments_query = DepartmentController.get_user_department_query(user) departments = [x.as_dict() for x in departments_query] return 200, departments @staticmethod def is_department_member(user): return bool(DepartmentController.get_user_department_query(user)) @staticmethod def can_edit(user, flight): can_edit = False for department in DepartmentController.get_user_department_query(user): if flight.area.intersects(department.area) and user in department.airbosses.all(): can_edit = True return can_edit @staticmethod def info(department_id) -> (int, dict): department = Department.objects.filter(id=department_id).first() if not department: return 400, {'message': 'No department with this id exists.'} return 200, department.as_dict() @staticmethod def delete(department_id) -> (int, dict): department = Department.objects.filter(id=department_id).first() if not department: return 400, {'message': 'No department with this id exists.'} department.delete() return 200, {'message': 'Department successfully deleted.'}
[ "users.models.IcarusUser.objects.filter", "icarus_backend.department.DepartmentModel.Department.objects.filter", "django.utils.timezone.now", "numpy.asarray", "icarus_backend.department.DepartmentModel.Department", "django.db.models.Q", "icarus_backend.flight.FlightModel.Flight.objects.filter", "datet...
[((524, 540), 'numpy.asarray', 'np.asarray', (['area'], {}), '(area)\n', (534, 540), True, 'import numpy as np\n'), ((776, 789), 'django.contrib.gis.geos.Polygon', 'Polygon', (['area'], {}), '(area)\n', (783, 789), False, 'from django.contrib.gis.geos import Polygon\n'), ((1027, 1072), 'icarus_backend.department.DepartmentModel.Department', 'Department', ([], {'name': 'name', 'area': 'area', 'owner': 'owner'}), '(name=name, area=area, owner=owner)\n', (1037, 1072), False, 'from icarus_backend.department.DepartmentModel import Department\n'), ((1428, 1441), 'django.contrib.gis.geos.Polygon', 'Polygon', (['area'], {}), '(area)\n', (1435, 1441), False, 'from django.contrib.gis.geos import Polygon\n'), ((5774, 5788), 'django.utils.timezone.now', 'timezone.now', ([], {}), '()\n', (5786, 5788), False, 'from django.utils import timezone\n'), ((1892, 1905), 'django.contrib.gis.geos.Polygon', 'Polygon', (['area'], {}), '(area)\n', (1899, 1905), False, 'from django.contrib.gis.geos import Polygon\n'), ((6049, 6148), 'icarus_backend.department.tasks.DepartmentTasks.email_jurisdiction.delay', 'DepartmentTasks.email_jurisdiction.delay', (['pilot.username', 'pilot.email', 'department.name', 'message'], {}), '(pilot.username, pilot.email,\n department.name, message)\n', (6089, 6148), False, 'from icarus_backend.department.tasks import DepartmentTasks\n'), ((811, 847), 'icarus_backend.department.DepartmentModel.Department.objects.filter', 'Department.objects.filter', ([], {'name': 'name'}), '(name=name)\n', (836, 847), False, 'from icarus_backend.department.DepartmentModel import Department\n'), ((965, 997), 'users.models.IcarusUser.objects.filter', 'User.objects.filter', ([], {'id': 'owner_id'}), '(id=owner_id)\n', (984, 997), True, 'from users.models import IcarusUser as User\n'), ((1463, 1499), 'icarus_backend.department.DepartmentModel.Department.objects.filter', 'Department.objects.filter', ([], {'name': 'name'}), '(name=name)\n', (1488, 1499), False, 'from icarus_backend.department.DepartmentModel import Department\n'), ((2263, 2299), 'icarus_backend.department.DepartmentModel.Department.objects.filter', 'Department.objects.filter', ([], {'name': 'name'}), '(name=name)\n', (2288, 2299), False, 'from icarus_backend.department.DepartmentModel import Department\n'), ((2428, 2462), 'users.models.IcarusUser.objects.filter', 'User.objects.filter', ([], {'id': 'airboss_id'}), '(id=airboss_id)\n', (2447, 2462), True, 'from users.models import IcarusUser as User\n'), ((2919, 2955), 'icarus_backend.department.DepartmentModel.Department.objects.filter', 'Department.objects.filter', ([], {'name': 'name'}), '(name=name)\n', (2944, 2955), False, 'from icarus_backend.department.DepartmentModel import Department\n'), ((3084, 3118), 'users.models.IcarusUser.objects.filter', 'User.objects.filter', ([], {'id': 'airboss_id'}), '(id=airboss_id)\n', (3103, 3118), True, 'from users.models import IcarusUser as User\n'), ((3603, 3639), 'icarus_backend.department.DepartmentModel.Department.objects.filter', 'Department.objects.filter', ([], {'name': 'name'}), '(name=name)\n', (3628, 3639), False, 'from icarus_backend.department.DepartmentModel import Department\n'), ((3776, 3818), 'users.models.IcarusUser.objects.filter', 'User.objects.filter', ([], {'id': 'watch_commander_id'}), '(id=watch_commander_id)\n', (3795, 3818), True, 'from users.models import IcarusUser as User\n'), ((4328, 4364), 'icarus_backend.department.DepartmentModel.Department.objects.filter', 'Department.objects.filter', ([], {'name': 'name'}), '(name=name)\n', (4353, 4364), False, 'from icarus_backend.department.DepartmentModel import Department\n'), ((4501, 4543), 'users.models.IcarusUser.objects.filter', 'User.objects.filter', ([], {'id': 'watch_commander_id'}), '(id=watch_commander_id)\n', (4520, 4543), True, 'from users.models import IcarusUser as User\n'), ((5151, 5194), 'icarus_backend.department.DepartmentModel.Department.objects.filter', 'Department.objects.filter', ([], {'id': 'department_id'}), '(id=department_id)\n', (5176, 5194), False, 'from icarus_backend.department.DepartmentModel import Department\n'), ((5387, 5417), 'datetime.timedelta', 'datetime.timedelta', ([], {'days': 'index'}), '(days=index)\n', (5405, 5417), False, 'import datetime\n'), ((5452, 5486), 'datetime.timedelta', 'datetime.timedelta', ([], {'days': '(index + 1)'}), '(days=index + 1)\n', (5470, 5486), False, 'import datetime\n'), ((5810, 5857), 'icarus_backend.department.DepartmentModel.Department.objects.filter', 'Department.objects.filter', ([], {'name': 'department_name'}), '(name=department_name)\n', (5835, 5857), False, 'from icarus_backend.department.DepartmentModel import Department\n'), ((5889, 5980), 'users.models.IcarusUser.objects.filter', 'User.objects.filter', ([], {'flight__area__intersects': 'department.area', 'flight__ends_at__gt': '_now'}), '(flight__area__intersects=department.area,\n flight__ends_at__gt=_now)\n', (5908, 5980), True, 'from users.models import IcarusUser as User\n'), ((7079, 7122), 'icarus_backend.department.DepartmentModel.Department.objects.filter', 'Department.objects.filter', ([], {'id': 'department_id'}), '(id=department_id)\n', (7104, 7122), False, 'from icarus_backend.department.DepartmentModel import Department\n'), ((7359, 7402), 'icarus_backend.department.DepartmentModel.Department.objects.filter', 'Department.objects.filter', ([], {'id': 'department_id'}), '(id=department_id)\n', (7384, 7402), False, 'from icarus_backend.department.DepartmentModel import Department\n'), ((5511, 5617), 'icarus_backend.flight.FlightModel.Flight.objects.filter', 'Flight.objects.filter', ([], {'area__intersects': 'department.area', 'starts_at__gt': 'starts_at', 'ends_at__lt': 'ends_at'}), '(area__intersects=department.area, starts_at__gt=\n starts_at, ends_at__lt=ends_at)\n', (5532, 5617), False, 'from icarus_backend.flight.FlightModel import Flight\n'), ((6246, 6269), 'django.db.models.Q', 'Q', ([], {'airbosses__in': '[user]'}), '(airbosses__in=[user])\n', (6247, 6269), False, 'from django.db.models import Q\n'), ((6272, 6301), 'django.db.models.Q', 'Q', ([], {'watchCommanders__in': '[user]'}), '(watchCommanders__in=[user])\n', (6273, 6301), False, 'from django.db.models import Q\n')]
import feedparser import tensorflow as tf import numpy as np from transformers import * import re, string import pandas as pd import sys from keras.preprocessing.sequence import pad_sequences feed = feedparser.parse('http://feeds.bbci.co.uk/news/rss.xml') titles = [article.title for article in feed.entries] print(f'Number of titles: {len(titles)}') tokenizer = BertTokenizer.from_pretrained('bert-base-cased') original_titles = titles.copy() titles = [tokenizer.tokenize('[CLS] ' + title + ' [CEP]') for title in titles] MAX_LEN=128 input_ids = pad_sequences([tokenizer.convert_tokens_to_ids(title) for title in titles], maxlen=MAX_LEN, dtype='long', truncating='post', padding='post') model = TFBertForSequenceClassification.from_pretrained('./seemsaccurate6/') classes = ['negative', 'positive'] results = model.predict(input_ids) count_g = 0 total_g = 0 countp = 0 countn = 0 def print_accuracy(count, total): accuracy = (count / total) * 100 print(f'Total articles: {total}') print(f'Total correct: {count}') print('Accuracy {:.2f}'.format(accuracy)) for i in range(len(results)): classi = np.argmax(results[i]) title = original_titles[i] total_g += 1 ''' if classi == 1: print(title) countp += 1 if classi == 0: countn += 1 ''' print(title) print(f'Class: {classi}') # print('**') # print(f'Title: {title}') # orig_classi = int(input('Human classification: ')) # if orig_classi == classi: # count_g += 1 # print_accuracy(count_g, total_g) # print('**') print(countp) print(countn)
[ "feedparser.parse", "numpy.argmax" ]
[((204, 260), 'feedparser.parse', 'feedparser.parse', (['"""http://feeds.bbci.co.uk/news/rss.xml"""'], {}), "('http://feeds.bbci.co.uk/news/rss.xml')\n", (220, 260), False, 'import feedparser\n'), ((1144, 1165), 'numpy.argmax', 'np.argmax', (['results[i]'], {}), '(results[i])\n', (1153, 1165), True, 'import numpy as np\n')]
import argparse, os import h5py from scipy.misc import imresize import skvideo.io from PIL import Image import torch from torch import nn import torchvision import random import numpy as np from models import resnext from datautils import utils from datautils import tgif_qa from datautils import msrvtt_qa from datautils import msvd_qa def build_resnet(): if not hasattr(torchvision.models, args.model): raise ValueError('Invalid model "%s"' % args.model) if not 'resnet' in args.model: raise ValueError('Feature extraction only supports ResNets') cnn = getattr(torchvision.models, args.model)(pretrained=True) model = torch.nn.Sequential(*list(cnn.children())[:-1]) model.cuda() model.eval() return model def build_resnext(): model = resnext.resnet101(num_classes=400, shortcut_type='B', cardinality=32, sample_size=112, sample_duration=16, last_fc=False) model = model.cuda() model = nn.DataParallel(model, device_ids=None) assert os.path.exists('preprocess/pretrained/resnext-101-kinetics.pth') model_data = torch.load('preprocess/pretrained/resnext-101-kinetics.pth', map_location='cpu') model.load_state_dict(model_data['state_dict']) model.eval() return model def run_batch(cur_batch, model): """ Args: cur_batch: treat a video as a batch of images model: ResNet model for feature extraction Returns: ResNet extracted feature. """ mean = np.array([0.485, 0.456, 0.406]).reshape(1, 3, 1, 1) std = np.array([0.229, 0.224, 0.224]).reshape(1, 3, 1, 1) image_batch = np.concatenate(cur_batch, 0).astype(np.float32) image_batch = (image_batch / 255.0 - mean) / std image_batch = torch.FloatTensor(image_batch).cuda() with torch.no_grad(): image_batch = torch.autograd.Variable(image_batch) feats = model(image_batch) feats = feats.data.cpu().clone().numpy() return feats def extract_clips_with_consecutive_frames(path, num_clips, num_frames_per_clip): """ Args: path: path of a video num_clips: expected numbers of splitted clips num_frames_per_clip: number of frames in a single clip, pretrained model only supports 16 frames Returns: A list of raw features of clips. """ valid = True clips = list() try: video_data = skvideo.io.vread(path) except: print('file {} error'.format(path)) valid = False if args.model == 'resnext101': return list(np.zeros(shape=(num_clips, 3, num_frames_per_clip, 112, 112))), valid else: return list(np.zeros(shape=(num_clips, num_frames_per_clip, 3, 224, 224))), valid total_frames = video_data.shape[0] img_size = (args.image_height, args.image_width) for i in np.linspace(0, total_frames, num_clips + 2, dtype=np.int32)[1:num_clips + 1]: clip_start = int(i) - int(num_frames_per_clip / 2) clip_end = int(i) + int(num_frames_per_clip / 2) if clip_start < 0: clip_start = 0 if clip_end > total_frames: clip_end = total_frames - 1 clip = video_data[clip_start:clip_end] if clip_start == 0: shortage = num_frames_per_clip - (clip_end - clip_start) added_frames = [] for _ in range(shortage): added_frames.append(np.expand_dims(video_data[clip_start], axis=0)) if len(added_frames) > 0: added_frames = np.concatenate(added_frames, axis=0) clip = np.concatenate((added_frames, clip), axis=0) if clip_end == (total_frames - 1): shortage = num_frames_per_clip - (clip_end - clip_start) added_frames = [] for _ in range(shortage): added_frames.append(np.expand_dims(video_data[clip_end], axis=0)) if len(added_frames) > 0: added_frames = np.concatenate(added_frames, axis=0) clip = np.concatenate((clip, added_frames), axis=0) new_clip = [] for j in range(num_frames_per_clip): frame_data = clip[j] img = Image.fromarray(frame_data) img = imresize(img, img_size, interp='bicubic') img = img.transpose(2, 0, 1)[None] frame_data = np.array(img) new_clip.append(frame_data) new_clip = np.asarray(new_clip) # (num_frames, width, height, channels) if args.model in ['resnext101']: new_clip = np.squeeze(new_clip) new_clip = np.transpose(new_clip, axes=(1, 0, 2, 3)) clips.append(new_clip) return clips, valid def generate_h5(model, video_ids, num_clips, outfile): """ Args: model: loaded pretrained model for feature extraction video_ids: list of video ids num_clips: expected numbers of splitted clips outfile: path of output file to be written Returns: h5 file containing visual features of splitted clips. """ if args.dataset == "tgif-qa": if not os.path.exists('data/tgif-qa/{}'.format(args.question_type)): os.makedirs('data/tgif-qa/{}'.format(args.question_type)) else: if not os.path.exists('data/{}'.format(args.dataset)): os.makedirs('data/{}'.format(args.dataset)) dataset_size = len(video_ids) with h5py.File(outfile, 'w') as fd: feat_dset = None video_ids_dset = None i0 = 0 _t = {'misc': utils.Timer()} for i, (video_path, video_id) in enumerate(video_ids): _t['misc'].tic() clips, valid = extract_clips_with_consecutive_frames(video_path, num_clips=num_clips, num_frames_per_clip=16) if args.feature_type == 'appearance': clip_feat = [] if valid: for clip_id, clip in enumerate(clips): feats = run_batch(clip, model) # (16, 2048) feats = feats.squeeze() clip_feat.append(feats) else: clip_feat = np.zeros(shape=(num_clips, 16, 2048)) clip_feat = np.asarray(clip_feat) # (8, 16, 2048) if feat_dset is None: C, F, D = clip_feat.shape feat_dset = fd.create_dataset('resnet_features', (dataset_size, C, F, D), dtype=np.float32) video_ids_dset = fd.create_dataset('ids', shape=(dataset_size,), dtype=np.int) elif args.feature_type == 'motion': clip_torch = torch.FloatTensor(np.asarray(clips)).cuda() if valid: clip_feat = model(clip_torch) # (8, 2048) clip_feat = clip_feat.squeeze() clip_feat = clip_feat.detach().cpu().numpy() else: clip_feat = np.zeros(shape=(num_clips, 2048)) if feat_dset is None: C, D = clip_feat.shape feat_dset = fd.create_dataset('resnext_features', (dataset_size, C, D), dtype=np.float32) video_ids_dset = fd.create_dataset('ids', shape=(dataset_size,), dtype=np.int) i1 = i0 + 1 feat_dset[i0:i1] = clip_feat video_ids_dset[i0:i1] = video_id i0 = i1 _t['misc'].toc() if (i % 1000 == 0): print('{:d}/{:d} {:.3f}s (projected finish: {:.2f} hours)' \ .format(i1, dataset_size, _t['misc'].average_time, _t['misc'].average_time * (dataset_size - i1) / 3600)) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--gpu_id', type=int, default=2, help='specify which gpu will be used') # dataset info parser.add_argument('--dataset', default='tgif-qa', choices=['tgif-qa', 'msvd-qa', 'msrvtt-qa'], type=str) parser.add_argument('--question_type', default='none', choices=['frameqa', 'count', 'transition', 'action', 'none'], type=str) # output parser.add_argument('--out', dest='outfile', help='output filepath', default="data/{}/{}_{}_feat.h5", type=str) # image sizes parser.add_argument('--num_clips', default=8, type=int) parser.add_argument('--image_height', default=224, type=int) parser.add_argument('--image_width', default=224, type=int) # network params parser.add_argument('--model', default='resnet101', choices=['resnet101', 'resnext101'], type=str) parser.add_argument('--seed', default='666', type=int, help='random seed') args = parser.parse_args() if args.model == 'resnet101': args.feature_type = 'appearance' elif args.model == 'resnext101': args.feature_type = 'motion' else: raise Exception('Feature type not supported!') # set gpu if args.model != 'resnext101': torch.cuda.set_device(args.gpu_id) torch.manual_seed(args.seed) np.random.seed(args.seed) # annotation files if args.dataset == 'tgif-qa': args.annotation_file = '/ceph-g/lethao/datasets/tgif-qa/csv/Total_{}_question.csv' args.video_dir = '/ceph-g/lethao/datasets/tgif-qa/gifs' args.outfile = 'data/{}/{}/{}_{}_{}_feat.h5' video_paths = tgif_qa.load_video_paths(args) random.shuffle(video_paths) # load model if args.model == 'resnet101': model = build_resnet() elif args.model == 'resnext101': model = build_resnext() generate_h5(model, video_paths, args.num_clips, args.outfile.format(args.dataset, args.question_type, args.dataset, args.question_type, args.feature_type)) elif args.dataset == 'msrvtt-qa': args.annotation_file = '/ceph-g/lethao/datasets/msrvtt/annotations/{}_qa.json' args.video_dir = '/ceph-g/lethao/datasets/msrvtt/videos/' video_paths = msrvtt_qa.load_video_paths(args) random.shuffle(video_paths) # load model if args.model == 'resnet101': model = build_resnet() elif args.model == 'resnext101': model = build_resnext() generate_h5(model, video_paths, args.num_clips, args.outfile.format(args.dataset, args.dataset, args.feature_type)) elif args.dataset == 'msvd-qa': args.annotation_file = '/ceph-g/lethao/datasets/msvd/MSVD-QA/{}_qa.json' args.video_dir = '/ceph-g/lethao/datasets/msvd/MSVD-QA/video/' args.video_name_mapping = '/ceph-g/lethao/datasets/msvd/youtube_mapping.txt' video_paths = msvd_qa.load_video_paths(args) random.shuffle(video_paths) # load model if args.model == 'resnet101': model = build_resnet() elif args.model == 'resnext101': model = build_resnext() generate_h5(model, video_paths, args.num_clips, args.outfile.format(args.dataset, args.dataset, args.feature_type))
[ "numpy.random.seed", "argparse.ArgumentParser", "random.shuffle", "torch.no_grad", "torch.load", "os.path.exists", "torch.FloatTensor", "numpy.transpose", "numpy.linspace", "torch.cuda.set_device", "datautils.msrvtt_qa.load_video_paths", "datautils.utils.Timer", "datautils.msvd_qa.load_video...
[((790, 915), 'models.resnext.resnet101', 'resnext.resnet101', ([], {'num_classes': '(400)', 'shortcut_type': '"""B"""', 'cardinality': '(32)', 'sample_size': '(112)', 'sample_duration': '(16)', 'last_fc': '(False)'}), "(num_classes=400, shortcut_type='B', cardinality=32,\n sample_size=112, sample_duration=16, last_fc=False)\n", (807, 915), False, 'from models import resnext\n'), ((1009, 1048), 'torch.nn.DataParallel', 'nn.DataParallel', (['model'], {'device_ids': 'None'}), '(model, device_ids=None)\n', (1024, 1048), False, 'from torch import nn\n'), ((1060, 1124), 'os.path.exists', 'os.path.exists', (['"""preprocess/pretrained/resnext-101-kinetics.pth"""'], {}), "('preprocess/pretrained/resnext-101-kinetics.pth')\n", (1074, 1124), False, 'import argparse, os\n'), ((1142, 1227), 'torch.load', 'torch.load', (['"""preprocess/pretrained/resnext-101-kinetics.pth"""'], {'map_location': '"""cpu"""'}), "('preprocess/pretrained/resnext-101-kinetics.pth', map_location='cpu'\n )\n", (1152, 1227), False, 'import torch\n'), ((7844, 7869), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (7867, 7869), False, 'import argparse, os\n'), ((9156, 9184), 'torch.manual_seed', 'torch.manual_seed', (['args.seed'], {}), '(args.seed)\n', (9173, 9184), False, 'import torch\n'), ((9189, 9214), 'numpy.random.seed', 'np.random.seed', (['args.seed'], {}), '(args.seed)\n', (9203, 9214), True, 'import numpy as np\n'), ((1832, 1847), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (1845, 1847), False, 'import torch\n'), ((1871, 1907), 'torch.autograd.Variable', 'torch.autograd.Variable', (['image_batch'], {}), '(image_batch)\n', (1894, 1907), False, 'import torch\n'), ((2868, 2927), 'numpy.linspace', 'np.linspace', (['(0)', 'total_frames', '(num_clips + 2)'], {'dtype': 'np.int32'}), '(0, total_frames, num_clips + 2, dtype=np.int32)\n', (2879, 2927), True, 'import numpy as np\n'), ((4449, 4469), 'numpy.asarray', 'np.asarray', (['new_clip'], {}), '(new_clip)\n', (4459, 4469), True, 'import numpy as np\n'), ((5433, 5456), 'h5py.File', 'h5py.File', (['outfile', '"""w"""'], {}), "(outfile, 'w')\n", (5442, 5456), False, 'import h5py\n'), ((9117, 9151), 'torch.cuda.set_device', 'torch.cuda.set_device', (['args.gpu_id'], {}), '(args.gpu_id)\n', (9138, 9151), False, 'import torch\n'), ((9503, 9533), 'datautils.tgif_qa.load_video_paths', 'tgif_qa.load_video_paths', (['args'], {}), '(args)\n', (9527, 9533), False, 'from datautils import tgif_qa\n'), ((9542, 9569), 'random.shuffle', 'random.shuffle', (['video_paths'], {}), '(video_paths)\n', (9556, 9569), False, 'import random\n'), ((1533, 1564), 'numpy.array', 'np.array', (['[0.485, 0.456, 0.406]'], {}), '([0.485, 0.456, 0.406])\n', (1541, 1564), True, 'import numpy as np\n'), ((1595, 1626), 'numpy.array', 'np.array', (['[0.229, 0.224, 0.224]'], {}), '([0.229, 0.224, 0.224])\n', (1603, 1626), True, 'import numpy as np\n'), ((1666, 1694), 'numpy.concatenate', 'np.concatenate', (['cur_batch', '(0)'], {}), '(cur_batch, 0)\n', (1680, 1694), True, 'import numpy as np\n'), ((1785, 1815), 'torch.FloatTensor', 'torch.FloatTensor', (['image_batch'], {}), '(image_batch)\n', (1802, 1815), False, 'import torch\n'), ((4216, 4243), 'PIL.Image.fromarray', 'Image.fromarray', (['frame_data'], {}), '(frame_data)\n', (4231, 4243), False, 'from PIL import Image\n'), ((4262, 4303), 'scipy.misc.imresize', 'imresize', (['img', 'img_size'], {'interp': '"""bicubic"""'}), "(img, img_size, interp='bicubic')\n", (4270, 4303), False, 'from scipy.misc import imresize\n'), ((4376, 4389), 'numpy.array', 'np.array', (['img'], {}), '(img)\n', (4384, 4389), True, 'import numpy as np\n'), ((4575, 4595), 'numpy.squeeze', 'np.squeeze', (['new_clip'], {}), '(new_clip)\n', (4585, 4595), True, 'import numpy as np\n'), ((4619, 4660), 'numpy.transpose', 'np.transpose', (['new_clip'], {'axes': '(1, 0, 2, 3)'}), '(new_clip, axes=(1, 0, 2, 3))\n', (4631, 4660), True, 'import numpy as np\n'), ((5556, 5569), 'datautils.utils.Timer', 'utils.Timer', ([], {}), '()\n', (5567, 5569), False, 'from datautils import utils\n'), ((10138, 10170), 'datautils.msrvtt_qa.load_video_paths', 'msrvtt_qa.load_video_paths', (['args'], {}), '(args)\n', (10164, 10170), False, 'from datautils import msrvtt_qa\n'), ((10179, 10206), 'random.shuffle', 'random.shuffle', (['video_paths'], {}), '(video_paths)\n', (10193, 10206), False, 'import random\n'), ((3557, 3593), 'numpy.concatenate', 'np.concatenate', (['added_frames'], {'axis': '(0)'}), '(added_frames, axis=0)\n', (3571, 3593), True, 'import numpy as np\n'), ((3617, 3661), 'numpy.concatenate', 'np.concatenate', (['(added_frames, clip)'], {'axis': '(0)'}), '((added_frames, clip), axis=0)\n', (3631, 3661), True, 'import numpy as np\n'), ((3993, 4029), 'numpy.concatenate', 'np.concatenate', (['added_frames'], {'axis': '(0)'}), '(added_frames, axis=0)\n', (4007, 4029), True, 'import numpy as np\n'), ((4053, 4097), 'numpy.concatenate', 'np.concatenate', (['(clip, added_frames)'], {'axis': '(0)'}), '((clip, added_frames), axis=0)\n', (4067, 4097), True, 'import numpy as np\n'), ((6236, 6257), 'numpy.asarray', 'np.asarray', (['clip_feat'], {}), '(clip_feat)\n', (6246, 6257), True, 'import numpy as np\n'), ((10818, 10848), 'datautils.msvd_qa.load_video_paths', 'msvd_qa.load_video_paths', (['args'], {}), '(args)\n', (10842, 10848), False, 'from datautils import msvd_qa\n'), ((10857, 10884), 'random.shuffle', 'random.shuffle', (['video_paths'], {}), '(video_paths)\n', (10871, 10884), False, 'import random\n'), ((3440, 3486), 'numpy.expand_dims', 'np.expand_dims', (['video_data[clip_start]'], {'axis': '(0)'}), '(video_data[clip_start], axis=0)\n', (3454, 3486), True, 'import numpy as np\n'), ((3878, 3922), 'numpy.expand_dims', 'np.expand_dims', (['video_data[clip_end]'], {'axis': '(0)'}), '(video_data[clip_end], axis=0)\n', (3892, 3922), True, 'import numpy as np\n'), ((6170, 6207), 'numpy.zeros', 'np.zeros', ([], {'shape': '(num_clips, 16, 2048)'}), '(shape=(num_clips, 16, 2048))\n', (6178, 6207), True, 'import numpy as np\n'), ((2585, 2646), 'numpy.zeros', 'np.zeros', ([], {'shape': '(num_clips, 3, num_frames_per_clip, 112, 112)'}), '(shape=(num_clips, 3, num_frames_per_clip, 112, 112))\n', (2593, 2646), True, 'import numpy as np\n'), ((2693, 2754), 'numpy.zeros', 'np.zeros', ([], {'shape': '(num_clips, num_frames_per_clip, 3, 224, 224)'}), '(shape=(num_clips, num_frames_per_clip, 3, 224, 224))\n', (2701, 2754), True, 'import numpy as np\n'), ((7001, 7034), 'numpy.zeros', 'np.zeros', ([], {'shape': '(num_clips, 2048)'}), '(shape=(num_clips, 2048))\n', (7009, 7034), True, 'import numpy as np\n'), ((6715, 6732), 'numpy.asarray', 'np.asarray', (['clips'], {}), '(clips)\n', (6725, 6732), True, 'import numpy as np\n')]
#!/usr/bin/env python3 """ @author: <NAME> @email: <EMAIL> * SETTINGS MODULE * Contains all the settings for a given simulation. At the first call of settings.init() all specified variables are initialized and available. Latest update: May 8th 2021 """ import system import force import printing import numpy as np from numba import jit, njit, vectorize import numba DT = None iter_equ = None iter_prod = None rescaling_freq = None # Routine for initializing all variables of the System def init(): # LJ POTENTIAL VARIABLES force.epsilon = 1. force.sigma = 1. force.cutoff = 4 #in units of sigma # SYSTEM VARIABLES n = 20 #number of particles per dimension system.dim = 2 #dimension of the sytem (2 or 3 - dimensional) system.N = n**system.dim #Number of particles system.rho = 0.5 #Number density system.L = n*np.power(1/system.rho, 1/system.dim) #Box dimensions (per edge) system.alat = system.L/n #Lattice parameter system.p = system.L/force.sigma system.T = 2. #target temperature (variable with cT "current temp also available") # SIMULATIONS VARIABLES global DT, iter_equ, iter_prod, rescaling_freq DT = 2E-4 iter_equ = 2000 iter_prod = 2000 rescaling_freq = 10 # PRINTING VARIABLES printing.eq_print = 20 printing.eq_energy_file = "LJMD_" + str(system.N) + "_equil_energy.txt" printing.eq_temp_file = "LJMD_" + str(system.N) + "_equil_temperature.txt" printing.eq_pos_file = "LJMD_" + str(system.N) + "_equil_positions.txt" printing.eq_vel_file = "LJMD_" + str(system.N) + "_equil_velocity.txt" printing.prod_print = 20 printing.prod_energy_file = "LJMD_" + str(system.N) + "_prod_energy.txt" printing.prod_temp_file = "LJMD_" + str(system.N) + "_prod_temperature.txt" printing.prod_pos_file = "LJMD_" + str(system.N) + "_prod_positions.txt" printing.prod_vel_file = "LJMD_" + str(system.N) + "_prod_velocity.txt" # SYSTEM CONTAINERS (positions, velocities, ...) system.pos = np.zeros((system.N, system.dim), dtype = np.float) system.vel = np.zeros((system.N, system.dim), dtype = np.float) system.force = np.zeros((system.N, system.dim), dtype = np.float) system.mass = 1 #the particles are assumed to be indentical (not in MQ terms) system.time = 0 #probably not very useful # SYSTEM INIT ROUTINES # These are some of the initial routines for initializing the system, # such as lattice positions, random velocities. # These routines may vary from simulation to simulation system.distribute_position_cubic_lattice() system.vel_random() system.vel_shift() system.vel_rescale(system.T) force.LJ_potential_shift()
[ "system.distribute_position_cubic_lattice", "numpy.power", "numpy.zeros", "system.vel_rescale", "system.vel_shift", "system.vel_random", "force.LJ_potential_shift" ]
[((2035, 2083), 'numpy.zeros', 'np.zeros', (['(system.N, system.dim)'], {'dtype': 'np.float'}), '((system.N, system.dim), dtype=np.float)\n', (2043, 2083), True, 'import numpy as np\n'), ((2103, 2151), 'numpy.zeros', 'np.zeros', (['(system.N, system.dim)'], {'dtype': 'np.float'}), '((system.N, system.dim), dtype=np.float)\n', (2111, 2151), True, 'import numpy as np\n'), ((2173, 2221), 'numpy.zeros', 'np.zeros', (['(system.N, system.dim)'], {'dtype': 'np.float'}), '((system.N, system.dim), dtype=np.float)\n', (2181, 2221), True, 'import numpy as np\n'), ((2570, 2612), 'system.distribute_position_cubic_lattice', 'system.distribute_position_cubic_lattice', ([], {}), '()\n', (2610, 2612), False, 'import system\n'), ((2617, 2636), 'system.vel_random', 'system.vel_random', ([], {}), '()\n', (2634, 2636), False, 'import system\n'), ((2641, 2659), 'system.vel_shift', 'system.vel_shift', ([], {}), '()\n', (2657, 2659), False, 'import system\n'), ((2664, 2692), 'system.vel_rescale', 'system.vel_rescale', (['system.T'], {}), '(system.T)\n', (2682, 2692), False, 'import system\n'), ((2697, 2723), 'force.LJ_potential_shift', 'force.LJ_potential_shift', ([], {}), '()\n', (2721, 2723), False, 'import force\n'), ((869, 909), 'numpy.power', 'np.power', (['(1 / system.rho)', '(1 / system.dim)'], {}), '(1 / system.rho, 1 / system.dim)\n', (877, 909), True, 'import numpy as np\n')]