edited_code
stringlengths
17
978k
original_code
stringlengths
17
978k
""" Copyright (c) 2020, salesforce.com, inc. All rights reserved. SPDX-License-Identifier: BSD-3-Clause For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause """ import os import sys from http.server import HTTPServer, SimpleHTTPRequestHandler from multiprocessing import Process import subprocess from transformers import RobertaForSequenceClassification, RobertaTokenizer import json import fire import torch from urllib.parse import urlparse, unquote model_combine_256: RobertaForSequenceClassification = None tokenizer: RobertaTokenizer = None device: str = None def log(*args): print(f"[{os.environ.get("RANK", "")}]", *args, file=sys.stderr) class RequestHandler(SimpleHTTPRequestHandler): def do_GET(self): query = unquote(urlparse(self.path).query) if not query: self.begin_content('text/html') html = os.path.join(os.path.dirname(__file__), 'index.html') self.wfile.write(open(html).read().encode()) return self.begin_content('application/json;charset=UTF-8') tokens = tokenizer.encode(query[1:]) all_tokens = len(tokens) - 2 tokens = tokens[:tokenizer.max_len - 2] used_tokens = len(tokens) - 2 model = model_combine_256 tokens = torch.tensor([tokenizer.bos_token_id] + tokens + [tokenizer.eos_token_id]).unsqueeze(0) mask = torch.ones_like(tokens) with torch.no_grad(): logits = model(tokens.to(device), attention_mask=mask.to(device))[0] probs = logits.softmax(dim=-1) fake, real = probs.detach().cpu().flatten().numpy().tolist() self.wfile.write(json.dumps(dict( all_tokens=all_tokens, used_tokens=used_tokens, real_probability=real, fake_probability=fake )).encode()) def begin_content(self, content_type): self.send_response(200) self.send_header('Content-Type', content_type) self.send_header('Access-Control-Allow-Origin', '*') self.end_headers() def log_message(self, format, *args): log(format % args) def serve_forever(server, model_combine_256, tokenizer, device): log('Process has started; loading the model ...') globals()['tokenizer'] = tokenizer globals()['device'] = device globals()['model_combine_256'] = model_combine_256.to(device) log(f'Ready to serve at http://localhost:{server.server_address[1]}') server.serve_forever() def main(port=8080, device='cuda' if torch.cuda.is_available() else 'cpu'): data_combine_256 = torch.load('combine_256.pt', map_location='cpu') model_name = 'roberta-large' tokenizer = RobertaTokenizer.from_pretrained(model_name) model_combine_256 = RobertaForSequenceClassification.from_pretrained('roberta-large') model_combine_256.load_state_dict(data_combine_256['model_state_dict'], strict=False) model_combine_256.eval() print(f'Starting HTTP server on port {port}', file=sys.stderr) server = HTTPServer(('0.0.0.0', port), RequestHandler) # avoid calling CUDA API before forking; doing so in a subprocess is fine. num_workers = int(subprocess.check_output([sys.executable, '-c', 'import torch; print(torch.cuda.device_count())'])) if num_workers <= 1: serve_forever(server, model_combine_256, tokenizer, device) else: print(f'Launching {num_workers} worker processes...') subprocesses = [] for i in range(num_workers): os.environ['RANK'] = f'{i}' os.environ['CUDA_VISIBLE_DEVICES'] = f'{i}' process = Process(target=serve_forever, args=(server, model_combine_256, tokenizer, device)) process.start() subprocesses.append(process) del os.environ['RANK'] del os.environ['CUDA_VISIBLE_DEVICES'] for process in subprocesses: process.join() if __name__ == '__main__': fire.Fire(main)
""" Copyright (c) 2020, salesforce.com, inc. All rights reserved. SPDX-License-Identifier: BSD-3-Clause For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause """ import os import sys from http.server import HTTPServer, SimpleHTTPRequestHandler from multiprocessing import Process import subprocess from transformers import RobertaForSequenceClassification, RobertaTokenizer import json import fire import torch from urllib.parse import urlparse, unquote model_combine_256: RobertaForSequenceClassification = None tokenizer: RobertaTokenizer = None device: str = None def log(*args): print(f"[{os.environ.get('RANK', '')}]", *args, file=sys.stderr) class RequestHandler(SimpleHTTPRequestHandler): def do_GET(self): query = unquote(urlparse(self.path).query) if not query: self.begin_content('text/html') html = os.path.join(os.path.dirname(__file__), 'index.html') self.wfile.write(open(html).read().encode()) return self.begin_content('application/json;charset=UTF-8') tokens = tokenizer.encode(query[1:]) all_tokens = len(tokens) - 2 tokens = tokens[:tokenizer.max_len - 2] used_tokens = len(tokens) - 2 model = model_combine_256 tokens = torch.tensor([tokenizer.bos_token_id] + tokens + [tokenizer.eos_token_id]).unsqueeze(0) mask = torch.ones_like(tokens) with torch.no_grad(): logits = model(tokens.to(device), attention_mask=mask.to(device))[0] probs = logits.softmax(dim=-1) fake, real = probs.detach().cpu().flatten().numpy().tolist() self.wfile.write(json.dumps(dict( all_tokens=all_tokens, used_tokens=used_tokens, real_probability=real, fake_probability=fake )).encode()) def begin_content(self, content_type): self.send_response(200) self.send_header('Content-Type', content_type) self.send_header('Access-Control-Allow-Origin', '*') self.end_headers() def log_message(self, format, *args): log(format % args) def serve_forever(server, model_combine_256, tokenizer, device): log('Process has started; loading the model ...') globals()['tokenizer'] = tokenizer globals()['device'] = device globals()['model_combine_256'] = model_combine_256.to(device) log(f'Ready to serve at http://localhost:{server.server_address[1]}') server.serve_forever() def main(port=8080, device='cuda' if torch.cuda.is_available() else 'cpu'): data_combine_256 = torch.load('combine_256.pt', map_location='cpu') model_name = 'roberta-large' tokenizer = RobertaTokenizer.from_pretrained(model_name) model_combine_256 = RobertaForSequenceClassification.from_pretrained('roberta-large') model_combine_256.load_state_dict(data_combine_256['model_state_dict'], strict=False) model_combine_256.eval() print(f'Starting HTTP server on port {port}', file=sys.stderr) server = HTTPServer(('0.0.0.0', port), RequestHandler) # avoid calling CUDA API before forking; doing so in a subprocess is fine. num_workers = int(subprocess.check_output([sys.executable, '-c', 'import torch; print(torch.cuda.device_count())'])) if num_workers <= 1: serve_forever(server, model_combine_256, tokenizer, device) else: print(f'Launching {num_workers} worker processes...') subprocesses = [] for i in range(num_workers): os.environ['RANK'] = f'{i}' os.environ['CUDA_VISIBLE_DEVICES'] = f'{i}' process = Process(target=serve_forever, args=(server, model_combine_256, tokenizer, device)) process.start() subprocesses.append(process) del os.environ['RANK'] del os.environ['CUDA_VISIBLE_DEVICES'] for process in subprocesses: process.join() if __name__ == '__main__': fire.Fire(main)
import builtins import datetime as dt from io import StringIO from string import ascii_lowercase import numpy as np import pytest from pandas.errors import UnsupportedFunctionCall import pandas as pd from pandas import ( DataFrame, Index, MultiIndex, NaT, Series, Timestamp, _is_numpy_dev, date_range, isna, ) import pandas._testing as tm import pandas.core.nanops as nanops from pandas.util import _test_decorators as td @pytest.fixture( params=[np.int32, np.int64, np.float32, np.float64], ids=["np.int32", "np.int64", "np.float32", "np.float64"], ) def numpy_dtypes_for_minmax(request): """ Fixture of numpy dtypes with min and max values used for testing cummin and cummax """ dtype = request.param min_val = ( np.iinfo(dtype).min if np.dtype(dtype).kind == "i" else np.finfo(dtype).min ) max_val = ( np.iinfo(dtype).max if np.dtype(dtype).kind == "i" else np.finfo(dtype).max ) return (dtype, min_val, max_val) @pytest.mark.parametrize("agg_func", ["any", "all"]) @pytest.mark.parametrize("skipna", [True, False]) @pytest.mark.parametrize( "vals", [ ["foo", "bar", "baz"], ["foo", "", ""], ["", "", ""], [1, 2, 3], [1, 0, 0], [0, 0, 0], [1.0, 2.0, 3.0], [1.0, 0.0, 0.0], [0.0, 0.0, 0.0], [True, True, True], [True, False, False], [False, False, False], [np.nan, np.nan, np.nan], ], ) def test_groupby_bool_aggs(agg_func, skipna, vals): df = DataFrame({"key": ["a"] * 3 + ["b"] * 3, "val": vals * 2}) # Figure out expectation using Python builtin exp = getattr(builtins, agg_func)(vals) # edge case for missing data with skipna and 'any' if skipna and all(isna(vals)) and agg_func == "any": exp = False exp_df = DataFrame([exp] * 2, columns=["val"], index=Index(["a", "b"], name="key")) result = getattr(df.groupby("key"), agg_func)(skipna=skipna) tm.assert_frame_equal(result, exp_df) def test_max_min_non_numeric(): # #2700 aa = DataFrame({"nn": [11, 11, 22, 22], "ii": [1, 2, 3, 4], "ss": 4 * ["mama"]}) result = aa.groupby("nn").max() assert "ss" in result result = aa.groupby("nn").max(numeric_only=False) assert "ss" in result result = aa.groupby("nn").min() assert "ss" in result result = aa.groupby("nn").min(numeric_only=False) assert "ss" in result def test_intercept_builtin_sum(): s = Series([1.0, 2.0, np.nan, 3.0]) grouped = s.groupby([0, 1, 2, 2]) result = grouped.agg(builtins.sum) result2 = grouped.apply(builtins.sum) expected = grouped.sum() tm.assert_series_equal(result, expected) tm.assert_series_equal(result2, expected) # @pytest.mark.parametrize("f", [max, min, sum]) # def test_builtins_apply(f): @pytest.mark.parametrize("f", [max, min, sum]) @pytest.mark.parametrize("keys", ["jim", ["jim", "joe"]]) # Single key # Multi-key def test_builtins_apply(keys, f): # see gh-8155 df = pd.DataFrame(np.random.randint(1, 50, (1000, 2)), columns=["jim", "joe"]) df["jolie"] = np.random.randn(1000) fname = f.__name__ result = df.groupby(keys).apply(f) ngroups = len(df.drop_duplicates(subset=keys)) assert_msg = f"invalid frame shape: {result.shape} (expected ({ngroups}, 3))" assert result.shape == (ngroups, 3), assert_msg tm.assert_frame_equal( result, # numpy's equivalent function df.groupby(keys).apply(getattr(np, fname)), ) if f != sum: expected = df.groupby(keys).agg(fname).reset_index() expected.set_index(keys, inplace=True, drop=False) tm.assert_frame_equal(result, expected, check_dtype=False) tm.assert_series_equal(getattr(result, fname)(), getattr(df, fname)()) def test_arg_passthru(): # make sure that we are passing thru kwargs # to our agg functions # GH3668 # GH5724 df = pd.DataFrame( { "group": [1, 1, 2], "int": [1, 2, 3], "float": [4.0, 5.0, 6.0], "string": list("abc"), "category_string": pd.Series(list("abc")).astype("category"), "category_int": [7, 8, 9], "datetime": pd.date_range("20130101", periods=3), "datetimetz": pd.date_range("20130101", periods=3, tz="US/Eastern"), "timedelta": pd.timedelta_range("1 s", periods=3, freq="s"), }, columns=[ "group", "int", "float", "string", "category_string", "category_int", "datetime", "datetimetz", "timedelta", ], ) expected_columns_numeric = Index(["int", "float", "category_int"]) # mean / median expected = pd.DataFrame( { "category_int": [7.5, 9], "float": [4.5, 6.0], "timedelta": [pd.Timedelta("1.5s"), pd.Timedelta("3s")], "int": [1.5, 3], "datetime": [ pd.Timestamp("2013-01-01 12:00:00"), pd.Timestamp("2013-01-03 00:00:00"), ], "datetimetz": [ pd.Timestamp("2013-01-01 12:00:00", tz="US/Eastern"), pd.Timestamp("2013-01-03 00:00:00", tz="US/Eastern"), ], }, index=Index([1, 2], name="group"), columns=["int", "float", "category_int", "datetime", "datetimetz", "timedelta"], ) for attr in ["mean", "median"]: result = getattr(df.groupby("group"), attr)() tm.assert_index_equal(result.columns, expected_columns_numeric) result = getattr(df.groupby("group"), attr)(numeric_only=False) tm.assert_frame_equal(result.reindex_like(expected), expected) # TODO: min, max *should* handle # categorical (ordered) dtype expected_columns = Index( [ "int", "float", "string", "category_int", "datetime", "datetimetz", "timedelta", ] ) for attr in ["min", "max"]: result = getattr(df.groupby("group"), attr)() tm.assert_index_equal(result.columns, expected_columns) result = getattr(df.groupby("group"), attr)(numeric_only=False) tm.assert_index_equal(result.columns, expected_columns) expected_columns = Index( [ "int", "float", "string", "category_string", "category_int", "datetime", "datetimetz", "timedelta", ] ) for attr in ["first", "last"]: result = getattr(df.groupby("group"), attr)() tm.assert_index_equal(result.columns, expected_columns) result = getattr(df.groupby("group"), attr)(numeric_only=False) tm.assert_index_equal(result.columns, expected_columns) expected_columns = Index(["int", "float", "string", "category_int", "timedelta"]) result = df.groupby("group").sum() tm.assert_index_equal(result.columns, expected_columns_numeric) result = df.groupby("group").sum(numeric_only=False) tm.assert_index_equal(result.columns, expected_columns) expected_columns = Index(["int", "float", "category_int"]) for attr in ["prod", "cumprod"]: result = getattr(df.groupby("group"), attr)() tm.assert_index_equal(result.columns, expected_columns_numeric) result = getattr(df.groupby("group"), attr)(numeric_only=False) tm.assert_index_equal(result.columns, expected_columns) # like min, max, but don't include strings expected_columns = Index( ["int", "float", "category_int", "datetime", "datetimetz", "timedelta"] ) for attr in ["cummin", "cummax"]: result = getattr(df.groupby("group"), attr)() # GH 15561: numeric_only=False set by default like min/max tm.assert_index_equal(result.columns, expected_columns) result = getattr(df.groupby("group"), attr)(numeric_only=False) tm.assert_index_equal(result.columns, expected_columns) expected_columns = Index(["int", "float", "category_int", "timedelta"]) result = getattr(df.groupby("group"), "cumsum")() tm.assert_index_equal(result.columns, expected_columns_numeric) result = getattr(df.groupby("group"), "cumsum")(numeric_only=False) tm.assert_index_equal(result.columns, expected_columns) def test_non_cython_api(): # GH5610 # non-cython calls should not include the grouper df = DataFrame( [[1, 2, "foo"], [1, np.nan, "bar"], [3, np.nan, "baz"]], columns=["A", "B", "C"] ) g = df.groupby("A") gni = df.groupby("A", as_index=False) # mad expected = DataFrame([[0], [np.nan]], columns=["B"], index=[1, 3]) expected.index.name = "A" result = g.mad() tm.assert_frame_equal(result, expected) expected = DataFrame([[0.0, 0.0], [0, np.nan]], columns=["A", "B"], index=[0, 1]) result = gni.mad() tm.assert_frame_equal(result, expected) # describe expected_index = pd.Index([1, 3], name="A") expected_col = pd.MultiIndex( levels=[["B"], ["count", "mean", "std", "min", "25%", "50%", "75%", "max"]], codes=[[0] * 8, list(range(8))], ) expected = pd.DataFrame( [ [1.0, 2.0, np.nan, 2.0, 2.0, 2.0, 2.0, 2.0], [0.0, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan], ], index=expected_index, columns=expected_col, ) result = g.describe() tm.assert_frame_equal(result, expected) expected = pd.concat( [ df[df.A == 1].describe().unstack().to_frame().T, df[df.A == 3].describe().unstack().to_frame().T, ] ) expected.index = pd.Index([0, 1]) result = gni.describe() tm.assert_frame_equal(result, expected) # any expected = DataFrame( [[True, True], [False, True]], columns=["B", "C"], index=[1, 3] ) expected.index.name = "A" result = g.any() tm.assert_frame_equal(result, expected) # idxmax expected = DataFrame([[0.0], [np.nan]], columns=["B"], index=[1, 3]) expected.index.name = "A" result = g.idxmax() tm.assert_frame_equal(result, expected) def test_cython_api2(): # this takes the fast apply path # cumsum (GH5614) df = DataFrame([[1, 2, np.nan], [1, np.nan, 9], [3, 4, 9]], columns=["A", "B", "C"]) expected = DataFrame([[2, np.nan], [np.nan, 9], [4, 9]], columns=["B", "C"]) result = df.groupby("A").cumsum() tm.assert_frame_equal(result, expected) # GH 5755 - cumsum is a transformer and should ignore as_index result = df.groupby("A", as_index=False).cumsum() tm.assert_frame_equal(result, expected) # GH 13994 result = df.groupby("A").cumsum(axis=1) expected = df.cumsum(axis=1) tm.assert_frame_equal(result, expected) result = df.groupby("A").cumprod(axis=1) expected = df.cumprod(axis=1) tm.assert_frame_equal(result, expected) def test_cython_median(): df = DataFrame(np.random.randn(1000)) df.values[::2] = np.nan labels = np.random.randint(0, 50, size=1000).astype(float) labels[::17] = np.nan result = df.groupby(labels).median() exp = df.groupby(labels).agg(nanops.nanmedian) tm.assert_frame_equal(result, exp) df = DataFrame(np.random.randn(1000, 5)) rs = df.groupby(labels).agg(np.median) xp = df.groupby(labels).median() tm.assert_frame_equal(rs, xp) def test_median_empty_bins(observed): df = pd.DataFrame(np.random.randint(0, 44, 500)) grps = range(0, 55, 5) bins = pd.cut(df[0], grps) result = df.groupby(bins, observed=observed).median() expected = df.groupby(bins, observed=observed).agg(lambda x: x.median()) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "dtype", ["int8", "int16", "int32", "int64", "float32", "float64", "uint64"] ) @pytest.mark.parametrize( "method,data", [ ("first", {"df": [{"a": 1, "b": 1}, {"a": 2, "b": 3}]}), ("last", {"df": [{"a": 1, "b": 2}, {"a": 2, "b": 4}]}), ("min", {"df": [{"a": 1, "b": 1}, {"a": 2, "b": 3}]}), ("max", {"df": [{"a": 1, "b": 2}, {"a": 2, "b": 4}]}), ("nth", {"df": [{"a": 1, "b": 2}, {"a": 2, "b": 4}], "args": [1]}), ("count", {"df": [{"a": 1, "b": 2}, {"a": 2, "b": 2}], "out_type": "int64"}), ], ) def test_groupby_non_arithmetic_agg_types(dtype, method, data): # GH9311, GH6620 df = pd.DataFrame( [{"a": 1, "b": 1}, {"a": 1, "b": 2}, {"a": 2, "b": 3}, {"a": 2, "b": 4}] ) df["b"] = df.b.astype(dtype) if "args" not in data: data["args"] = [] if "out_type" in data: out_type = data["out_type"] else: out_type = dtype exp = data["df"] df_out = pd.DataFrame(exp) df_out["b"] = df_out.b.astype(out_type) df_out.set_index("a", inplace=True) grpd = df.groupby("a") t = getattr(grpd, method)(*data["args"]) tm.assert_frame_equal(t, df_out) @pytest.mark.parametrize( "i", [ ( Timestamp("2011-01-15 12:50:28.502376"), Timestamp("2011-01-20 12:50:28.593448"), ), (24650000000000001, 24650000000000002), ], ) def test_groupby_non_arithmetic_agg_int_like_precision(i): # see gh-6620, gh-9311 df = pd.DataFrame([{"a": 1, "b": i[0]}, {"a": 1, "b": i[1]}]) grp_exp = { "first": {"expected": i[0]}, "last": {"expected": i[1]}, "min": {"expected": i[0]}, "max": {"expected": i[1]}, "nth": {"expected": i[1], "args": [1]}, "count": {"expected": 2}, } for method, data in grp_exp.items(): if "args" not in data: data["args"] = [] grouped = df.groupby("a") res = getattr(grouped, method)(*data["args"]) assert res.iloc[0].b == data["expected"] @pytest.mark.parametrize( "func, values", [ ("idxmin", {"c_int": [0, 2], "c_float": [1, 3], "c_date": [1, 2]}), ("idxmax", {"c_int": [1, 3], "c_float": [0, 2], "c_date": [0, 3]}), ], ) def test_idxmin_idxmax_returns_int_types(func, values): # GH 25444 df = pd.DataFrame( { "name": ["A", "A", "B", "B"], "c_int": [1, 2, 3, 4], "c_float": [4.02, 3.03, 2.04, 1.05], "c_date": ["2019", "2018", "2016", "2017"], } ) df["c_date"] = pd.to_datetime(df["c_date"]) result = getattr(df.groupby("name"), func)() expected = pd.DataFrame(values, index=Index(["A", "B"], name="name")) tm.assert_frame_equal(result, expected) def test_fill_consistency(): # GH9221 # pass thru keyword arguments to the generated wrapper # are set if the passed kw is None (only) df = DataFrame( index=pd.MultiIndex.from_product( [["value1", "value2"], date_range("2014-01-01", "2014-01-06")] ), columns=Index(["1", "2"], name="id"), ) df["1"] = [ np.nan, 1, np.nan, np.nan, 11, np.nan, np.nan, 2, np.nan, np.nan, 22, np.nan, ] df["2"] = [ np.nan, 3, np.nan, np.nan, 33, np.nan, np.nan, 4, np.nan, np.nan, 44, np.nan, ] expected = df.groupby(level=0, axis=0).fillna(method="ffill") result = df.T.groupby(level=0, axis=1).fillna(method="ffill").T tm.assert_frame_equal(result, expected) def test_groupby_cumprod(): # GH 4095 df = pd.DataFrame({"key": ["b"] * 10, "value": 2}) actual = df.groupby("key")["value"].cumprod() expected = df.groupby("key")["value"].apply(lambda x: x.cumprod()) expected.name = "value" tm.assert_series_equal(actual, expected) df = pd.DataFrame({"key": ["b"] * 100, "value": 2}) actual = df.groupby("key")["value"].cumprod() # if overflows, groupby product casts to float # while numpy passes back invalid values df["value"] = df["value"].astype(float) expected = df.groupby("key")["value"].apply(lambda x: x.cumprod()) expected.name = "value" tm.assert_series_equal(actual, expected) def scipy_sem(*args, **kwargs): from scipy.stats import sem return sem(*args, ddof=1, **kwargs) @pytest.mark.parametrize( "op,targop", [ ("mean", np.mean), ("median", np.median), ("std", np.std), ("var", np.var), ("sum", np.sum), ("prod", np.prod), ("min", np.min), ("max", np.max), ("first", lambda x: x.iloc[0]), ("last", lambda x: x.iloc[-1]), ("count", np.size), pytest.param("sem", scipy_sem, marks=td.skip_if_no_scipy), ], ) def test_ops_general(op, targop): df = DataFrame(np.random.randn(1000)) labels = np.random.randint(0, 50, size=1000).astype(float) result = getattr(df.groupby(labels), op)().astype(float) expected = df.groupby(labels).agg(targop) tm.assert_frame_equal(result, expected) def test_max_nan_bug(): raw = """,Date,app,File -04-23,2013-04-23 00:00:00,,log080001.log -05-06,2013-05-06 00:00:00,,log.log -05-07,2013-05-07 00:00:00,OE,xlsx""" df = pd.read_csv(StringIO(raw), parse_dates=[0]) gb = df.groupby("Date") r = gb[["File"]].max() e = gb["File"].max().to_frame() tm.assert_frame_equal(r, e) assert not r["File"].isna().any() def test_nlargest(): a = Series([1, 3, 5, 7, 2, 9, 0, 4, 6, 10]) b = Series(list("a" * 5 + "b" * 5)) gb = a.groupby(b) r = gb.nlargest(3) e = Series( [7, 5, 3, 10, 9, 6], index=MultiIndex.from_arrays([list("aaabbb"), [3, 2, 1, 9, 5, 8]]), ) tm.assert_series_equal(r, e) a = Series([1, 1, 3, 2, 0, 3, 3, 2, 1, 0]) gb = a.groupby(b) e = Series( [3, 2, 1, 3, 3, 2], index=MultiIndex.from_arrays([list("aaabbb"), [2, 3, 1, 6, 5, 7]]), ) tm.assert_series_equal(gb.nlargest(3, keep="last"), e) def test_nlargest_mi_grouper(): # see gh-21411 npr = np.random.RandomState(123456789) dts = date_range("20180101", periods=10) iterables = [dts, ["one", "two"]] idx = MultiIndex.from_product(iterables, names=["first", "second"]) s = Series(npr.randn(20), index=idx) result = s.groupby("first").nlargest(1) exp_idx = MultiIndex.from_tuples( [ (dts[0], dts[0], "one"), (dts[1], dts[1], "one"), (dts[2], dts[2], "one"), (dts[3], dts[3], "two"), (dts[4], dts[4], "one"), (dts[5], dts[5], "one"), (dts[6], dts[6], "one"), (dts[7], dts[7], "one"), (dts[8], dts[8], "two"), (dts[9], dts[9], "one"), ], names=["first", "first", "second"], ) exp_values = [ 2.2129019979039612, 1.8417114045748335, 0.858963679564603, 1.3759151378258088, 0.9430284594687134, 0.5296914208183142, 0.8318045593815487, -0.8476703342910327, 0.3804446884133735, -0.8028845810770998, ] expected = Series(exp_values, index=exp_idx) tm.assert_series_equal(result, expected, check_exact=False) def test_nsmallest(): a = Series([1, 3, 5, 7, 2, 9, 0, 4, 6, 10]) b = Series(list("a" * 5 + "b" * 5)) gb = a.groupby(b) r = gb.nsmallest(3) e = Series( [1, 2, 3, 0, 4, 6], index=MultiIndex.from_arrays([list("aaabbb"), [0, 4, 1, 6, 7, 8]]), ) tm.assert_series_equal(r, e) a = Series([1, 1, 3, 2, 0, 3, 3, 2, 1, 0]) gb = a.groupby(b) e = Series( [0, 1, 1, 0, 1, 2], index=MultiIndex.from_arrays([list("aaabbb"), [4, 1, 0, 9, 8, 7]]), ) tm.assert_series_equal(gb.nsmallest(3, keep="last"), e) @pytest.mark.parametrize("func", ["cumprod", "cumsum"]) def test_numpy_compat(func): # see gh-12811 df = pd.DataFrame({"A": [1, 2, 1], "B": [1, 2, 3]}) g = df.groupby("A") msg = "numpy operations are not valid with groupby" with pytest.raises(UnsupportedFunctionCall, match=msg): getattr(g, func)(1, 2, 3) with pytest.raises(UnsupportedFunctionCall, match=msg): getattr(g, func)(foo=1) @pytest.mark.xfail( _is_numpy_dev, reason="https://github.com/pandas-dev/pandas/issues/31992", strict=False, ) def test_cummin(numpy_dtypes_for_minmax): dtype = numpy_dtypes_for_minmax[0] min_val = numpy_dtypes_for_minmax[1] # GH 15048 base_df = pd.DataFrame( {"A": [1, 1, 1, 1, 2, 2, 2, 2], "B": [3, 4, 3, 2, 2, 3, 2, 1]} ) expected_mins = [3, 3, 3, 2, 2, 2, 2, 1] df = base_df.astype(dtype) expected = pd.DataFrame({"B": expected_mins}).astype(dtype) result = df.groupby("A").cummin() tm.assert_frame_equal(result, expected) result = df.groupby("A").B.apply(lambda x: x.cummin()).to_frame() tm.assert_frame_equal(result, expected) # Test w/ min value for dtype df.loc[[2, 6], "B"] = min_val expected.loc[[2, 3, 6, 7], "B"] = min_val result = df.groupby("A").cummin() tm.assert_frame_equal(result, expected) expected = df.groupby("A").B.apply(lambda x: x.cummin()).to_frame() tm.assert_frame_equal(result, expected) # Test nan in some values base_df.loc[[0, 2, 4, 6], "B"] = np.nan expected = pd.DataFrame({"B": [np.nan, 4, np.nan, 2, np.nan, 3, np.nan, 1]}) result = base_df.groupby("A").cummin() tm.assert_frame_equal(result, expected) expected = base_df.groupby("A").B.apply(lambda x: x.cummin()).to_frame() tm.assert_frame_equal(result, expected) # GH 15561 df = pd.DataFrame(dict(a=[1], b=pd.to_datetime(["2001"]))) expected = pd.Series(pd.to_datetime("2001"), index=[0], name="b") result = df.groupby("a")["b"].cummin() tm.assert_series_equal(expected, result) # GH 15635 df = pd.DataFrame(dict(a=[1, 2, 1], b=[1, 2, 2])) result = df.groupby("a").b.cummin() expected = pd.Series([1, 2, 1], name="b") tm.assert_series_equal(result, expected) @pytest.mark.xfail( _is_numpy_dev, reason="https://github.com/pandas-dev/pandas/issues/31992", strict=False, ) def test_cummin_all_nan_column(): base_df = pd.DataFrame({"A": [1, 1, 1, 1, 2, 2, 2, 2], "B": [np.nan] * 8}) expected = pd.DataFrame({"B": [np.nan] * 8}) result = base_df.groupby("A").cummin() tm.assert_frame_equal(expected, result) result = base_df.groupby("A").B.apply(lambda x: x.cummin()).to_frame() tm.assert_frame_equal(expected, result) @pytest.mark.xfail( _is_numpy_dev, reason="https://github.com/pandas-dev/pandas/issues/31992", strict=False, ) def test_cummax(numpy_dtypes_for_minmax): dtype = numpy_dtypes_for_minmax[0] max_val = numpy_dtypes_for_minmax[2] # GH 15048 base_df = pd.DataFrame( {"A": [1, 1, 1, 1, 2, 2, 2, 2], "B": [3, 4, 3, 2, 2, 3, 2, 1]} ) expected_maxs = [3, 4, 4, 4, 2, 3, 3, 3] df = base_df.astype(dtype) expected = pd.DataFrame({"B": expected_maxs}).astype(dtype) result = df.groupby("A").cummax() tm.assert_frame_equal(result, expected) result = df.groupby("A").B.apply(lambda x: x.cummax()).to_frame() tm.assert_frame_equal(result, expected) # Test w/ max value for dtype df.loc[[2, 6], "B"] = max_val expected.loc[[2, 3, 6, 7], "B"] = max_val result = df.groupby("A").cummax() tm.assert_frame_equal(result, expected) expected = df.groupby("A").B.apply(lambda x: x.cummax()).to_frame() tm.assert_frame_equal(result, expected) # Test nan in some values base_df.loc[[0, 2, 4, 6], "B"] = np.nan expected = pd.DataFrame({"B": [np.nan, 4, np.nan, 4, np.nan, 3, np.nan, 3]}) result = base_df.groupby("A").cummax() tm.assert_frame_equal(result, expected) expected = base_df.groupby("A").B.apply(lambda x: x.cummax()).to_frame() tm.assert_frame_equal(result, expected) # GH 15561 df = pd.DataFrame(dict(a=[1], b=pd.to_datetime(["2001"]))) expected = pd.Series(pd.to_datetime("2001"), index=[0], name="b") result = df.groupby("a")["b"].cummax() tm.assert_series_equal(expected, result) # GH 15635 df = pd.DataFrame(dict(a=[1, 2, 1], b=[2, 1, 1])) result = df.groupby("a").b.cummax() expected = pd.Series([2, 1, 2], name="b") tm.assert_series_equal(result, expected) @pytest.mark.xfail( _is_numpy_dev, reason="https://github.com/pandas-dev/pandas/issues/31992", strict=False, ) def test_cummax_all_nan_column(): base_df = pd.DataFrame({"A": [1, 1, 1, 1, 2, 2, 2, 2], "B": [np.nan] * 8}) expected = pd.DataFrame({"B": [np.nan] * 8}) result = base_df.groupby("A").cummax() tm.assert_frame_equal(expected, result) result = base_df.groupby("A").B.apply(lambda x: x.cummax()).to_frame() tm.assert_frame_equal(expected, result) @pytest.mark.parametrize( "in_vals, out_vals", [ # Basics: strictly increasing (T), strictly decreasing (F), # abs val increasing (F), non-strictly increasing (T) ([1, 2, 5, 3, 2, 0, 4, 5, -6, 1, 1], [True, False, False, True]), # Test with inf vals ( [1, 2.1, np.inf, 3, 2, np.inf, -np.inf, 5, 11, 1, -np.inf], [True, False, True, False], ), # Test with nan vals; should always be False ( [1, 2, np.nan, 3, 2, np.nan, np.nan, 5, -np.inf, 1, np.nan], [False, False, False, False], ), ], ) def test_is_monotonic_increasing(in_vals, out_vals): # GH 17015 source_dict = { "A": ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"], "B": ["a", "a", "a", "b", "b", "b", "c", "c", "c", "d", "d"], "C": in_vals, } df = pd.DataFrame(source_dict) result = df.groupby("B").C.is_monotonic_increasing index = Index(list("abcd"), name="B") expected = pd.Series(index=index, data=out_vals, name="C") tm.assert_series_equal(result, expected) # Also check result equal to manually taking x.is_monotonic_increasing. expected = df.groupby(["B"]).C.apply(lambda x: x.is_monotonic_increasing) tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "in_vals, out_vals", [ # Basics: strictly decreasing (T), strictly increasing (F), # abs val decreasing (F), non-strictly increasing (T) ([10, 9, 7, 3, 4, 5, -3, 2, 0, 1, 1], [True, False, False, True]), # Test with inf vals ( [np.inf, 1, -np.inf, np.inf, 2, -3, -np.inf, 5, -3, -np.inf, -np.inf], [True, True, False, True], ), # Test with nan vals; should always be False ( [1, 2, np.nan, 3, 2, np.nan, np.nan, 5, -np.inf, 1, np.nan], [False, False, False, False], ), ], ) def test_is_monotonic_decreasing(in_vals, out_vals): # GH 17015 source_dict = { "A": ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"], "B": ["a", "a", "a", "b", "b", "b", "c", "c", "c", "d", "d"], "C": in_vals, } df = pd.DataFrame(source_dict) result = df.groupby("B").C.is_monotonic_decreasing index = Index(list("abcd"), name="B") expected = pd.Series(index=index, data=out_vals, name="C") tm.assert_series_equal(result, expected) # describe # -------------------------------- def test_apply_describe_bug(mframe): grouped = mframe.groupby(level="first") grouped.describe() # it works! def test_series_describe_multikey(): ts = tm.makeTimeSeries() grouped = ts.groupby([lambda x: x.year, lambda x: x.month]) result = grouped.describe() tm.assert_series_equal(result["mean"], grouped.mean(), check_names=False) tm.assert_series_equal(result["std"], grouped.std(), check_names=False) tm.assert_series_equal(result["min"], grouped.min(), check_names=False) def test_series_describe_single(): ts = tm.makeTimeSeries() grouped = ts.groupby(lambda x: x.month) result = grouped.apply(lambda x: x.describe()) expected = grouped.describe().stack() tm.assert_series_equal(result, expected) def test_series_index_name(df): grouped = df.loc[:, ["C"]].groupby(df["A"]) result = grouped.agg(lambda x: x.mean()) assert result.index.name == "A" def test_frame_describe_multikey(tsframe): grouped = tsframe.groupby([lambda x: x.year, lambda x: x.month]) result = grouped.describe() desc_groups = [] for col in tsframe: group = grouped[col].describe() # GH 17464 - Remove duplicate MultiIndex levels group_col = pd.MultiIndex( levels=[[col], group.columns], codes=[[0] * len(group.columns), range(len(group.columns))], ) group = pd.DataFrame(group.values, columns=group_col, index=group.index) desc_groups.append(group) expected = pd.concat(desc_groups, axis=1) tm.assert_frame_equal(result, expected) groupedT = tsframe.groupby({"A": 0, "B": 0, "C": 1, "D": 1}, axis=1) result = groupedT.describe() expected = tsframe.describe().T expected.index = pd.MultiIndex( levels=[[0, 1], expected.index], codes=[[0, 0, 1, 1], range(len(expected.index))], ) tm.assert_frame_equal(result, expected) def test_frame_describe_tupleindex(): # GH 14848 - regression from 0.19.0 to 0.19.1 df1 = DataFrame( { "x": [1, 2, 3, 4, 5] * 3, "y": [10, 20, 30, 40, 50] * 3, "z": [100, 200, 300, 400, 500] * 3, } ) df1["k"] = [(0, 0, 1), (0, 1, 0), (1, 0, 0)] * 5 df2 = df1.rename(columns={"k": "key"}) msg = "Names should be list-like for a MultiIndex" with pytest.raises(ValueError, match=msg): df1.groupby("k").describe() with pytest.raises(ValueError, match=msg): df2.groupby("key").describe() def test_frame_describe_unstacked_format(): # GH 4792 prices = { pd.Timestamp("2011-01-06 10:59:05", tz=None): 24990, pd.Timestamp("2011-01-06 12:43:33", tz=None): 25499, pd.Timestamp("2011-01-06 12:54:09", tz=None): 25499, } volumes = { pd.Timestamp("2011-01-06 10:59:05", tz=None): 1500000000, pd.Timestamp("2011-01-06 12:43:33", tz=None): 5000000000, pd.Timestamp("2011-01-06 12:54:09", tz=None): 100000000, } df = pd.DataFrame({"PRICE": prices, "VOLUME": volumes}) result = df.groupby("PRICE").VOLUME.describe() data = [ df[df.PRICE == 24990].VOLUME.describe().values.tolist(), df[df.PRICE == 25499].VOLUME.describe().values.tolist(), ] expected = pd.DataFrame( data, index=pd.Index([24990, 25499], name="PRICE"), columns=["count", "mean", "std", "min", "25%", "50%", "75%", "max"], ) tm.assert_frame_equal(result, expected) # nunique # -------------------------------- @pytest.mark.parametrize("n", 10 ** np.arange(2, 6)) @pytest.mark.parametrize("m", [10, 100, 1000]) @pytest.mark.parametrize("sort", [False, True]) @pytest.mark.parametrize("dropna", [False, True]) def test_series_groupby_nunique(n, m, sort, dropna): def check_nunique(df, keys, as_index=True): original_df = df.copy() gr = df.groupby(keys, as_index=as_index, sort=sort) left = gr["julie"].nunique(dropna=dropna) gr = df.groupby(keys, as_index=as_index, sort=sort) right = gr["julie"].apply(Series.nunique, dropna=dropna) if not as_index: right = right.reset_index(drop=True) tm.assert_series_equal(left, right, check_names=False) tm.assert_frame_equal(df, original_df) days = date_range("2015-08-23", periods=10) frame = DataFrame( { "jim": np.random.choice(list(ascii_lowercase), n), "joe": np.random.choice(days, n), "julie": np.random.randint(0, m, n), } ) check_nunique(frame, ["jim"]) check_nunique(frame, ["jim", "joe"]) frame.loc[1::17, "jim"] = None frame.loc[3::37, "joe"] = None frame.loc[7::19, "julie"] = None frame.loc[8::19, "julie"] = None frame.loc[9::19, "julie"] = None check_nunique(frame, ["jim"]) check_nunique(frame, ["jim", "joe"]) check_nunique(frame, ["jim"], as_index=False) check_nunique(frame, ["jim", "joe"], as_index=False) def test_nunique(): df = DataFrame({"A": list("abbacc"), "B": list("abxacc"), "C": list("abbacx")}) expected = DataFrame({"A": [1] * 3, "B": [1, 2, 1], "C": [1, 1, 2]}) result = df.groupby("A", as_index=False).nunique() tm.assert_frame_equal(result, expected) # as_index expected.index = list("abc") expected.index.name = "A" result = df.groupby("A").nunique() tm.assert_frame_equal(result, expected) # with na result = df.replace({"x": None}).groupby("A").nunique(dropna=False) tm.assert_frame_equal(result, expected) # dropna expected = DataFrame({"A": [1] * 3, "B": [1] * 3, "C": [1] * 3}, index=list("abc")) expected.index.name = "A" result = df.replace({"x": None}).groupby("A").nunique() tm.assert_frame_equal(result, expected) def test_nunique_with_object(): # GH 11077 data = pd.DataFrame( [ [100, 1, "Alice"], [200, 2, "Bob"], [300, 3, "Charlie"], [-400, 4, "Dan"], [500, 5, "Edith"], ], columns=["amount", "id", "name"], ) result = data.groupby(["id", "amount"])["name"].nunique() index = MultiIndex.from_arrays([data.id, data.amount]) expected = pd.Series([1] * 5, name="name", index=index) tm.assert_series_equal(result, expected) def test_nunique_with_empty_series(): # GH 12553 data = pd.Series(name="name", dtype=object) result = data.groupby(level=0).nunique() expected = pd.Series(name="name", dtype="int64") tm.assert_series_equal(result, expected) def test_nunique_with_timegrouper(): # GH 13453 test = pd.DataFrame( { "time": [ Timestamp("2016-06-28 09:35:35"), Timestamp("2016-06-28 16:09:30"), Timestamp("2016-06-28 16:46:28"), ], "data": ["1", "2", "3"], } ).set_index("time") result = test.groupby(pd.Grouper(freq="h"))["data"].nunique() expected = test.groupby(pd.Grouper(freq="h"))["data"].apply(pd.Series.nunique) tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "key, data, dropna, expected", [ ( ["x", "x", "x"], [Timestamp("2019-01-01"), NaT, Timestamp("2019-01-01")], True, Series([1], index=pd.Index(["x"], name="key"), name="data"), ), ( ["x", "x", "x"], [dt.date(2019, 1, 1), NaT, dt.date(2019, 1, 1)], True, Series([1], index=pd.Index(["x"], name="key"), name="data"), ), ( ["x", "x", "x", "y", "y"], [dt.date(2019, 1, 1), NaT, dt.date(2019, 1, 1), NaT, dt.date(2019, 1, 1)], False, Series([2, 2], index=pd.Index(["x", "y"], name="key"), name="data"), ), ( ["x", "x", "x", "x", "y"], [dt.date(2019, 1, 1), NaT, dt.date(2019, 1, 1), NaT, dt.date(2019, 1, 1)], False, Series([2, 1], index=pd.Index(["x", "y"], name="key"), name="data"), ), ], ) def test_nunique_with_NaT(key, data, dropna, expected): # GH 27951 df = pd.DataFrame({"key": key, "data": data}) result = df.groupby(["key"])["data"].nunique(dropna=dropna) tm.assert_series_equal(result, expected) def test_nunique_preserves_column_level_names(): # GH 23222 test = pd.DataFrame([1, 2, 2], columns=pd.Index(["A"], name="level_0")) result = test.groupby([0, 0, 0]).nunique() expected = pd.DataFrame([2], columns=test.columns) tm.assert_frame_equal(result, expected) # count # -------------------------------- def test_groupby_timedelta_cython_count(): df = DataFrame( {"g": list("ab" * 2), "delt": np.arange(4).astype("timedelta64[ns]")} ) expected = Series([2, 2], index=pd.Index(["a", "b"], name="g"), name="delt") result = df.groupby("g").delt.count() tm.assert_series_equal(expected, result) def test_count(): n = 1 << 15 dr = date_range("2015-08-30", periods=n // 10, freq="T") df = DataFrame( { "1st": np.random.choice(list(ascii_lowercase), n), "2nd": np.random.randint(0, 5, n), "3rd": np.random.randn(n).round(3), "4th": np.random.randint(-10, 10, n), "5th": np.random.choice(dr, n), "6th": np.random.randn(n).round(3), "7th": np.random.randn(n).round(3), "8th": np.random.choice(dr, n) - np.random.choice(dr, 1), "9th": np.random.choice(list(ascii_lowercase), n), } ) for col in df.columns.drop(["1st", "2nd", "4th"]): df.loc[np.random.choice(n, n // 10), col] = np.nan df["9th"] = df["9th"].astype("category") for key in ["1st", "2nd", ["1st", "2nd"]]: left = df.groupby(key).count() right = df.groupby(key).apply(DataFrame.count).drop(key, axis=1) tm.assert_frame_equal(left, right) def test_count_non_nulls(): # GH#5610 # count counts non-nulls df = pd.DataFrame( [[1, 2, "foo"], [1, np.nan, "bar"], [3, np.nan, np.nan]], columns=["A", "B", "C"], ) count_as = df.groupby("A").count() count_not_as = df.groupby("A", as_index=False).count() expected = DataFrame([[1, 2], [0, 0]], columns=["B", "C"], index=[1, 3]) expected.index.name = "A" tm.assert_frame_equal(count_not_as, expected.reset_index()) tm.assert_frame_equal(count_as, expected) count_B = df.groupby("A")["B"].count() tm.assert_series_equal(count_B, expected["B"]) def test_count_object(): df = pd.DataFrame({"a": ["a"] * 3 + ["b"] * 3, "c": [2] * 3 + [3] * 3}) result = df.groupby("c").a.count() expected = pd.Series([3, 3], index=pd.Index([2, 3], name="c"), name="a") tm.assert_series_equal(result, expected) df = pd.DataFrame({"a": ["a", np.nan, np.nan] + ["b"] * 3, "c": [2] * 3 + [3] * 3}) result = df.groupby("c").a.count() expected = pd.Series([1, 3], index=pd.Index([2, 3], name="c"), name="a") tm.assert_series_equal(result, expected) def test_count_cross_type(): # GH8169 vals = np.hstack( (np.random.randint(0, 5, (100, 2)), np.random.randint(0, 2, (100, 2))) ) df = pd.DataFrame(vals, columns=["a", "b", "c", "d"]) df[df == 2] = np.nan expected = df.groupby(["c", "d"]).count() for t in ["float32", "object"]: df["a"] = df["a"].astype(t) df["b"] = df["b"].astype(t) result = df.groupby(["c", "d"]).count() tm.assert_frame_equal(result, expected) def test_lower_int_prec_count(): df = DataFrame( { "a": np.array([0, 1, 2, 100], np.int8), "b": np.array([1, 2, 3, 6], np.uint32), "c": np.array([4, 5, 6, 8], np.int16), "grp": list("ab" * 2), } ) result = df.groupby("grp").count() expected = DataFrame( {"a": [2, 2], "b": [2, 2], "c": [2, 2]}, index=pd.Index(list("ab"), name="grp") ) tm.assert_frame_equal(result, expected) def test_count_uses_size_on_exception(): class RaisingObjectException(Exception): pass class RaisingObject: def __init__(self, msg="I will raise inside Cython"): super().__init__() self.msg = msg def __eq__(self, other): # gets called in Cython to check that raising calls the method raise RaisingObjectException(self.msg) df = DataFrame({"a": [RaisingObject() for _ in range(4)], "grp": list("ab" * 2)}) result = df.groupby("grp").count() expected = DataFrame({"a": [2, 2]}, index=pd.Index(list("ab"), name="grp")) tm.assert_frame_equal(result, expected) # size # -------------------------------- @pytest.mark.parametrize("by", ["A", "B", ["A", "B"]]) def test_size(df, by): grouped = df.groupby(by=by) result = grouped.size() for key, group in grouped: assert result[key] == len(group) @pytest.mark.parametrize("by", ["A", "B", ["A", "B"]]) @pytest.mark.parametrize("sort", [True, False]) def test_size_sort(df, sort, by): df = DataFrame(np.random.choice(20, (1000, 3)), columns=list("ABC")) left = df.groupby(by=by, sort=sort).size() right = df.groupby(by=by, sort=sort)["C"].apply(lambda a: a.shape[0]) tm.assert_series_equal(left, right, check_names=False) def test_size_series_dataframe(): # https://github.com/pandas-dev/pandas/issues/11699 df = DataFrame(columns=["A", "B"]) out = Series(dtype="int64", index=Index([], name="A")) tm.assert_series_equal(df.groupby("A").size(), out) def test_size_groupby_all_null(): # https://github.com/pandas-dev/pandas/issues/23050 # Assert no 'Value Error : Length of passed values is 2, index implies 0' df = DataFrame({"A": [None, None]}) # all-null groups result = df.groupby("A").size() expected = Series(dtype="int64", index=Index([], name="A")) tm.assert_series_equal(result, expected) # quantile # -------------------------------- @pytest.mark.parametrize( "interpolation", ["linear", "lower", "higher", "nearest", "midpoint"] ) @pytest.mark.parametrize( "a_vals,b_vals", [ # Ints ([1, 2, 3, 4, 5], [5, 4, 3, 2, 1]), ([1, 2, 3, 4], [4, 3, 2, 1]), ([1, 2, 3, 4, 5], [4, 3, 2, 1]), # Floats ([1.0, 2.0, 3.0, 4.0, 5.0], [5.0, 4.0, 3.0, 2.0, 1.0]), # Missing data ([1.0, np.nan, 3.0, np.nan, 5.0], [5.0, np.nan, 3.0, np.nan, 1.0]), ([np.nan, 4.0, np.nan, 2.0, np.nan], [np.nan, 4.0, np.nan, 2.0, np.nan]), # Timestamps ( list(pd.date_range("1/1/18", freq="D", periods=5)), list(pd.date_range("1/1/18", freq="D", periods=5))[::-1], ), # All NA ([np.nan] * 5, [np.nan] * 5), ], ) @pytest.mark.parametrize("q", [0, 0.25, 0.5, 0.75, 1]) def test_quantile(interpolation, a_vals, b_vals, q): if interpolation == "nearest" and q == 0.5 and b_vals == [4, 3, 2, 1]: pytest.skip( "Unclear numpy expectation for nearest result with equidistant data" ) a_expected = pd.Series(a_vals).quantile(q, interpolation=interpolation) b_expected = pd.Series(b_vals).quantile(q, interpolation=interpolation) df = DataFrame( {"key": ["a"] * len(a_vals) + ["b"] * len(b_vals), "val": a_vals + b_vals} ) expected = DataFrame( [a_expected, b_expected], columns=["val"], index=Index(["a", "b"], name="key") ) result = df.groupby("key").quantile(q, interpolation=interpolation) tm.assert_frame_equal(result, expected) def test_quantile_array(): # https://github.com/pandas-dev/pandas/issues/27526 df = pd.DataFrame({"A": [0, 1, 2, 3, 4]}) result = df.groupby([0, 0, 1, 1, 1]).quantile([0.25]) index = pd.MultiIndex.from_product([[0, 1], [0.25]]) expected = pd.DataFrame({"A": [0.25, 2.50]}, index=index) tm.assert_frame_equal(result, expected) df = pd.DataFrame({"A": [0, 1, 2, 3], "B": [4, 5, 6, 7]}) index = pd.MultiIndex.from_product([[0, 1], [0.25, 0.75]]) result = df.groupby([0, 0, 1, 1]).quantile([0.25, 0.75]) expected = pd.DataFrame( {"A": [0.25, 0.75, 2.25, 2.75], "B": [4.25, 4.75, 6.25, 6.75]}, index=index ) tm.assert_frame_equal(result, expected) def test_quantile_array2(): # https://github.com/pandas-dev/pandas/pull/28085#issuecomment-524066959 df = pd.DataFrame( np.random.RandomState(0).randint(0, 5, size=(10, 3)), columns=list("ABC") ) result = df.groupby("A").quantile([0.3, 0.7]) expected = pd.DataFrame( { "B": [0.9, 2.1, 2.2, 3.4, 1.6, 2.4, 2.3, 2.7, 0.0, 0.0], "C": [1.2, 2.8, 1.8, 3.0, 0.0, 0.0, 1.9, 3.1, 3.0, 3.0], }, index=pd.MultiIndex.from_product( [[0, 1, 2, 3, 4], [0.3, 0.7]], names=["A", None] ), ) tm.assert_frame_equal(result, expected) def test_quantile_array_no_sort(): df = pd.DataFrame({"A": [0, 1, 2], "B": [3, 4, 5]}) result = df.groupby([1, 0, 1], sort=False).quantile([0.25, 0.5, 0.75]) expected = pd.DataFrame( {"A": [0.5, 1.0, 1.5, 1.0, 1.0, 1.0], "B": [3.5, 4.0, 4.5, 4.0, 4.0, 4.0]}, index=pd.MultiIndex.from_product([[1, 0], [0.25, 0.5, 0.75]]), ) tm.assert_frame_equal(result, expected) result = df.groupby([1, 0, 1], sort=False).quantile([0.75, 0.25]) expected = pd.DataFrame( {"A": [1.5, 0.5, 1.0, 1.0], "B": [4.5, 3.5, 4.0, 4.0]}, index=pd.MultiIndex.from_product([[1, 0], [0.75, 0.25]]), ) tm.assert_frame_equal(result, expected) def test_quantile_array_multiple_levels(): df = pd.DataFrame( {"A": [0, 1, 2], "B": [3, 4, 5], "c": ["a", "a", "a"], "d": ["a", "a", "b"]} ) result = df.groupby(["c", "d"]).quantile([0.25, 0.75]) index = pd.MultiIndex.from_tuples( [("a", "a", 0.25), ("a", "a", 0.75), ("a", "b", 0.25), ("a", "b", 0.75)], names=["c", "d", None], ) expected = pd.DataFrame( {"A": [0.25, 0.75, 2.0, 2.0], "B": [3.25, 3.75, 5.0, 5.0]}, index=index ) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("frame_size", [(2, 3), (100, 10)]) @pytest.mark.parametrize("groupby", [[0], [0, 1]]) @pytest.mark.parametrize("q", [[0.5, 0.6]]) def test_groupby_quantile_with_arraylike_q_and_int_columns(frame_size, groupby, q): # GH30289 nrow, ncol = frame_size df = pd.DataFrame( np.array([ncol * [_ % 4] for _ in range(nrow)]), columns=range(ncol) ) idx_levels = [list(range(min(nrow, 4)))] * len(groupby) + [q] idx_codes = [[x for x in range(min(nrow, 4)) for _ in q]] * len(groupby) + [ list(range(len(q))) * min(nrow, 4) ] expected_index = pd.MultiIndex( levels=idx_levels, codes=idx_codes, names=groupby + [None] ) expected_values = [ [float(x)] * (ncol - len(groupby)) for x in range(min(nrow, 4)) for _ in q ] expected_columns = [x for x in range(ncol) if x not in groupby] expected = pd.DataFrame( expected_values, index=expected_index, columns=expected_columns ) result = df.groupby(groupby).quantile(q) tm.assert_frame_equal(result, expected) def test_quantile_raises(): df = pd.DataFrame( [["foo", "a"], ["foo", "b"], ["foo", "c"]], columns=["key", "val"] ) with pytest.raises(TypeError, match="cannot be performed against 'object' dtypes"): df.groupby("key").quantile() def test_quantile_out_of_bounds_q_raises(): # https://github.com/pandas-dev/pandas/issues/27470 df = pd.DataFrame(dict(a=[0, 0, 0, 1, 1, 1], b=range(6))) g = df.groupby([0, 0, 0, 1, 1, 1]) with pytest.raises(ValueError, match="Got '50.0' instead"): g.quantile(50) with pytest.raises(ValueError, match="Got '-1.0' instead"): g.quantile(-1) def test_quantile_missing_group_values_no_segfaults(): # GH 28662 data = np.array([1.0, np.nan, 1.0]) df = pd.DataFrame(dict(key=data, val=range(3))) # Random segfaults; would have been guaranteed in loop grp = df.groupby("key") for _ in range(100): grp.quantile() def test_quantile_missing_group_values_correct_results(): # GH 28662 data = np.array([1.0, np.nan, 3.0, np.nan]) df = pd.DataFrame(dict(key=data, val=range(4))) result = df.groupby("key").quantile() expected = pd.DataFrame( [1.0, 3.0], index=pd.Index([1.0, 3.0], name="key"), columns=["val"] ) tm.assert_frame_equal(result, expected) # pipe # -------------------------------- def test_pipe(): # Test the pipe method of DataFrameGroupBy. # Issue #17871 random_state = np.random.RandomState(1234567890) df = DataFrame( { "A": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "foo"], "B": random_state.randn(8), "C": random_state.randn(8), } ) def f(dfgb): return dfgb.B.max() - dfgb.C.min().min() def square(srs): return srs ** 2 # Note that the transformations are # GroupBy -> Series # Series -> Series # This then chains the GroupBy.pipe and the # NDFrame.pipe methods result = df.groupby("A").pipe(f).pipe(square) index = Index(["bar", "foo"], dtype="object", name="A") expected = pd.Series([8.99110003361, 8.17516964785], name="B", index=index) tm.assert_series_equal(expected, result) def test_pipe_args(): # Test passing args to the pipe method of DataFrameGroupBy. # Issue #17871 df = pd.DataFrame( { "group": ["A", "A", "B", "B", "C"], "x": [1.0, 2.0, 3.0, 2.0, 5.0], "y": [10.0, 100.0, 1000.0, -100.0, -1000.0], } ) def f(dfgb, arg1): return dfgb.filter(lambda grp: grp.y.mean() > arg1, dropna=False).groupby( dfgb.grouper ) def g(dfgb, arg2): return dfgb.sum() / dfgb.sum().sum() + arg2 def h(df, arg3): return df.x + df.y - arg3 result = df.groupby("group").pipe(f, 0).pipe(g, 10).pipe(h, 100) # Assert the results here index = pd.Index(["A", "B", "C"], name="group") expected = pd.Series([-79.5160891089, -78.4839108911, -80], index=index) tm.assert_series_equal(expected, result) # test SeriesGroupby.pipe ser = pd.Series([1, 1, 2, 2, 3, 3]) result = ser.groupby(ser).pipe(lambda grp: grp.sum() * grp.count()) expected = pd.Series([4, 8, 12], index=pd.Int64Index([1, 2, 3])) tm.assert_series_equal(result, expected) def test_groupby_mean_no_overflow(): # Regression test for (#22487) df = pd.DataFrame( { "user": ["A", "A", "A", "A", "A"], "connections": [4970, 4749, 4719, 4704, 18446744073699999744], } ) assert df.groupby("user")["connections"].mean()["A"] == 3689348814740003840
import builtins import datetime as dt from io import StringIO from string import ascii_lowercase import numpy as np import pytest from pandas.errors import UnsupportedFunctionCall import pandas as pd from pandas import ( DataFrame, Index, MultiIndex, NaT, Series, Timestamp, _is_numpy_dev, date_range, isna, ) import pandas._testing as tm import pandas.core.nanops as nanops from pandas.util import _test_decorators as td @pytest.fixture( params=[np.int32, np.int64, np.float32, np.float64], ids=["np.int32", "np.int64", "np.float32", "np.float64"], ) def numpy_dtypes_for_minmax(request): """ Fixture of numpy dtypes with min and max values used for testing cummin and cummax """ dtype = request.param min_val = ( np.iinfo(dtype).min if np.dtype(dtype).kind == "i" else np.finfo(dtype).min ) max_val = ( np.iinfo(dtype).max if np.dtype(dtype).kind == "i" else np.finfo(dtype).max ) return (dtype, min_val, max_val) @pytest.mark.parametrize("agg_func", ["any", "all"]) @pytest.mark.parametrize("skipna", [True, False]) @pytest.mark.parametrize( "vals", [ ["foo", "bar", "baz"], ["foo", "", ""], ["", "", ""], [1, 2, 3], [1, 0, 0], [0, 0, 0], [1.0, 2.0, 3.0], [1.0, 0.0, 0.0], [0.0, 0.0, 0.0], [True, True, True], [True, False, False], [False, False, False], [np.nan, np.nan, np.nan], ], ) def test_groupby_bool_aggs(agg_func, skipna, vals): df = DataFrame({"key": ["a"] * 3 + ["b"] * 3, "val": vals * 2}) # Figure out expectation using Python builtin exp = getattr(builtins, agg_func)(vals) # edge case for missing data with skipna and 'any' if skipna and all(isna(vals)) and agg_func == "any": exp = False exp_df = DataFrame([exp] * 2, columns=["val"], index=Index(["a", "b"], name="key")) result = getattr(df.groupby("key"), agg_func)(skipna=skipna) tm.assert_frame_equal(result, exp_df) def test_max_min_non_numeric(): # #2700 aa = DataFrame({"nn": [11, 11, 22, 22], "ii": [1, 2, 3, 4], "ss": 4 * ["mama"]}) result = aa.groupby("nn").max() assert "ss" in result result = aa.groupby("nn").max(numeric_only=False) assert "ss" in result result = aa.groupby("nn").min() assert "ss" in result result = aa.groupby("nn").min(numeric_only=False) assert "ss" in result def test_intercept_builtin_sum(): s = Series([1.0, 2.0, np.nan, 3.0]) grouped = s.groupby([0, 1, 2, 2]) result = grouped.agg(builtins.sum) result2 = grouped.apply(builtins.sum) expected = grouped.sum() tm.assert_series_equal(result, expected) tm.assert_series_equal(result2, expected) # @pytest.mark.parametrize("f", [max, min, sum]) # def test_builtins_apply(f): @pytest.mark.parametrize("f", [max, min, sum]) @pytest.mark.parametrize("keys", ["jim", ["jim", "joe"]]) # Single key # Multi-key def test_builtins_apply(keys, f): # see gh-8155 df = pd.DataFrame(np.random.randint(1, 50, (1000, 2)), columns=["jim", "joe"]) df["jolie"] = np.random.randn(1000) fname = f.__name__ result = df.groupby(keys).apply(f) ngroups = len(df.drop_duplicates(subset=keys)) assert_msg = f"invalid frame shape: {result.shape} (expected ({ngroups}, 3))" assert result.shape == (ngroups, 3), assert_msg tm.assert_frame_equal( result, # numpy's equivalent function df.groupby(keys).apply(getattr(np, fname)), ) if f != sum: expected = df.groupby(keys).agg(fname).reset_index() expected.set_index(keys, inplace=True, drop=False) tm.assert_frame_equal(result, expected, check_dtype=False) tm.assert_series_equal(getattr(result, fname)(), getattr(df, fname)()) def test_arg_passthru(): # make sure that we are passing thru kwargs # to our agg functions # GH3668 # GH5724 df = pd.DataFrame( { "group": [1, 1, 2], "int": [1, 2, 3], "float": [4.0, 5.0, 6.0], "string": list("abc"), "category_string": pd.Series(list("abc")).astype("category"), "category_int": [7, 8, 9], "datetime": pd.date_range("20130101", periods=3), "datetimetz": pd.date_range("20130101", periods=3, tz="US/Eastern"), "timedelta": pd.timedelta_range("1 s", periods=3, freq="s"), }, columns=[ "group", "int", "float", "string", "category_string", "category_int", "datetime", "datetimetz", "timedelta", ], ) expected_columns_numeric = Index(["int", "float", "category_int"]) # mean / median expected = pd.DataFrame( { "category_int": [7.5, 9], "float": [4.5, 6.0], "timedelta": [pd.Timedelta("1.5s"), pd.Timedelta("3s")], "int": [1.5, 3], "datetime": [ pd.Timestamp("2013-01-01 12:00:00"), pd.Timestamp("2013-01-03 00:00:00"), ], "datetimetz": [ pd.Timestamp("2013-01-01 12:00:00", tz="US/Eastern"), pd.Timestamp("2013-01-03 00:00:00", tz="US/Eastern"), ], }, index=Index([1, 2], name="group"), columns=["int", "float", "category_int", "datetime", "datetimetz", "timedelta"], ) for attr in ["mean", "median"]: result = getattr(df.groupby("group"), attr)() tm.assert_index_equal(result.columns, expected_columns_numeric) result = getattr(df.groupby("group"), attr)(numeric_only=False) tm.assert_frame_equal(result.reindex_like(expected), expected) # TODO: min, max *should* handle # categorical (ordered) dtype expected_columns = Index( [ "int", "float", "string", "category_int", "datetime", "datetimetz", "timedelta", ] ) for attr in ["min", "max"]: result = getattr(df.groupby("group"), attr)() tm.assert_index_equal(result.columns, expected_columns) result = getattr(df.groupby("group"), attr)(numeric_only=False) tm.assert_index_equal(result.columns, expected_columns) expected_columns = Index( [ "int", "float", "string", "category_string", "category_int", "datetime", "datetimetz", "timedelta", ] ) for attr in ["first", "last"]: result = getattr(df.groupby("group"), attr)() tm.assert_index_equal(result.columns, expected_columns) result = getattr(df.groupby("group"), attr)(numeric_only=False) tm.assert_index_equal(result.columns, expected_columns) expected_columns = Index(["int", "float", "string", "category_int", "timedelta"]) result = df.groupby("group").sum() tm.assert_index_equal(result.columns, expected_columns_numeric) result = df.groupby("group").sum(numeric_only=False) tm.assert_index_equal(result.columns, expected_columns) expected_columns = Index(["int", "float", "category_int"]) for attr in ["prod", "cumprod"]: result = getattr(df.groupby("group"), attr)() tm.assert_index_equal(result.columns, expected_columns_numeric) result = getattr(df.groupby("group"), attr)(numeric_only=False) tm.assert_index_equal(result.columns, expected_columns) # like min, max, but don't include strings expected_columns = Index( ["int", "float", "category_int", "datetime", "datetimetz", "timedelta"] ) for attr in ["cummin", "cummax"]: result = getattr(df.groupby("group"), attr)() # GH 15561: numeric_only=False set by default like min/max tm.assert_index_equal(result.columns, expected_columns) result = getattr(df.groupby("group"), attr)(numeric_only=False) tm.assert_index_equal(result.columns, expected_columns) expected_columns = Index(["int", "float", "category_int", "timedelta"]) result = getattr(df.groupby("group"), "cumsum")() tm.assert_index_equal(result.columns, expected_columns_numeric) result = getattr(df.groupby("group"), "cumsum")(numeric_only=False) tm.assert_index_equal(result.columns, expected_columns) def test_non_cython_api(): # GH5610 # non-cython calls should not include the grouper df = DataFrame( [[1, 2, "foo"], [1, np.nan, "bar"], [3, np.nan, "baz"]], columns=["A", "B", "C"] ) g = df.groupby("A") gni = df.groupby("A", as_index=False) # mad expected = DataFrame([[0], [np.nan]], columns=["B"], index=[1, 3]) expected.index.name = "A" result = g.mad() tm.assert_frame_equal(result, expected) expected = DataFrame([[0.0, 0.0], [0, np.nan]], columns=["A", "B"], index=[0, 1]) result = gni.mad() tm.assert_frame_equal(result, expected) # describe expected_index = pd.Index([1, 3], name="A") expected_col = pd.MultiIndex( levels=[["B"], ["count", "mean", "std", "min", "25%", "50%", "75%", "max"]], codes=[[0] * 8, list(range(8))], ) expected = pd.DataFrame( [ [1.0, 2.0, np.nan, 2.0, 2.0, 2.0, 2.0, 2.0], [0.0, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan], ], index=expected_index, columns=expected_col, ) result = g.describe() tm.assert_frame_equal(result, expected) expected = pd.concat( [ df[df.A == 1].describe().unstack().to_frame().T, df[df.A == 3].describe().unstack().to_frame().T, ] ) expected.index = pd.Index([0, 1]) result = gni.describe() tm.assert_frame_equal(result, expected) # any expected = DataFrame( [[True, True], [False, True]], columns=["B", "C"], index=[1, 3] ) expected.index.name = "A" result = g.any() tm.assert_frame_equal(result, expected) # idxmax expected = DataFrame([[0.0], [np.nan]], columns=["B"], index=[1, 3]) expected.index.name = "A" result = g.idxmax() tm.assert_frame_equal(result, expected) def test_cython_api2(): # this takes the fast apply path # cumsum (GH5614) df = DataFrame([[1, 2, np.nan], [1, np.nan, 9], [3, 4, 9]], columns=["A", "B", "C"]) expected = DataFrame([[2, np.nan], [np.nan, 9], [4, 9]], columns=["B", "C"]) result = df.groupby("A").cumsum() tm.assert_frame_equal(result, expected) # GH 5755 - cumsum is a transformer and should ignore as_index result = df.groupby("A", as_index=False).cumsum() tm.assert_frame_equal(result, expected) # GH 13994 result = df.groupby("A").cumsum(axis=1) expected = df.cumsum(axis=1) tm.assert_frame_equal(result, expected) result = df.groupby("A").cumprod(axis=1) expected = df.cumprod(axis=1) tm.assert_frame_equal(result, expected) def test_cython_median(): df = DataFrame(np.random.randn(1000)) df.values[::2] = np.nan labels = np.random.randint(0, 50, size=1000).astype(float) labels[::17] = np.nan result = df.groupby(labels).median() exp = df.groupby(labels).agg(nanops.nanmedian) tm.assert_frame_equal(result, exp) df = DataFrame(np.random.randn(1000, 5)) rs = df.groupby(labels).agg(np.median) xp = df.groupby(labels).median() tm.assert_frame_equal(rs, xp) def test_median_empty_bins(observed): df = pd.DataFrame(np.random.randint(0, 44, 500)) grps = range(0, 55, 5) bins = pd.cut(df[0], grps) result = df.groupby(bins, observed=observed).median() expected = df.groupby(bins, observed=observed).agg(lambda x: x.median()) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "dtype", ["int8", "int16", "int32", "int64", "float32", "float64", "uint64"] ) @pytest.mark.parametrize( "method,data", [ ("first", {"df": [{"a": 1, "b": 1}, {"a": 2, "b": 3}]}), ("last", {"df": [{"a": 1, "b": 2}, {"a": 2, "b": 4}]}), ("min", {"df": [{"a": 1, "b": 1}, {"a": 2, "b": 3}]}), ("max", {"df": [{"a": 1, "b": 2}, {"a": 2, "b": 4}]}), ("nth", {"df": [{"a": 1, "b": 2}, {"a": 2, "b": 4}], "args": [1]}), ("count", {"df": [{"a": 1, "b": 2}, {"a": 2, "b": 2}], "out_type": "int64"}), ], ) def test_groupby_non_arithmetic_agg_types(dtype, method, data): # GH9311, GH6620 df = pd.DataFrame( [{"a": 1, "b": 1}, {"a": 1, "b": 2}, {"a": 2, "b": 3}, {"a": 2, "b": 4}] ) df["b"] = df.b.astype(dtype) if "args" not in data: data["args"] = [] if "out_type" in data: out_type = data["out_type"] else: out_type = dtype exp = data["df"] df_out = pd.DataFrame(exp) df_out["b"] = df_out.b.astype(out_type) df_out.set_index("a", inplace=True) grpd = df.groupby("a") t = getattr(grpd, method)(*data["args"]) tm.assert_frame_equal(t, df_out) @pytest.mark.parametrize( "i", [ ( Timestamp("2011-01-15 12:50:28.502376"), Timestamp("2011-01-20 12:50:28.593448"), ), (24650000000000001, 24650000000000002), ], ) def test_groupby_non_arithmetic_agg_int_like_precision(i): # see gh-6620, gh-9311 df = pd.DataFrame([{"a": 1, "b": i[0]}, {"a": 1, "b": i[1]}]) grp_exp = { "first": {"expected": i[0]}, "last": {"expected": i[1]}, "min": {"expected": i[0]}, "max": {"expected": i[1]}, "nth": {"expected": i[1], "args": [1]}, "count": {"expected": 2}, } for method, data in grp_exp.items(): if "args" not in data: data["args"] = [] grouped = df.groupby("a") res = getattr(grouped, method)(*data["args"]) assert res.iloc[0].b == data["expected"] @pytest.mark.parametrize( "func, values", [ ("idxmin", {"c_int": [0, 2], "c_float": [1, 3], "c_date": [1, 2]}), ("idxmax", {"c_int": [1, 3], "c_float": [0, 2], "c_date": [0, 3]}), ], ) def test_idxmin_idxmax_returns_int_types(func, values): # GH 25444 df = pd.DataFrame( { "name": ["A", "A", "B", "B"], "c_int": [1, 2, 3, 4], "c_float": [4.02, 3.03, 2.04, 1.05], "c_date": ["2019", "2018", "2016", "2017"], } ) df["c_date"] = pd.to_datetime(df["c_date"]) result = getattr(df.groupby("name"), func)() expected = pd.DataFrame(values, index=Index(["A", "B"], name="name")) tm.assert_frame_equal(result, expected) def test_fill_consistency(): # GH9221 # pass thru keyword arguments to the generated wrapper # are set if the passed kw is None (only) df = DataFrame( index=pd.MultiIndex.from_product( [["value1", "value2"], date_range("2014-01-01", "2014-01-06")] ), columns=Index(["1", "2"], name="id"), ) df["1"] = [ np.nan, 1, np.nan, np.nan, 11, np.nan, np.nan, 2, np.nan, np.nan, 22, np.nan, ] df["2"] = [ np.nan, 3, np.nan, np.nan, 33, np.nan, np.nan, 4, np.nan, np.nan, 44, np.nan, ] expected = df.groupby(level=0, axis=0).fillna(method="ffill") result = df.T.groupby(level=0, axis=1).fillna(method="ffill").T tm.assert_frame_equal(result, expected) def test_groupby_cumprod(): # GH 4095 df = pd.DataFrame({"key": ["b"] * 10, "value": 2}) actual = df.groupby("key")["value"].cumprod() expected = df.groupby("key")["value"].apply(lambda x: x.cumprod()) expected.name = "value" tm.assert_series_equal(actual, expected) df = pd.DataFrame({"key": ["b"] * 100, "value": 2}) actual = df.groupby("key")["value"].cumprod() # if overflows, groupby product casts to float # while numpy passes back invalid values df["value"] = df["value"].astype(float) expected = df.groupby("key")["value"].apply(lambda x: x.cumprod()) expected.name = "value" tm.assert_series_equal(actual, expected) def scipy_sem(*args, **kwargs): from scipy.stats import sem return sem(*args, ddof=1, **kwargs) @pytest.mark.parametrize( "op,targop", [ ("mean", np.mean), ("median", np.median), ("std", np.std), ("var", np.var), ("sum", np.sum), ("prod", np.prod), ("min", np.min), ("max", np.max), ("first", lambda x: x.iloc[0]), ("last", lambda x: x.iloc[-1]), ("count", np.size), pytest.param("sem", scipy_sem, marks=td.skip_if_no_scipy), ], ) def test_ops_general(op, targop): df = DataFrame(np.random.randn(1000)) labels = np.random.randint(0, 50, size=1000).astype(float) result = getattr(df.groupby(labels), op)().astype(float) expected = df.groupby(labels).agg(targop) tm.assert_frame_equal(result, expected) def test_max_nan_bug(): raw = """,Date,app,File -04-23,2013-04-23 00:00:00,,log080001.log -05-06,2013-05-06 00:00:00,,log.log -05-07,2013-05-07 00:00:00,OE,xlsx""" df = pd.read_csv(StringIO(raw), parse_dates=[0]) gb = df.groupby("Date") r = gb[["File"]].max() e = gb["File"].max().to_frame() tm.assert_frame_equal(r, e) assert not r["File"].isna().any() def test_nlargest(): a = Series([1, 3, 5, 7, 2, 9, 0, 4, 6, 10]) b = Series(list("a" * 5 + "b" * 5)) gb = a.groupby(b) r = gb.nlargest(3) e = Series( [7, 5, 3, 10, 9, 6], index=MultiIndex.from_arrays([list("aaabbb"), [3, 2, 1, 9, 5, 8]]), ) tm.assert_series_equal(r, e) a = Series([1, 1, 3, 2, 0, 3, 3, 2, 1, 0]) gb = a.groupby(b) e = Series( [3, 2, 1, 3, 3, 2], index=MultiIndex.from_arrays([list("aaabbb"), [2, 3, 1, 6, 5, 7]]), ) tm.assert_series_equal(gb.nlargest(3, keep="last"), e) def test_nlargest_mi_grouper(): # see gh-21411 npr = np.random.RandomState(123456789) dts = date_range("20180101", periods=10) iterables = [dts, ["one", "two"]] idx = MultiIndex.from_product(iterables, names=["first", "second"]) s = Series(npr.randn(20), index=idx) result = s.groupby("first").nlargest(1) exp_idx = MultiIndex.from_tuples( [ (dts[0], dts[0], "one"), (dts[1], dts[1], "one"), (dts[2], dts[2], "one"), (dts[3], dts[3], "two"), (dts[4], dts[4], "one"), (dts[5], dts[5], "one"), (dts[6], dts[6], "one"), (dts[7], dts[7], "one"), (dts[8], dts[8], "two"), (dts[9], dts[9], "one"), ], names=["first", "first", "second"], ) exp_values = [ 2.2129019979039612, 1.8417114045748335, 0.858963679564603, 1.3759151378258088, 0.9430284594687134, 0.5296914208183142, 0.8318045593815487, -0.8476703342910327, 0.3804446884133735, -0.8028845810770998, ] expected = Series(exp_values, index=exp_idx) tm.assert_series_equal(result, expected, check_exact=False) def test_nsmallest(): a = Series([1, 3, 5, 7, 2, 9, 0, 4, 6, 10]) b = Series(list("a" * 5 + "b" * 5)) gb = a.groupby(b) r = gb.nsmallest(3) e = Series( [1, 2, 3, 0, 4, 6], index=MultiIndex.from_arrays([list("aaabbb"), [0, 4, 1, 6, 7, 8]]), ) tm.assert_series_equal(r, e) a = Series([1, 1, 3, 2, 0, 3, 3, 2, 1, 0]) gb = a.groupby(b) e = Series( [0, 1, 1, 0, 1, 2], index=MultiIndex.from_arrays([list("aaabbb"), [4, 1, 0, 9, 8, 7]]), ) tm.assert_series_equal(gb.nsmallest(3, keep="last"), e) @pytest.mark.parametrize("func", ["cumprod", "cumsum"]) def test_numpy_compat(func): # see gh-12811 df = pd.DataFrame({"A": [1, 2, 1], "B": [1, 2, 3]}) g = df.groupby("A") msg = "numpy operations are not valid with groupby" with pytest.raises(UnsupportedFunctionCall, match=msg): getattr(g, func)(1, 2, 3) with pytest.raises(UnsupportedFunctionCall, match=msg): getattr(g, func)(foo=1) @pytest.mark.xfail( _is_numpy_dev, reason="https://github.com/pandas-dev/pandas/issues/31992", strict=False, ) def test_cummin(numpy_dtypes_for_minmax): dtype = numpy_dtypes_for_minmax[0] min_val = numpy_dtypes_for_minmax[1] # GH 15048 base_df = pd.DataFrame( {"A": [1, 1, 1, 1, 2, 2, 2, 2], "B": [3, 4, 3, 2, 2, 3, 2, 1]} ) expected_mins = [3, 3, 3, 2, 2, 2, 2, 1] df = base_df.astype(dtype) expected = pd.DataFrame({"B": expected_mins}).astype(dtype) result = df.groupby("A").cummin() tm.assert_frame_equal(result, expected) result = df.groupby("A").B.apply(lambda x: x.cummin()).to_frame() tm.assert_frame_equal(result, expected) # Test w/ min value for dtype df.loc[[2, 6], "B"] = min_val expected.loc[[2, 3, 6, 7], "B"] = min_val result = df.groupby("A").cummin() tm.assert_frame_equal(result, expected) expected = df.groupby("A").B.apply(lambda x: x.cummin()).to_frame() tm.assert_frame_equal(result, expected) # Test nan in some values base_df.loc[[0, 2, 4, 6], "B"] = np.nan expected = pd.DataFrame({"B": [np.nan, 4, np.nan, 2, np.nan, 3, np.nan, 1]}) result = base_df.groupby("A").cummin() tm.assert_frame_equal(result, expected) expected = base_df.groupby("A").B.apply(lambda x: x.cummin()).to_frame() tm.assert_frame_equal(result, expected) # GH 15561 df = pd.DataFrame(dict(a=[1], b=pd.to_datetime(["2001"]))) expected = pd.Series(pd.to_datetime("2001"), index=[0], name="b") result = df.groupby("a")["b"].cummin() tm.assert_series_equal(expected, result) # GH 15635 df = pd.DataFrame(dict(a=[1, 2, 1], b=[1, 2, 2])) result = df.groupby("a").b.cummin() expected = pd.Series([1, 2, 1], name="b") tm.assert_series_equal(result, expected) @pytest.mark.xfail( _is_numpy_dev, reason="https://github.com/pandas-dev/pandas/issues/31992", strict=False, ) def test_cummin_all_nan_column(): base_df = pd.DataFrame({"A": [1, 1, 1, 1, 2, 2, 2, 2], "B": [np.nan] * 8}) expected = pd.DataFrame({"B": [np.nan] * 8}) result = base_df.groupby("A").cummin() tm.assert_frame_equal(expected, result) result = base_df.groupby("A").B.apply(lambda x: x.cummin()).to_frame() tm.assert_frame_equal(expected, result) @pytest.mark.xfail( _is_numpy_dev, reason="https://github.com/pandas-dev/pandas/issues/31992", strict=False, ) def test_cummax(numpy_dtypes_for_minmax): dtype = numpy_dtypes_for_minmax[0] max_val = numpy_dtypes_for_minmax[2] # GH 15048 base_df = pd.DataFrame( {"A": [1, 1, 1, 1, 2, 2, 2, 2], "B": [3, 4, 3, 2, 2, 3, 2, 1]} ) expected_maxs = [3, 4, 4, 4, 2, 3, 3, 3] df = base_df.astype(dtype) expected = pd.DataFrame({"B": expected_maxs}).astype(dtype) result = df.groupby("A").cummax() tm.assert_frame_equal(result, expected) result = df.groupby("A").B.apply(lambda x: x.cummax()).to_frame() tm.assert_frame_equal(result, expected) # Test w/ max value for dtype df.loc[[2, 6], "B"] = max_val expected.loc[[2, 3, 6, 7], "B"] = max_val result = df.groupby("A").cummax() tm.assert_frame_equal(result, expected) expected = df.groupby("A").B.apply(lambda x: x.cummax()).to_frame() tm.assert_frame_equal(result, expected) # Test nan in some values base_df.loc[[0, 2, 4, 6], "B"] = np.nan expected = pd.DataFrame({"B": [np.nan, 4, np.nan, 4, np.nan, 3, np.nan, 3]}) result = base_df.groupby("A").cummax() tm.assert_frame_equal(result, expected) expected = base_df.groupby("A").B.apply(lambda x: x.cummax()).to_frame() tm.assert_frame_equal(result, expected) # GH 15561 df = pd.DataFrame(dict(a=[1], b=pd.to_datetime(["2001"]))) expected = pd.Series(pd.to_datetime("2001"), index=[0], name="b") result = df.groupby("a")["b"].cummax() tm.assert_series_equal(expected, result) # GH 15635 df = pd.DataFrame(dict(a=[1, 2, 1], b=[2, 1, 1])) result = df.groupby("a").b.cummax() expected = pd.Series([2, 1, 2], name="b") tm.assert_series_equal(result, expected) @pytest.mark.xfail( _is_numpy_dev, reason="https://github.com/pandas-dev/pandas/issues/31992", strict=False, ) def test_cummax_all_nan_column(): base_df = pd.DataFrame({"A": [1, 1, 1, 1, 2, 2, 2, 2], "B": [np.nan] * 8}) expected = pd.DataFrame({"B": [np.nan] * 8}) result = base_df.groupby("A").cummax() tm.assert_frame_equal(expected, result) result = base_df.groupby("A").B.apply(lambda x: x.cummax()).to_frame() tm.assert_frame_equal(expected, result) @pytest.mark.parametrize( "in_vals, out_vals", [ # Basics: strictly increasing (T), strictly decreasing (F), # abs val increasing (F), non-strictly increasing (T) ([1, 2, 5, 3, 2, 0, 4, 5, -6, 1, 1], [True, False, False, True]), # Test with inf vals ( [1, 2.1, np.inf, 3, 2, np.inf, -np.inf, 5, 11, 1, -np.inf], [True, False, True, False], ), # Test with nan vals; should always be False ( [1, 2, np.nan, 3, 2, np.nan, np.nan, 5, -np.inf, 1, np.nan], [False, False, False, False], ), ], ) def test_is_monotonic_increasing(in_vals, out_vals): # GH 17015 source_dict = { "A": ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"], "B": ["a", "a", "a", "b", "b", "b", "c", "c", "c", "d", "d"], "C": in_vals, } df = pd.DataFrame(source_dict) result = df.groupby("B").C.is_monotonic_increasing index = Index(list("abcd"), name="B") expected = pd.Series(index=index, data=out_vals, name="C") tm.assert_series_equal(result, expected) # Also check result equal to manually taking x.is_monotonic_increasing. expected = df.groupby(["B"]).C.apply(lambda x: x.is_monotonic_increasing) tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "in_vals, out_vals", [ # Basics: strictly decreasing (T), strictly increasing (F), # abs val decreasing (F), non-strictly increasing (T) ([10, 9, 7, 3, 4, 5, -3, 2, 0, 1, 1], [True, False, False, True]), # Test with inf vals ( [np.inf, 1, -np.inf, np.inf, 2, -3, -np.inf, 5, -3, -np.inf, -np.inf], [True, True, False, True], ), # Test with nan vals; should always be False ( [1, 2, np.nan, 3, 2, np.nan, np.nan, 5, -np.inf, 1, np.nan], [False, False, False, False], ), ], ) def test_is_monotonic_decreasing(in_vals, out_vals): # GH 17015 source_dict = { "A": ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"], "B": ["a", "a", "a", "b", "b", "b", "c", "c", "c", "d", "d"], "C": in_vals, } df = pd.DataFrame(source_dict) result = df.groupby("B").C.is_monotonic_decreasing index = Index(list("abcd"), name="B") expected = pd.Series(index=index, data=out_vals, name="C") tm.assert_series_equal(result, expected) # describe # -------------------------------- def test_apply_describe_bug(mframe): grouped = mframe.groupby(level="first") grouped.describe() # it works! def test_series_describe_multikey(): ts = tm.makeTimeSeries() grouped = ts.groupby([lambda x: x.year, lambda x: x.month]) result = grouped.describe() tm.assert_series_equal(result["mean"], grouped.mean(), check_names=False) tm.assert_series_equal(result["std"], grouped.std(), check_names=False) tm.assert_series_equal(result["min"], grouped.min(), check_names=False) def test_series_describe_single(): ts = tm.makeTimeSeries() grouped = ts.groupby(lambda x: x.month) result = grouped.apply(lambda x: x.describe()) expected = grouped.describe().stack() tm.assert_series_equal(result, expected) def test_series_index_name(df): grouped = df.loc[:, ["C"]].groupby(df["A"]) result = grouped.agg(lambda x: x.mean()) assert result.index.name == "A" def test_frame_describe_multikey(tsframe): grouped = tsframe.groupby([lambda x: x.year, lambda x: x.month]) result = grouped.describe() desc_groups = [] for col in tsframe: group = grouped[col].describe() # GH 17464 - Remove duplicate MultiIndex levels group_col = pd.MultiIndex( levels=[[col], group.columns], codes=[[0] * len(group.columns), range(len(group.columns))], ) group = pd.DataFrame(group.values, columns=group_col, index=group.index) desc_groups.append(group) expected = pd.concat(desc_groups, axis=1) tm.assert_frame_equal(result, expected) groupedT = tsframe.groupby({"A": 0, "B": 0, "C": 1, "D": 1}, axis=1) result = groupedT.describe() expected = tsframe.describe().T expected.index = pd.MultiIndex( levels=[[0, 1], expected.index], codes=[[0, 0, 1, 1], range(len(expected.index))], ) tm.assert_frame_equal(result, expected) def test_frame_describe_tupleindex(): # GH 14848 - regression from 0.19.0 to 0.19.1 df1 = DataFrame( { "x": [1, 2, 3, 4, 5] * 3, "y": [10, 20, 30, 40, 50] * 3, "z": [100, 200, 300, 400, 500] * 3, } ) df1["k"] = [(0, 0, 1), (0, 1, 0), (1, 0, 0)] * 5 df2 = df1.rename(columns={"k": "key"}) msg = "Names should be list-like for a MultiIndex" with pytest.raises(ValueError, match=msg): df1.groupby("k").describe() with pytest.raises(ValueError, match=msg): df2.groupby("key").describe() def test_frame_describe_unstacked_format(): # GH 4792 prices = { pd.Timestamp("2011-01-06 10:59:05", tz=None): 24990, pd.Timestamp("2011-01-06 12:43:33", tz=None): 25499, pd.Timestamp("2011-01-06 12:54:09", tz=None): 25499, } volumes = { pd.Timestamp("2011-01-06 10:59:05", tz=None): 1500000000, pd.Timestamp("2011-01-06 12:43:33", tz=None): 5000000000, pd.Timestamp("2011-01-06 12:54:09", tz=None): 100000000, } df = pd.DataFrame({"PRICE": prices, "VOLUME": volumes}) result = df.groupby("PRICE").VOLUME.describe() data = [ df[df.PRICE == 24990].VOLUME.describe().values.tolist(), df[df.PRICE == 25499].VOLUME.describe().values.tolist(), ] expected = pd.DataFrame( data, index=pd.Index([24990, 25499], name="PRICE"), columns=["count", "mean", "std", "min", "25%", "50%", "75%", "max"], ) tm.assert_frame_equal(result, expected) # nunique # -------------------------------- @pytest.mark.parametrize("n", 10 ** np.arange(2, 6)) @pytest.mark.parametrize("m", [10, 100, 1000]) @pytest.mark.parametrize("sort", [False, True]) @pytest.mark.parametrize("dropna", [False, True]) def test_series_groupby_nunique(n, m, sort, dropna): def check_nunique(df, keys, as_index=True): original_df = df.copy() gr = df.groupby(keys, as_index=as_index, sort=sort) left = gr["julie"].nunique(dropna=dropna) gr = df.groupby(keys, as_index=as_index, sort=sort) right = gr["julie"].apply(Series.nunique, dropna=dropna) if not as_index: right = right.reset_index(drop=True) tm.assert_series_equal(left, right, check_names=False) tm.assert_frame_equal(df, original_df) days = date_range("2015-08-23", periods=10) frame = DataFrame( { "jim": np.random.choice(list(ascii_lowercase), n), "joe": np.random.choice(days, n), "julie": np.random.randint(0, m, n), } ) check_nunique(frame, ["jim"]) check_nunique(frame, ["jim", "joe"]) frame.loc[1::17, "jim"] = None frame.loc[3::37, "joe"] = None frame.loc[7::19, "julie"] = None frame.loc[8::19, "julie"] = None frame.loc[9::19, "julie"] = None check_nunique(frame, ["jim"]) check_nunique(frame, ["jim", "joe"]) check_nunique(frame, ["jim"], as_index=False) check_nunique(frame, ["jim", "joe"], as_index=False) def test_nunique(): df = DataFrame({"A": list("abbacc"), "B": list("abxacc"), "C": list("abbacx")}) expected = DataFrame({"A": [1] * 3, "B": [1, 2, 1], "C": [1, 1, 2]}) result = df.groupby("A", as_index=False).nunique() tm.assert_frame_equal(result, expected) # as_index expected.index = list("abc") expected.index.name = "A" result = df.groupby("A").nunique() tm.assert_frame_equal(result, expected) # with na result = df.replace({"x": None}).groupby("A").nunique(dropna=False) tm.assert_frame_equal(result, expected) # dropna expected = DataFrame({"A": [1] * 3, "B": [1] * 3, "C": [1] * 3}, index=list("abc")) expected.index.name = "A" result = df.replace({"x": None}).groupby("A").nunique() tm.assert_frame_equal(result, expected) def test_nunique_with_object(): # GH 11077 data = pd.DataFrame( [ [100, 1, "Alice"], [200, 2, "Bob"], [300, 3, "Charlie"], [-400, 4, "Dan"], [500, 5, "Edith"], ], columns=["amount", "id", "name"], ) result = data.groupby(["id", "amount"])["name"].nunique() index = MultiIndex.from_arrays([data.id, data.amount]) expected = pd.Series([1] * 5, name="name", index=index) tm.assert_series_equal(result, expected) def test_nunique_with_empty_series(): # GH 12553 data = pd.Series(name="name", dtype=object) result = data.groupby(level=0).nunique() expected = pd.Series(name="name", dtype="int64") tm.assert_series_equal(result, expected) def test_nunique_with_timegrouper(): # GH 13453 test = pd.DataFrame( { "time": [ Timestamp("2016-06-28 09:35:35"), Timestamp("2016-06-28 16:09:30"), Timestamp("2016-06-28 16:46:28"), ], "data": ["1", "2", "3"], } ).set_index("time") result = test.groupby(pd.Grouper(freq="h"))["data"].nunique() expected = test.groupby(pd.Grouper(freq="h"))["data"].apply(pd.Series.nunique) tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "key, data, dropna, expected", [ ( ["x", "x", "x"], [Timestamp("2019-01-01"), NaT, Timestamp("2019-01-01")], True, Series([1], index=pd.Index(["x"], name="key"), name="data"), ), ( ["x", "x", "x"], [dt.date(2019, 1, 1), NaT, dt.date(2019, 1, 1)], True, Series([1], index=pd.Index(["x"], name="key"), name="data"), ), ( ["x", "x", "x", "y", "y"], [dt.date(2019, 1, 1), NaT, dt.date(2019, 1, 1), NaT, dt.date(2019, 1, 1)], False, Series([2, 2], index=pd.Index(["x", "y"], name="key"), name="data"), ), ( ["x", "x", "x", "x", "y"], [dt.date(2019, 1, 1), NaT, dt.date(2019, 1, 1), NaT, dt.date(2019, 1, 1)], False, Series([2, 1], index=pd.Index(["x", "y"], name="key"), name="data"), ), ], ) def test_nunique_with_NaT(key, data, dropna, expected): # GH 27951 df = pd.DataFrame({"key": key, "data": data}) result = df.groupby(["key"])["data"].nunique(dropna=dropna) tm.assert_series_equal(result, expected) def test_nunique_preserves_column_level_names(): # GH 23222 test = pd.DataFrame([1, 2, 2], columns=pd.Index(["A"], name="level_0")) result = test.groupby([0, 0, 0]).nunique() expected = pd.DataFrame([2], columns=test.columns) tm.assert_frame_equal(result, expected) # count # -------------------------------- def test_groupby_timedelta_cython_count(): df = DataFrame( {"g": list("ab" * 2), "delt": np.arange(4).astype("timedelta64[ns]")} ) expected = Series([2, 2], index=pd.Index(["a", "b"], name="g"), name="delt") result = df.groupby("g").delt.count() tm.assert_series_equal(expected, result) def test_count(): n = 1 << 15 dr = date_range("2015-08-30", periods=n // 10, freq="T") df = DataFrame( { "1st": np.random.choice(list(ascii_lowercase), n), "2nd": np.random.randint(0, 5, n), "3rd": np.random.randn(n).round(3), "4th": np.random.randint(-10, 10, n), "5th": np.random.choice(dr, n), "6th": np.random.randn(n).round(3), "7th": np.random.randn(n).round(3), "8th": np.random.choice(dr, n) - np.random.choice(dr, 1), "9th": np.random.choice(list(ascii_lowercase), n), } ) for col in df.columns.drop(["1st", "2nd", "4th"]): df.loc[np.random.choice(n, n // 10), col] = np.nan df["9th"] = df["9th"].astype("category") for key in ["1st", "2nd", ["1st", "2nd"]]: left = df.groupby(key).count() right = df.groupby(key).apply(DataFrame.count).drop(key, axis=1) tm.assert_frame_equal(left, right) def test_count_non_nulls(): # GH#5610 # count counts non-nulls df = pd.DataFrame( [[1, 2, "foo"], [1, np.nan, "bar"], [3, np.nan, np.nan]], columns=["A", "B", "C"], ) count_as = df.groupby("A").count() count_not_as = df.groupby("A", as_index=False).count() expected = DataFrame([[1, 2], [0, 0]], columns=["B", "C"], index=[1, 3]) expected.index.name = "A" tm.assert_frame_equal(count_not_as, expected.reset_index()) tm.assert_frame_equal(count_as, expected) count_B = df.groupby("A")["B"].count() tm.assert_series_equal(count_B, expected["B"]) def test_count_object(): df = pd.DataFrame({"a": ["a"] * 3 + ["b"] * 3, "c": [2] * 3 + [3] * 3}) result = df.groupby("c").a.count() expected = pd.Series([3, 3], index=pd.Index([2, 3], name="c"), name="a") tm.assert_series_equal(result, expected) df = pd.DataFrame({"a": ["a", np.nan, np.nan] + ["b"] * 3, "c": [2] * 3 + [3] * 3}) result = df.groupby("c").a.count() expected = pd.Series([1, 3], index=pd.Index([2, 3], name="c"), name="a") tm.assert_series_equal(result, expected) def test_count_cross_type(): # GH8169 vals = np.hstack( (np.random.randint(0, 5, (100, 2)), np.random.randint(0, 2, (100, 2))) ) df = pd.DataFrame(vals, columns=["a", "b", "c", "d"]) df[df == 2] = np.nan expected = df.groupby(["c", "d"]).count() for t in ["float32", "object"]: df["a"] = df["a"].astype(t) df["b"] = df["b"].astype(t) result = df.groupby(["c", "d"]).count() tm.assert_frame_equal(result, expected) def test_lower_int_prec_count(): df = DataFrame( { "a": np.array([0, 1, 2, 100], np.int8), "b": np.array([1, 2, 3, 6], np.uint32), "c": np.array([4, 5, 6, 8], np.int16), "grp": list("ab" * 2), } ) result = df.groupby("grp").count() expected = DataFrame( {"a": [2, 2], "b": [2, 2], "c": [2, 2]}, index=pd.Index(list("ab"), name="grp") ) tm.assert_frame_equal(result, expected) def test_count_uses_size_on_exception(): class RaisingObjectException(Exception): pass class RaisingObject: def __init__(self, msg="I will raise inside Cython"): super().__init__() self.msg = msg def __eq__(self, other): # gets called in Cython to check that raising calls the method raise RaisingObjectException(self.msg) df = DataFrame({"a": [RaisingObject() for _ in range(4)], "grp": list("ab" * 2)}) result = df.groupby("grp").count() expected = DataFrame({"a": [2, 2]}, index=pd.Index(list("ab"), name="grp")) tm.assert_frame_equal(result, expected) # size # -------------------------------- @pytest.mark.parametrize("by", ["A", "B", ["A", "B"]]) def test_size(df, by): grouped = df.groupby(by=by) result = grouped.size() for key, group in grouped: assert result[key] == len(group) @pytest.mark.parametrize("by", ["A", "B", ["A", "B"]]) @pytest.mark.parametrize("sort", [True, False]) def test_size_sort(df, sort, by): df = DataFrame(np.random.choice(20, (1000, 3)), columns=list("ABC")) left = df.groupby(by=by, sort=sort).size() right = df.groupby(by=by, sort=sort)["C"].apply(lambda a: a.shape[0]) tm.assert_series_equal(left, right, check_names=False) def test_size_series_dataframe(): # https://github.com/pandas-dev/pandas/issues/11699 df = DataFrame(columns=["A", "B"]) out = Series(dtype="int64", index=Index([], name="A")) tm.assert_series_equal(df.groupby("A").size(), out) def test_size_groupby_all_null(): # https://github.com/pandas-dev/pandas/issues/23050 # Assert no 'Value Error : Length of passed values is 2, index implies 0' df = DataFrame({"A": [None, None]}) # all-null groups result = df.groupby("A").size() expected = Series(dtype="int64", index=Index([], name="A")) tm.assert_series_equal(result, expected) # quantile # -------------------------------- @pytest.mark.parametrize( "interpolation", ["linear", "lower", "higher", "nearest", "midpoint"] ) @pytest.mark.parametrize( "a_vals,b_vals", [ # Ints ([1, 2, 3, 4, 5], [5, 4, 3, 2, 1]), ([1, 2, 3, 4], [4, 3, 2, 1]), ([1, 2, 3, 4, 5], [4, 3, 2, 1]), # Floats ([1.0, 2.0, 3.0, 4.0, 5.0], [5.0, 4.0, 3.0, 2.0, 1.0]), # Missing data ([1.0, np.nan, 3.0, np.nan, 5.0], [5.0, np.nan, 3.0, np.nan, 1.0]), ([np.nan, 4.0, np.nan, 2.0, np.nan], [np.nan, 4.0, np.nan, 2.0, np.nan]), # Timestamps ( list(pd.date_range("1/1/18", freq="D", periods=5)), list(pd.date_range("1/1/18", freq="D", periods=5))[::-1], ), # All NA ([np.nan] * 5, [np.nan] * 5), ], ) @pytest.mark.parametrize("q", [0, 0.25, 0.5, 0.75, 1]) def test_quantile(interpolation, a_vals, b_vals, q): if interpolation == "nearest" and q == 0.5 and b_vals == [4, 3, 2, 1]: pytest.skip( "Unclear numpy expectation for nearest result with equidistant data" ) a_expected = pd.Series(a_vals).quantile(q, interpolation=interpolation) b_expected = pd.Series(b_vals).quantile(q, interpolation=interpolation) df = DataFrame( {"key": ["a"] * len(a_vals) + ["b"] * len(b_vals), "val": a_vals + b_vals} ) expected = DataFrame( [a_expected, b_expected], columns=["val"], index=Index(["a", "b"], name="key") ) result = df.groupby("key").quantile(q, interpolation=interpolation) tm.assert_frame_equal(result, expected) def test_quantile_array(): # https://github.com/pandas-dev/pandas/issues/27526 df = pd.DataFrame({"A": [0, 1, 2, 3, 4]}) result = df.groupby([0, 0, 1, 1, 1]).quantile([0.25]) index = pd.MultiIndex.from_product([[0, 1], [0.25]]) expected = pd.DataFrame({"A": [0.25, 2.50]}, index=index) tm.assert_frame_equal(result, expected) df = pd.DataFrame({"A": [0, 1, 2, 3], "B": [4, 5, 6, 7]}) index = pd.MultiIndex.from_product([[0, 1], [0.25, 0.75]]) result = df.groupby([0, 0, 1, 1]).quantile([0.25, 0.75]) expected = pd.DataFrame( {"A": [0.25, 0.75, 2.25, 2.75], "B": [4.25, 4.75, 6.25, 6.75]}, index=index ) tm.assert_frame_equal(result, expected) def test_quantile_array2(): # https://github.com/pandas-dev/pandas/pull/28085#issuecomment-524066959 df = pd.DataFrame( np.random.RandomState(0).randint(0, 5, size=(10, 3)), columns=list("ABC") ) result = df.groupby("A").quantile([0.3, 0.7]) expected = pd.DataFrame( { "B": [0.9, 2.1, 2.2, 3.4, 1.6, 2.4, 2.3, 2.7, 0.0, 0.0], "C": [1.2, 2.8, 1.8, 3.0, 0.0, 0.0, 1.9, 3.1, 3.0, 3.0], }, index=pd.MultiIndex.from_product( [[0, 1, 2, 3, 4], [0.3, 0.7]], names=["A", None] ), ) tm.assert_frame_equal(result, expected) def test_quantile_array_no_sort(): df = pd.DataFrame({"A": [0, 1, 2], "B": [3, 4, 5]}) result = df.groupby([1, 0, 1], sort=False).quantile([0.25, 0.5, 0.75]) expected = pd.DataFrame( {"A": [0.5, 1.0, 1.5, 1.0, 1.0, 1.0], "B": [3.5, 4.0, 4.5, 4.0, 4.0, 4.0]}, index=pd.MultiIndex.from_product([[1, 0], [0.25, 0.5, 0.75]]), ) tm.assert_frame_equal(result, expected) result = df.groupby([1, 0, 1], sort=False).quantile([0.75, 0.25]) expected = pd.DataFrame( {"A": [1.5, 0.5, 1.0, 1.0], "B": [4.5, 3.5, 4.0, 4.0]}, index=pd.MultiIndex.from_product([[1, 0], [0.75, 0.25]]), ) tm.assert_frame_equal(result, expected) def test_quantile_array_multiple_levels(): df = pd.DataFrame( {"A": [0, 1, 2], "B": [3, 4, 5], "c": ["a", "a", "a"], "d": ["a", "a", "b"]} ) result = df.groupby(["c", "d"]).quantile([0.25, 0.75]) index = pd.MultiIndex.from_tuples( [("a", "a", 0.25), ("a", "a", 0.75), ("a", "b", 0.25), ("a", "b", 0.75)], names=["c", "d", None], ) expected = pd.DataFrame( {"A": [0.25, 0.75, 2.0, 2.0], "B": [3.25, 3.75, 5.0, 5.0]}, index=index ) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("frame_size", [(2, 3), (100, 10)]) @pytest.mark.parametrize("groupby", [[0], [0, 1]]) @pytest.mark.parametrize("q", [[0.5, 0.6]]) def test_groupby_quantile_with_arraylike_q_and_int_columns(frame_size, groupby, q): # GH30289 nrow, ncol = frame_size df = pd.DataFrame( np.array([ncol * [_ % 4] for _ in range(nrow)]), columns=range(ncol) ) idx_levels = [list(range(min(nrow, 4)))] * len(groupby) + [q] idx_codes = [[x for x in range(min(nrow, 4)) for _ in q]] * len(groupby) + [ list(range(len(q))) * min(nrow, 4) ] expected_index = pd.MultiIndex( levels=idx_levels, codes=idx_codes, names=groupby + [None] ) expected_values = [ [float(x)] * (ncol - len(groupby)) for x in range(min(nrow, 4)) for _ in q ] expected_columns = [x for x in range(ncol) if x not in groupby] expected = pd.DataFrame( expected_values, index=expected_index, columns=expected_columns ) result = df.groupby(groupby).quantile(q) tm.assert_frame_equal(result, expected) def test_quantile_raises(): df = pd.DataFrame( [["foo", "a"], ["foo", "b"], ["foo", "c"]], columns=["key", "val"] ) with pytest.raises(TypeError, match="cannot be performed against 'object' dtypes"): df.groupby("key").quantile() def test_quantile_out_of_bounds_q_raises(): # https://github.com/pandas-dev/pandas/issues/27470 df = pd.DataFrame(dict(a=[0, 0, 0, 1, 1, 1], b=range(6))) g = df.groupby([0, 0, 0, 1, 1, 1]) with pytest.raises(ValueError, match="Got '50.0' instead"): g.quantile(50) with pytest.raises(ValueError, match="Got '-1.0' instead"): g.quantile(-1) def test_quantile_missing_group_values_no_segfaults(): # GH 28662 data = np.array([1.0, np.nan, 1.0]) df = pd.DataFrame(dict(key=data, val=range(3))) # Random segfaults; would have been guaranteed in loop grp = df.groupby("key") for _ in range(100): grp.quantile() def test_quantile_missing_group_values_correct_results(): # GH 28662 data = np.array([1.0, np.nan, 3.0, np.nan]) df = pd.DataFrame(dict(key=data, val=range(4))) result = df.groupby("key").quantile() expected = pd.DataFrame( [1.0, 3.0], index=pd.Index([1.0, 3.0], name="key"), columns=["val"] ) tm.assert_frame_equal(result, expected) # pipe # -------------------------------- def test_pipe(): # Test the pipe method of DataFrameGroupBy. # Issue #17871 random_state = np.random.RandomState(1234567890) df = DataFrame( { "A": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "foo"], "B": random_state.randn(8), "C": random_state.randn(8), } ) def f(dfgb): return dfgb.B.max() - dfgb.C.min().min() def square(srs): return srs ** 2 # Note that the transformations are # GroupBy -> Series # Series -> Series # This then chains the GroupBy.pipe and the # NDFrame.pipe methods result = df.groupby("A").pipe(f).pipe(square) index = Index(["bar", "foo"], dtype="object", name="A") expected = pd.Series([8.99110003361, 8.17516964785], name="B", index=index) tm.assert_series_equal(expected, result) def test_pipe_args(): # Test passing args to the pipe method of DataFrameGroupBy. # Issue #17871 df = pd.DataFrame( { "group": ["A", "A", "B", "B", "C"], "x": [1.0, 2.0, 3.0, 2.0, 5.0], "y": [10.0, 100.0, 1000.0, -100.0, -1000.0], } ) def f(dfgb, arg1): return dfgb.filter(lambda grp: grp.y.mean() > arg1, dropna=False).groupby( dfgb.grouper ) def g(dfgb, arg2): return dfgb.sum() / dfgb.sum().sum() + arg2 def h(df, arg3): return df.x + df.y - arg3 result = df.groupby("group").pipe(f, 0).pipe(g, 10).pipe(h, 100) # Assert the results here index = pd.Index(["A", "B", "C"], name="group") expected = pd.Series([-79.5160891089, -78.4839108911, -80], index=index) tm.assert_series_equal(expected, result) # test SeriesGroupby.pipe ser = pd.Series([1, 1, 2, 2, 3, 3]) result = ser.groupby(ser).pipe(lambda grp: grp.sum() * grp.count()) expected = pd.Series([4, 8, 12], index=pd.Int64Index([1, 2, 3])) tm.assert_series_equal(result, expected) def test_groupby_mean_no_overflow(): # Regression test for (#22487) df = pd.DataFrame( { "user": ["A", "A", "A", "A", "A"], "connections": [4970, 4749, 4719, 4704, 18446744073699999744], } ) assert df.groupby("user")["connections"].mean()["A"] == 3689348814740003840
""" Distributed under the terms of the BSD 3-Clause License. The full license is in the file LICENSE, distributed with this software. Author: Jun Zhu <jun.zhu@xfel.eu> Copyright (C) European X-Ray Free-Electron Laser Facility GmbH. All rights reserved. """ from collections import deque import sys import traceback import time import os.path as osp from queue import Empty from weakref import WeakKeyDictionary import functools import itertools from threading import Event from PyQt5.QtCore import ( pyqtSignal, pyqtSlot, QObject, Qt, QThread, QTimer ) from PyQt5.QtGui import QIcon from PyQt5.QtWidgets import ( QAction, QFrame, QMainWindow, QScrollArea, QSplitter, QTabWidget, QVBoxLayout, QWidget ) from redis import ConnectionError from .ctrl_widgets import ( AnalysisCtrlWidget, ExtensionCtrlWidget, FomFilterCtrlWidget, DataSourceWidget ) from .misc_widgets import AnalysisSetupManager, GuiLogger from .image_tool import ImageToolWindow from .windows import ( BinningWindow, CorrelationWindow, HistogramWindow, PulseOfInterestWindow, PumpProbeWindow, FileStreamWindow, AboutWindow ) from .. import __version__ from ..config import config from ..logger import logger from ..utils import profiler from ..ipc import RedisConnection, RedisPSubscriber from ..pipeline import MpInQueue from ..processes import shutdown_all from ..database import MonProxy class ThreadLoggerBridge(QObject): """QThread which subscribes logs the Redis server. This QThread forward the message from the Redis server and send it to the MainGUI via signal-slot connection. """ log_msg_sgn = pyqtSignal(str, str) _sub = RedisPSubscriber("log:*") def __init__(self): super().__init__() self._running = False def recv(self): self._running = True while self._running: try: msg = self._sub.get_message(ignore_subscribe_messages=True) self.log_msg_sgn.emit(msg['channel'], msg['data']) except Exception: pass time.sleep(0.001) def connectToMainThread(self, instance): self.log_msg_sgn.connect(instance.onLogMsgReceived) def stop(self): self._running = False class MainGUI(QMainWindow): """The main GUI for azimuthal integration.""" _root_dir = osp.dirname(osp.abspath(__file__)) start_sgn = pyqtSignal() stop_sgn = pyqtSignal() quit_sgn = pyqtSignal() _db = RedisConnection() _WIDTH, _HEIGHT = config['GUI_MAIN_GUI_SIZE'] def __init__(self, pause_ev, close_ev): """Initialization.""" super().__init__() self._pause_ev = pause_ev self._close_ev = close_ev self._input_update_ev = Event() self._input = MpInQueue(self._input_update_ev, pause_ev, close_ev) self._pulse_resolved = config["PULSE_RESOLVED"] self._require_geometry = config["REQUIRE_GEOMETRY"] self._queue = deque(maxlen=1) self.setAttribute(Qt.WA_DeleteOnClose) self.title = f"EXtra-foam {__version__} ({config["DETECTOR"]})" self.setWindowTitle(self.title + " - main GUI") # ************************************************************* # Central widget # ************************************************************* self._ctrl_widgets = [] # book-keeping control widgets self._cw = QSplitter() self._cw.setChildrenCollapsible(False) self.setCentralWidget(self._cw) self._left_cw_container = QScrollArea() self._left_cw_container.setFrameShape(QFrame.NoFrame) self._left_cw = QTabWidget() self._right_cw_container = QScrollArea() self._right_cw_container.setFrameShape(QFrame.NoFrame) self._right_cw = QSplitter(Qt.Vertical) self._right_cw.setChildrenCollapsible(False) self._source_cw = self.createCtrlWidget(DataSourceWidget) self._extension_cw = self.createCtrlWidget(ExtensionCtrlWidget) self._ctrl_panel_cw = QTabWidget() self._analysis_cw = QWidget() self._statistics_cw = QWidget() self._util_panel_container = QWidget() self._util_panel_cw = QTabWidget() # ************************************************************* # Tool bar # Note: the order of '_addAction` affect the unittest!!! # ************************************************************* self._tool_bar = self.addToolBar("Control") # make icon a bit larger self._tool_bar.setIconSize(2 * self._tool_bar.iconSize()) self._start_at = self._addAction("Start bridge", "start.png") self._start_at.triggered.connect(self.onStart) self._stop_at = self._addAction("Stop bridge", "stop.png") self._stop_at.triggered.connect(self.onStop) self._stop_at.setEnabled(False) self._tool_bar.addSeparator() image_tool_at = self._addAction("Image tool", "image_tool.png") image_tool_at.triggered.connect( lambda: (self._image_tool.show(), self._image_tool.activateWindow())) open_poi_window_at = self._addAction("Pulse-of-interest", "poi.png") open_poi_window_at.triggered.connect( functools.partial(self.onOpenPlotWindow, PulseOfInterestWindow)) if not self._pulse_resolved: open_poi_window_at.setEnabled(False) pump_probe_window_at = self._addAction("Pump-probe", "pump-probe.png") pump_probe_window_at.triggered.connect( functools.partial(self.onOpenPlotWindow, PumpProbeWindow)) open_correlation_window_at = self._addAction( "Correlation", "correlation.png") open_correlation_window_at.triggered.connect( functools.partial(self.onOpenPlotWindow, CorrelationWindow)) open_histogram_window_at = self._addAction( "Histogram", "histogram.png") open_histogram_window_at.triggered.connect( functools.partial(self.onOpenPlotWindow, HistogramWindow)) open_bin2d_window_at = self._addAction("Binning", "binning.png") open_bin2d_window_at.triggered.connect( functools.partial(self.onOpenPlotWindow, BinningWindow)) self._tool_bar.addSeparator() open_file_stream_window_at = self._addAction( "File stream", "file_stream.png") open_file_stream_window_at.triggered.connect( lambda: self.onOpenSatelliteWindow(FileStreamWindow)) open_about_at = self._addAction("About EXtra-foam", "about.png") open_about_at.triggered.connect( lambda: self.onOpenSatelliteWindow(AboutWindow)) # ************************************************************* # Miscellaneous # ************************************************************* # book-keeping opened windows self._plot_windows = WeakKeyDictionary() self._satellite_windows = WeakKeyDictionary() self._gui_logger = GuiLogger(parent=self) logger.addHandler(self._gui_logger) self._analysis_setup_manager = AnalysisSetupManager() self._thread_logger = ThreadLoggerBridge() self.quit_sgn.connect(self._thread_logger.stop) self._thread_logger_t = QThread() self._thread_logger.moveToThread(self._thread_logger_t) self._thread_logger_t.started.connect(self._thread_logger.recv) self._thread_logger.connectToMainThread(self) # For real time plot self._running = False self._plot_timer = QTimer() self._plot_timer.timeout.connect(self.updateAll) # For checking the connection to the Redis server self._redis_timer = QTimer() self._redis_timer.timeout.connect(self.pingRedisServer) self.__redis_connection_fails = 0 self._mon_proxy = MonProxy() # ************************************************************* # control widgets # ************************************************************* # analysis control widgets self.analysis_ctrl_widget = self.createCtrlWidget(AnalysisCtrlWidget) self.fom_filter_ctrl_widget = self.createCtrlWidget(FomFilterCtrlWidget) # ************************************************************* # status bar # ************************************************************* # StatusBar to display topic name self.statusBar().showMessage(f"TOPIC: {config["TOPIC"]}") self.statusBar().setStyleSheet("QStatusBar{font-weight:bold;}") # ImageToolWindow is treated differently since it is the second # control window. self._image_tool = ImageToolWindow( queue=self._queue, pulse_resolved=self._pulse_resolved, require_geometry=self._require_geometry, parent=self) self.initUI() self.initConnections() self.updateMetaData() self._analysis_setup_manager.onInit() self.setMinimumSize(640, 480) self.resize(self._WIDTH, self._HEIGHT) self.show() def createCtrlWidget(self, widget_class): widget = widget_class(pulse_resolved=self._pulse_resolved, require_geometry=self._require_geometry, parent=self) self._ctrl_widgets.append(widget) return widget def initUI(self): self.initLeftUI() self.initRightUI() self._cw.addWidget(self._left_cw_container) self._cw.addWidget(self._right_cw_container) self._cw.setSizes([self._WIDTH * 0.6, self._WIDTH * 0.4]) def initLeftUI(self): self._left_cw.setTabPosition(QTabWidget.TabPosition.West) self._left_cw.addTab(self._source_cw, "Data source") self._left_cw_container.setWidget(self._left_cw) self._left_cw_container.setWidgetResizable(True) self._left_cw.addTab(self._extension_cw, "Extension") def initRightUI(self): self.initCtrlUI() self.initUtilUI() self._right_cw.addWidget(self._ctrl_panel_cw) self._right_cw.addWidget(self._util_panel_container) self._right_cw_container.setWidget(self._right_cw) self._right_cw_container.setWidgetResizable(True) def initCtrlUI(self): self.initGeneralAnalysisUI() self._ctrl_panel_cw.addTab(self._analysis_cw, "General analysis setup") def initGeneralAnalysisUI(self): layout = QVBoxLayout() layout.addWidget(self.analysis_ctrl_widget) layout.addWidget(self.fom_filter_ctrl_widget) self._analysis_cw.setLayout(layout) def initUtilUI(self): self._util_panel_cw.addTab(self._gui_logger.widget, "Logger") self._util_panel_cw.addTab(self._analysis_setup_manager, "Analysis Setup Manager") self._util_panel_cw.setTabPosition(QTabWidget.TabPosition.South) layout = QVBoxLayout() layout.addWidget(self._util_panel_cw) self._util_panel_container.setLayout(layout) def initConnections(self): self._analysis_setup_manager.load_metadata_sgn.connect(self.loadMetaData) def connect_input_to_output(self, output): self._input.connect(output) @profiler("Update Plots", process_time=True) def updateAll(self): """Update all the plots in the main and child windows.""" if not self._running: return try: processed = self._input.get() self._queue.append(processed) except Empty: return # clear the previous plots no matter what comes next # for w in self._plot_windows.keys(): # w.reset() data = self._queue[0] self._image_tool.updateWidgetsF() for w in itertools.chain(self._plot_windows): try: w.updateWidgetsF() except Exception as e: exc_type, exc_value, exc_traceback = sys.exc_info() logger.debug(repr(traceback.format_tb(exc_traceback)) + repr(e)) logger.error(f"[Update plots] {repr(e)}") logger.debug(f"Plot train with ID: {data.tid}") def pingRedisServer(self): try: self._db.ping() if self.__redis_connection_fails > 0: # Note: Indeed, we do not have mechanism to recover from # a Redis server crash. It is recommended to restart # Extra-foam if you encounter this situation. logger.info("Reconnect to the Redis server!") self.__redis_connection_fails = 0 except ConnectionError: self.__redis_connection_fails += 1 rest_attempts = config["REDIS_MAX_PING_ATTEMPTS"] - \ self.__redis_connection_fails if rest_attempts > 0: logger.warning(f"No response from the Redis server! Shut " f"down after {rest_attempts} attempts ...") else: logger.warning(f"No response from the Redis server! " f"Shutting down!") self.close() def _addAction(self, description, filename): icon = QIcon(osp.join(self._root_dir, "icons/" + filename)) action = QAction(icon, description, self) self._tool_bar.addAction(action) return action def onOpenPlotWindow(self, instance_type): """Open a plot window if it does not exist. Otherwise bring the opened window to the table top. """ if self.checkWindowExistence(instance_type, self._plot_windows): return return instance_type(self._queue, pulse_resolved=self._pulse_resolved, require_geometry=self._require_geometry, parent=self) def onOpenSatelliteWindow(self, instance_type): """Open a satellite window if it does not exist. Otherwise bring the opened window to the table top. """ if self.checkWindowExistence(instance_type, self._satellite_windows): return return instance_type(parent=self) def checkWindowExistence(self, instance_type, windows): for key in windows: if isinstance(key, instance_type): key.activateWindow() return True return False def registerWindow(self, instance): self._plot_windows[instance] = 1 def unregisterWindow(self, instance): del self._plot_windows[instance] def registerSatelliteWindow(self, instance): self._satellite_windows[instance] = 1 def unregisterSatelliteWindow(self, instance): del self._satellite_windows[instance] @property def input(self): return self._input def start(self): """Start running. ProcessWorker interface. """ self._thread_logger_t.start() self._plot_timer.start(config["GUI_PLOT_UPDATE_TIMER"]) self._redis_timer.start(config["REDIS_PING_ATTEMPT_INTERVAL"]) self._input.start() def onStart(self): if not self.updateMetaData(): return self.start_sgn.emit() self._start_at.setEnabled(False) self._stop_at.setEnabled(True) for widget in self._ctrl_widgets: widget.onStart() for win in self._plot_windows: win.onStart() self._image_tool.onStart() self._analysis_setup_manager.onStart() self._running = True # starting to update plots self._input_update_ev.set() # notify update def onStop(self): """Actions taken before the end of a 'run'.""" self._running = False self.stop_sgn.emit() # TODO: wait for some signal self._start_at.setEnabled(True) self._stop_at.setEnabled(False) for widget in self._ctrl_widgets: widget.onStop() for win in self._plot_windows: win.onStop() self._image_tool.onStop() self._analysis_setup_manager.onStop() def updateMetaData(self): """Update metadata from all the ctrl widgets. :returns bool: True if all metadata successfully parsed and emitted, otherwise False. """ for widget in self._ctrl_widgets: if not widget.updateMetaData(): return False for win in self._plot_windows: if not win.updateMetaData(): return False return self._image_tool.updateMetaData() def loadMetaData(self): """Load metadata from Redis and set child control widgets.""" for widget in self._ctrl_widgets: widget.loadMetaData() for win in self._plot_windows: win.loadMetaData() self._image_tool.loadMetaData() @pyqtSlot(str, str) def onLogMsgReceived(self, ch, msg): if ch == 'log:debug': logger.debug(msg) elif ch == 'log:info': logger.info(msg) elif ch == 'log:warning': logger.warning(msg) elif ch == 'log:error': logger.error(msg) def closeEvent(self, QCloseEvent): # prevent from logging in the GUI when it has been closed logger.removeHandler(self._gui_logger) # tell all processes to close self._close_ev.set() # clean up the logger thread self.quit_sgn.emit() self._thread_logger_t.quit() self._thread_logger_t.wait() # shutdown pipeline workers and Redis server shutdown_all() self._image_tool.close() for window in list(itertools.chain(self._plot_windows, self._satellite_windows)): # Close all open child windows to make sure their resources # (any running process etc.) are released gracefully. This # is especially necessary for the case when file stream was # still ongoing when the main GUI was closed. window.close() super().closeEvent(QCloseEvent)
""" Distributed under the terms of the BSD 3-Clause License. The full license is in the file LICENSE, distributed with this software. Author: Jun Zhu <jun.zhu@xfel.eu> Copyright (C) European X-Ray Free-Electron Laser Facility GmbH. All rights reserved. """ from collections import deque import sys import traceback import time import os.path as osp from queue import Empty from weakref import WeakKeyDictionary import functools import itertools from threading import Event from PyQt5.QtCore import ( pyqtSignal, pyqtSlot, QObject, Qt, QThread, QTimer ) from PyQt5.QtGui import QIcon from PyQt5.QtWidgets import ( QAction, QFrame, QMainWindow, QScrollArea, QSplitter, QTabWidget, QVBoxLayout, QWidget ) from redis import ConnectionError from .ctrl_widgets import ( AnalysisCtrlWidget, ExtensionCtrlWidget, FomFilterCtrlWidget, DataSourceWidget ) from .misc_widgets import AnalysisSetupManager, GuiLogger from .image_tool import ImageToolWindow from .windows import ( BinningWindow, CorrelationWindow, HistogramWindow, PulseOfInterestWindow, PumpProbeWindow, FileStreamWindow, AboutWindow ) from .. import __version__ from ..config import config from ..logger import logger from ..utils import profiler from ..ipc import RedisConnection, RedisPSubscriber from ..pipeline import MpInQueue from ..processes import shutdown_all from ..database import MonProxy class ThreadLoggerBridge(QObject): """QThread which subscribes logs the Redis server. This QThread forward the message from the Redis server and send it to the MainGUI via signal-slot connection. """ log_msg_sgn = pyqtSignal(str, str) _sub = RedisPSubscriber("log:*") def __init__(self): super().__init__() self._running = False def recv(self): self._running = True while self._running: try: msg = self._sub.get_message(ignore_subscribe_messages=True) self.log_msg_sgn.emit(msg['channel'], msg['data']) except Exception: pass time.sleep(0.001) def connectToMainThread(self, instance): self.log_msg_sgn.connect(instance.onLogMsgReceived) def stop(self): self._running = False class MainGUI(QMainWindow): """The main GUI for azimuthal integration.""" _root_dir = osp.dirname(osp.abspath(__file__)) start_sgn = pyqtSignal() stop_sgn = pyqtSignal() quit_sgn = pyqtSignal() _db = RedisConnection() _WIDTH, _HEIGHT = config['GUI_MAIN_GUI_SIZE'] def __init__(self, pause_ev, close_ev): """Initialization.""" super().__init__() self._pause_ev = pause_ev self._close_ev = close_ev self._input_update_ev = Event() self._input = MpInQueue(self._input_update_ev, pause_ev, close_ev) self._pulse_resolved = config["PULSE_RESOLVED"] self._require_geometry = config["REQUIRE_GEOMETRY"] self._queue = deque(maxlen=1) self.setAttribute(Qt.WA_DeleteOnClose) self.title = f"EXtra-foam {__version__} ({config['DETECTOR']})" self.setWindowTitle(self.title + " - main GUI") # ************************************************************* # Central widget # ************************************************************* self._ctrl_widgets = [] # book-keeping control widgets self._cw = QSplitter() self._cw.setChildrenCollapsible(False) self.setCentralWidget(self._cw) self._left_cw_container = QScrollArea() self._left_cw_container.setFrameShape(QFrame.NoFrame) self._left_cw = QTabWidget() self._right_cw_container = QScrollArea() self._right_cw_container.setFrameShape(QFrame.NoFrame) self._right_cw = QSplitter(Qt.Vertical) self._right_cw.setChildrenCollapsible(False) self._source_cw = self.createCtrlWidget(DataSourceWidget) self._extension_cw = self.createCtrlWidget(ExtensionCtrlWidget) self._ctrl_panel_cw = QTabWidget() self._analysis_cw = QWidget() self._statistics_cw = QWidget() self._util_panel_container = QWidget() self._util_panel_cw = QTabWidget() # ************************************************************* # Tool bar # Note: the order of '_addAction` affect the unittest!!! # ************************************************************* self._tool_bar = self.addToolBar("Control") # make icon a bit larger self._tool_bar.setIconSize(2 * self._tool_bar.iconSize()) self._start_at = self._addAction("Start bridge", "start.png") self._start_at.triggered.connect(self.onStart) self._stop_at = self._addAction("Stop bridge", "stop.png") self._stop_at.triggered.connect(self.onStop) self._stop_at.setEnabled(False) self._tool_bar.addSeparator() image_tool_at = self._addAction("Image tool", "image_tool.png") image_tool_at.triggered.connect( lambda: (self._image_tool.show(), self._image_tool.activateWindow())) open_poi_window_at = self._addAction("Pulse-of-interest", "poi.png") open_poi_window_at.triggered.connect( functools.partial(self.onOpenPlotWindow, PulseOfInterestWindow)) if not self._pulse_resolved: open_poi_window_at.setEnabled(False) pump_probe_window_at = self._addAction("Pump-probe", "pump-probe.png") pump_probe_window_at.triggered.connect( functools.partial(self.onOpenPlotWindow, PumpProbeWindow)) open_correlation_window_at = self._addAction( "Correlation", "correlation.png") open_correlation_window_at.triggered.connect( functools.partial(self.onOpenPlotWindow, CorrelationWindow)) open_histogram_window_at = self._addAction( "Histogram", "histogram.png") open_histogram_window_at.triggered.connect( functools.partial(self.onOpenPlotWindow, HistogramWindow)) open_bin2d_window_at = self._addAction("Binning", "binning.png") open_bin2d_window_at.triggered.connect( functools.partial(self.onOpenPlotWindow, BinningWindow)) self._tool_bar.addSeparator() open_file_stream_window_at = self._addAction( "File stream", "file_stream.png") open_file_stream_window_at.triggered.connect( lambda: self.onOpenSatelliteWindow(FileStreamWindow)) open_about_at = self._addAction("About EXtra-foam", "about.png") open_about_at.triggered.connect( lambda: self.onOpenSatelliteWindow(AboutWindow)) # ************************************************************* # Miscellaneous # ************************************************************* # book-keeping opened windows self._plot_windows = WeakKeyDictionary() self._satellite_windows = WeakKeyDictionary() self._gui_logger = GuiLogger(parent=self) logger.addHandler(self._gui_logger) self._analysis_setup_manager = AnalysisSetupManager() self._thread_logger = ThreadLoggerBridge() self.quit_sgn.connect(self._thread_logger.stop) self._thread_logger_t = QThread() self._thread_logger.moveToThread(self._thread_logger_t) self._thread_logger_t.started.connect(self._thread_logger.recv) self._thread_logger.connectToMainThread(self) # For real time plot self._running = False self._plot_timer = QTimer() self._plot_timer.timeout.connect(self.updateAll) # For checking the connection to the Redis server self._redis_timer = QTimer() self._redis_timer.timeout.connect(self.pingRedisServer) self.__redis_connection_fails = 0 self._mon_proxy = MonProxy() # ************************************************************* # control widgets # ************************************************************* # analysis control widgets self.analysis_ctrl_widget = self.createCtrlWidget(AnalysisCtrlWidget) self.fom_filter_ctrl_widget = self.createCtrlWidget(FomFilterCtrlWidget) # ************************************************************* # status bar # ************************************************************* # StatusBar to display topic name self.statusBar().showMessage(f"TOPIC: {config['TOPIC']}") self.statusBar().setStyleSheet("QStatusBar{font-weight:bold;}") # ImageToolWindow is treated differently since it is the second # control window. self._image_tool = ImageToolWindow( queue=self._queue, pulse_resolved=self._pulse_resolved, require_geometry=self._require_geometry, parent=self) self.initUI() self.initConnections() self.updateMetaData() self._analysis_setup_manager.onInit() self.setMinimumSize(640, 480) self.resize(self._WIDTH, self._HEIGHT) self.show() def createCtrlWidget(self, widget_class): widget = widget_class(pulse_resolved=self._pulse_resolved, require_geometry=self._require_geometry, parent=self) self._ctrl_widgets.append(widget) return widget def initUI(self): self.initLeftUI() self.initRightUI() self._cw.addWidget(self._left_cw_container) self._cw.addWidget(self._right_cw_container) self._cw.setSizes([self._WIDTH * 0.6, self._WIDTH * 0.4]) def initLeftUI(self): self._left_cw.setTabPosition(QTabWidget.TabPosition.West) self._left_cw.addTab(self._source_cw, "Data source") self._left_cw_container.setWidget(self._left_cw) self._left_cw_container.setWidgetResizable(True) self._left_cw.addTab(self._extension_cw, "Extension") def initRightUI(self): self.initCtrlUI() self.initUtilUI() self._right_cw.addWidget(self._ctrl_panel_cw) self._right_cw.addWidget(self._util_panel_container) self._right_cw_container.setWidget(self._right_cw) self._right_cw_container.setWidgetResizable(True) def initCtrlUI(self): self.initGeneralAnalysisUI() self._ctrl_panel_cw.addTab(self._analysis_cw, "General analysis setup") def initGeneralAnalysisUI(self): layout = QVBoxLayout() layout.addWidget(self.analysis_ctrl_widget) layout.addWidget(self.fom_filter_ctrl_widget) self._analysis_cw.setLayout(layout) def initUtilUI(self): self._util_panel_cw.addTab(self._gui_logger.widget, "Logger") self._util_panel_cw.addTab(self._analysis_setup_manager, "Analysis Setup Manager") self._util_panel_cw.setTabPosition(QTabWidget.TabPosition.South) layout = QVBoxLayout() layout.addWidget(self._util_panel_cw) self._util_panel_container.setLayout(layout) def initConnections(self): self._analysis_setup_manager.load_metadata_sgn.connect(self.loadMetaData) def connect_input_to_output(self, output): self._input.connect(output) @profiler("Update Plots", process_time=True) def updateAll(self): """Update all the plots in the main and child windows.""" if not self._running: return try: processed = self._input.get() self._queue.append(processed) except Empty: return # clear the previous plots no matter what comes next # for w in self._plot_windows.keys(): # w.reset() data = self._queue[0] self._image_tool.updateWidgetsF() for w in itertools.chain(self._plot_windows): try: w.updateWidgetsF() except Exception as e: exc_type, exc_value, exc_traceback = sys.exc_info() logger.debug(repr(traceback.format_tb(exc_traceback)) + repr(e)) logger.error(f"[Update plots] {repr(e)}") logger.debug(f"Plot train with ID: {data.tid}") def pingRedisServer(self): try: self._db.ping() if self.__redis_connection_fails > 0: # Note: Indeed, we do not have mechanism to recover from # a Redis server crash. It is recommended to restart # Extra-foam if you encounter this situation. logger.info("Reconnect to the Redis server!") self.__redis_connection_fails = 0 except ConnectionError: self.__redis_connection_fails += 1 rest_attempts = config["REDIS_MAX_PING_ATTEMPTS"] - \ self.__redis_connection_fails if rest_attempts > 0: logger.warning(f"No response from the Redis server! Shut " f"down after {rest_attempts} attempts ...") else: logger.warning(f"No response from the Redis server! " f"Shutting down!") self.close() def _addAction(self, description, filename): icon = QIcon(osp.join(self._root_dir, "icons/" + filename)) action = QAction(icon, description, self) self._tool_bar.addAction(action) return action def onOpenPlotWindow(self, instance_type): """Open a plot window if it does not exist. Otherwise bring the opened window to the table top. """ if self.checkWindowExistence(instance_type, self._plot_windows): return return instance_type(self._queue, pulse_resolved=self._pulse_resolved, require_geometry=self._require_geometry, parent=self) def onOpenSatelliteWindow(self, instance_type): """Open a satellite window if it does not exist. Otherwise bring the opened window to the table top. """ if self.checkWindowExistence(instance_type, self._satellite_windows): return return instance_type(parent=self) def checkWindowExistence(self, instance_type, windows): for key in windows: if isinstance(key, instance_type): key.activateWindow() return True return False def registerWindow(self, instance): self._plot_windows[instance] = 1 def unregisterWindow(self, instance): del self._plot_windows[instance] def registerSatelliteWindow(self, instance): self._satellite_windows[instance] = 1 def unregisterSatelliteWindow(self, instance): del self._satellite_windows[instance] @property def input(self): return self._input def start(self): """Start running. ProcessWorker interface. """ self._thread_logger_t.start() self._plot_timer.start(config["GUI_PLOT_UPDATE_TIMER"]) self._redis_timer.start(config["REDIS_PING_ATTEMPT_INTERVAL"]) self._input.start() def onStart(self): if not self.updateMetaData(): return self.start_sgn.emit() self._start_at.setEnabled(False) self._stop_at.setEnabled(True) for widget in self._ctrl_widgets: widget.onStart() for win in self._plot_windows: win.onStart() self._image_tool.onStart() self._analysis_setup_manager.onStart() self._running = True # starting to update plots self._input_update_ev.set() # notify update def onStop(self): """Actions taken before the end of a 'run'.""" self._running = False self.stop_sgn.emit() # TODO: wait for some signal self._start_at.setEnabled(True) self._stop_at.setEnabled(False) for widget in self._ctrl_widgets: widget.onStop() for win in self._plot_windows: win.onStop() self._image_tool.onStop() self._analysis_setup_manager.onStop() def updateMetaData(self): """Update metadata from all the ctrl widgets. :returns bool: True if all metadata successfully parsed and emitted, otherwise False. """ for widget in self._ctrl_widgets: if not widget.updateMetaData(): return False for win in self._plot_windows: if not win.updateMetaData(): return False return self._image_tool.updateMetaData() def loadMetaData(self): """Load metadata from Redis and set child control widgets.""" for widget in self._ctrl_widgets: widget.loadMetaData() for win in self._plot_windows: win.loadMetaData() self._image_tool.loadMetaData() @pyqtSlot(str, str) def onLogMsgReceived(self, ch, msg): if ch == 'log:debug': logger.debug(msg) elif ch == 'log:info': logger.info(msg) elif ch == 'log:warning': logger.warning(msg) elif ch == 'log:error': logger.error(msg) def closeEvent(self, QCloseEvent): # prevent from logging in the GUI when it has been closed logger.removeHandler(self._gui_logger) # tell all processes to close self._close_ev.set() # clean up the logger thread self.quit_sgn.emit() self._thread_logger_t.quit() self._thread_logger_t.wait() # shutdown pipeline workers and Redis server shutdown_all() self._image_tool.close() for window in list(itertools.chain(self._plot_windows, self._satellite_windows)): # Close all open child windows to make sure their resources # (any running process etc.) are released gracefully. This # is especially necessary for the case when file stream was # still ongoing when the main GUI was closed. window.close() super().closeEvent(QCloseEvent)
""" OpenVINO DL Workbench Class for ORM model described Jupyter notebook abstraction Copyright (c) 2021 Intel Corporation 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 http://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. """ import os from contextlib import closing from pathlib import Path from typing import Dict, Optional, Any from sqlalchemy import Column, String, Integer, ForeignKey, event from sqlalchemy.engine import Connection from sqlalchemy.orm import relationship, backref, Mapper, Session, sessionmaker from config.constants import JUPYTER_NOTEBOOKS_FOLDER, ESSENTIAL_DATA_FOLDER from wb.main.console_tool_wrapper.model_optimizer.tool import ModelOptimizerTool from wb.main.enumerates import ModelPrecisionEnum, JobTypesEnum, StatusEnum, OptimizationTypesEnum, ModelDomainEnum, \ ModelShapeTypeEnum from wb.main.jupyter_notebooks.cell_template_contexts import IntroCellTemplateContext, \ SetIRModelPathsCodeCellTemplateContext, ProfilingCodeCellTemplateContext, AccuracyDocsCellTemplateContext, \ AccuracyCodeCellTemplateContext, Int8OptimizationCodeCellTemplateContext, Int8OptimizationDocsCellTemplateContext, \ ObtainModelDocsCellTemplateContext, ModelDownloaderCodeCellTemplateContext, \ CheckModelFormatDocsCellTemplateContext, ModelConverterCodeCellTemplateContext, \ ModelOptimizerCodeCellTemplateContext, InstallRequirementsCodeCellTemplateContext, \ TokenizerParametersTemplateContext from wb.main.jupyter_notebooks.cli_tools_options import CLIToolEnum from wb.main.jupyter_notebooks.config_file_dumpers import AccuracyConfigFileDumper, Int8OptimizationConfigFileDumper from wb.main.jupyter_notebooks.jupyter_notebook_cell import NotebookCellIds from wb.main.jupyter_notebooks.jupyter_notebook_dumper import JupyterNotebookDumper from wb.main.jupyter_notebooks.notebook_template_creator import NotebookTemplateCreator from wb.main.models.base_model import BaseModel from wb.main.models.model_optimizer_job_model import ModelOptimizerJobModel class JupyterNotebookModel(BaseModel): __tablename__ = 'jupyter_notebooks' id = Column(Integer, primary_key=True, autoincrement=True) project_id = Column(Integer, ForeignKey('projects.id'), nullable=True) name = Column(String, nullable=False) # Relationships project: 'ProjectsModel' = relationship('ProjectsModel', backref=backref('jupyter_notebook', cascade='delete,all', uselist=False), foreign_keys=[project_id]) def __init__(self, project_id: int): self.project_id = project_id self.name = f'project_{self.project_id}.ipynb' @property def notebook_directory_path(self) -> str: return str(Path(JUPYTER_NOTEBOOKS_FOLDER).resolve().absolute() / str(self.id)) @property def notebook_path(self) -> str: return os.path.join(self.notebook_directory_path, self.name) @property def notebook_relative_path(self) -> str: return os.path.relpath(path=self.notebook_path, start=ESSENTIAL_DATA_FOLDER) @property def notebook_exists(self) -> bool: return os.path.isfile(self.notebook_path) @staticmethod def get_jupyter_notebook_model(project_id: int, session: Session) -> 'JupyterNotebookModel': jupyter_notebook_model: JupyterNotebookModel = session.query(JupyterNotebookModel).filter( JupyterNotebookModel.project_id == project_id ).first() if not jupyter_notebook_model: raise Exception(f'Jupyter notebook model not found for project id {project_id}') if not os.path.isfile(jupyter_notebook_model.notebook_path): raise Exception(f'Jupyter notebook file not found in path {jupyter_notebook_model.notebook_path}') return jupyter_notebook_model @property def jupyter_notebook_dumper(self) -> JupyterNotebookDumper: topology: 'TopologiesModel' = self.project.topology.optimized_from_record or self.project.topology is_nlp = topology.domain == ModelDomainEnum.NLP has_tokenizer = topology.tokenizer_model is not None notebook_template_creator = NotebookTemplateCreator(notebook_type=self.project.optimization_type, original_model_source=topology.source, original_model_framework=topology.original_model_framework, is_nlp=is_nlp, has_tokenizer=has_tokenizer,) return JupyterNotebookDumper(notebook_path=self.notebook_path, notebook_template_creator=notebook_template_creator) @property def initial_cells_context_map(self) -> Dict[NotebookCellIds, dict]: return { key: getter.__get__(self) for key, getter in self._cell_id_to_context_getter_map.items() } def _get_cell_template_context(self, cell_id: NotebookCellIds) -> dict: cell_context_getter = self._cell_id_to_context_getter_map.get(cell_id) if not cell_context_getter: raise Exception(f'No template context found for cell with id {cell_id}') return cell_context_getter.__get__(self) def update_cell_by_job_type(self, job_type: JobTypesEnum): cell_ids_to_update = self._job_type_to_update_cell_ids_map.get(job_type) if not cell_ids_to_update: raise Exception(f'No Jupyter notebook cell found to update for job with type {job_type}') notebook_dumper = self.jupyter_notebook_dumper cell_ids_to_update = [cell for cell in cell_ids_to_update if cell in notebook_dumper] for cell_id_to_update in cell_ids_to_update: cell_template_context = self._get_cell_template_context(cell_id=cell_id_to_update) notebook_dumper.update_cell(cell_id=cell_id_to_update, cell_template_context=cell_template_context) # Update int8 optimization cell for parent project notebook if cell_id_to_update == NotebookCellIds.int8_optimization_code: current_session = Session.object_session(self) parent_project = self.project.get_parent_project(session=current_session) if not parent_project: continue parent_project_notebook: JupyterNotebookModel = parent_project.jupyter_notebook if not parent_project_notebook or not parent_project_notebook.notebook_exists: continue parent_project_notebook_dumper: JupyterNotebookDumper = parent_project_notebook.jupyter_notebook_dumper parent_project_notebook_dumper.update_cell(cell_id=cell_id_to_update, cell_template_context=cell_template_context) def update_notebook_by_orm_event(self, model_class: BaseModel, orm_event: str): cell_ids_to_update = self._orm_event_to_update_cell_ids_map[model_class][orm_event] notebook_dumper = self.jupyter_notebook_dumper self.jupyter_notebook_dumper.update_notebook_cells() for cell_id_to_update in cell_ids_to_update: cell_template_context = self._get_cell_template_context(cell_id=cell_id_to_update) notebook_dumper.update_cell( cell_id=cell_id_to_update, cell_template_context=cell_template_context ) @property def _original_project(self) -> 'ProjectsModel': current_session = Session.object_session(self) return self.project.get_parent_project(session=current_session) or self.project @property def _is_optimized_project(self) -> bool: return self.project.optimization_type == OptimizationTypesEnum.int8calibration @property def _has_accuracy_checker_section(self) -> bool: return NotebookCellIds.accuracy_code in self.jupyter_notebook_dumper @property def _has_int8_calibration_section(self) -> bool: return NotebookCellIds.int8_optimization_code in self.jupyter_notebook_dumper @property def _has_tokenizer_section(self) -> bool: return NotebookCellIds.load_tokenizer_code in self.jupyter_notebook_dumper @property def _intro_cell_template_context(self) -> IntroCellTemplateContext: original_project: 'ProjectsModel' = self._original_project topology: 'TopologiesModel' = original_project.topology topology_json: dict = topology.json() model_task_type = topology_json.get('accuracyConfiguration', {}).get('taskType') project_model_framework = topology.original_model_framework.value model_precisions = topology.get_precisions() mo_params = topology_json.get('analysis', {}).get('moParams', {}) topology_analysis_precision = ModelPrecisionEnum.fp16.value if mo_params: topology_analysis_precision = mo_params['dataType'] model_precisions = ', '.join(model_precisions) if model_precisions else topology_analysis_precision return IntroCellTemplateContext( is_optimized_project=self._is_optimized_project, project_model_name=topology.name, project_model_domain=topology.domain.value if topology.domain else "Generic", project_device_name=original_project.device.device_name, project_model_task_type=model_task_type, project_model_framework=project_model_framework, project_model_precisions=model_precisions, has_tokenizer_section=self._has_tokenizer_section, has_accuracy_checker_section=self._has_accuracy_checker_section, has_int8_calibration_section=self._has_int8_calibration_section, ) @property def _python_executable(self) -> str: topology = self._original_project.topology python_executable = '' environment: 'EnvironmentModel' = topology.environment if environment: python_executable = environment.python_executable return str(python_executable) @property def _obtain_model_docs_cell_template_context(self) -> ObtainModelDocsCellTemplateContext: topology: 'TopologiesModel' = self._original_project.topology project_model_framework = topology.original_model_framework.value if topology.original_model_framework else None project_model_source = topology.source.value if topology.source else None return ObtainModelDocsCellTemplateContext( project_model_name=topology.name, project_model_framework=project_model_framework, project_model_source=project_model_source) @property def _model_downloader_code_cell_template_context(self) -> ModelDownloaderCodeCellTemplateContext: output_directory_path = 'downloaded_model' return ModelDownloaderCodeCellTemplateContext( omz_model_name=self.project.topology.name, output_directory_path=output_directory_path) @property def _model_converter_code_cell_template_context(self) -> ModelConverterCodeCellTemplateContext: model_downloader_cell_context = self._model_downloader_code_cell_template_context output_directory_path = 'ir_model' return ModelConverterCodeCellTemplateContext( omz_model_name=model_downloader_cell_context['omz_model_name'], download_directory_path=model_downloader_cell_context['output_directory_path'], output_directory_path=output_directory_path) def _add_layout_to_mo_args(self, mo_args: Dict[str, Any]) -> None: layout_from_mo_args = mo_args.get('layout') layout_from_topology = self.project.topology.meta.layout_configuration if not layout_from_mo_args and layout_from_topology: mo_args['layout'] = ','.join( f'{layer['name']}({''.join(map(str.lower, layer['layout']))})' for layer in layout_from_topology ) def _add_shape_to_mo_args(self, mo_args: Dict[str, Any]) -> None: if 'input' in mo_args and 'input_shape' in mo_args: return static_shapes = [ shape for shape in self.project.topology.shapes if shape.shape_type is ModelShapeTypeEnum.static ] if static_shapes: last_shape = static_shapes[-1] mo_args['input'] = ','.join( f'{input_['name']}[{' '.join(map(str, input_['shape']))}]' for input_ in last_shape.shape_configuration ) @property def _model_optimizer_code_cell_template_context(self) -> ModelOptimizerCodeCellTemplateContext: output_directory_path = 'ir_model' mo_arguments = '' python_executable = '' mo_jobs = self._original_project.topology.mo_jobs_from_result if mo_jobs: ready_mo_jobs = [job for job in mo_jobs if job.status == StatusEnum.ready] if ready_mo_jobs: last_ready_mo_job: ModelOptimizerJobModel = sorted(ready_mo_jobs, key=lambda job: job.job_id)[-1] mo_args = last_ready_mo_job.get_mo_args_for_tool(output_directory_path=output_directory_path) mo_args.pop('stream_output', None) self._add_shape_to_mo_args(mo_args) self._add_layout_to_mo_args(mo_args) original_topology: 'TopologiesModel' = last_ready_mo_job.original_topology environment: 'EnvironmentModel' = original_topology.environment if environment: python_executable = str(environment.python_executable) mo_tool = ModelOptimizerTool(python_executable, mo_args, original_topology.framework) mo_arguments = mo_tool.console_command_params python_executable += f" -m {mo_tool.exe}" return ModelOptimizerCodeCellTemplateContext(python_executor=python_executable, mo_arguments=mo_arguments, output_directory_path=output_directory_path) @property def _set_optimized_ir_model_paths_docs_cell_template_context(self) -> CheckModelFormatDocsCellTemplateContext: return CheckModelFormatDocsCellTemplateContext(is_optimized_project=self._is_optimized_project) @property def _set_original_ir_model_paths_code_cell_template_context(self) -> SetIRModelPathsCodeCellTemplateContext: original_model_xml_file_path, original_model_bin_file_path = self._original_project.topology.files_paths return SetIRModelPathsCodeCellTemplateContext(model_xml_file_path=original_model_xml_file_path, model_bin_file_path=original_model_bin_file_path) @property def _set_optimized_ir_model_paths_code_cell_template_context(self) -> SetIRModelPathsCodeCellTemplateContext: optimized_model_xml_file_path, optimized_model_bin_file_path = self.project.topology.files_paths return SetIRModelPathsCodeCellTemplateContext(model_xml_file_path=optimized_model_xml_file_path, model_bin_file_path=optimized_model_bin_file_path) @property def _profiling_code_cell_template_context(self) -> ProfilingCodeCellTemplateContext: model_xml_file_path, _ = self.project.topology.files_paths profiling_image_path = self.project.dataset.single_file_path profiling_device = self.project.device.device_name batch = 1 streams = 1 inference_time = 20 last_profiling_job_model: Optional['ProfilingJobModel'] = self.project.last_compound_inference_job if last_profiling_job_model: last_profiling_result: 'SingleInferenceInfoModel' = last_profiling_job_model.profiling_results[-1] batch = last_profiling_result.batch streams = last_profiling_result.nireq inference_time = last_profiling_job_model.inference_time if self._has_tokenizer_section: profiling_image_path = self._get_input_file_mapping_for_profiling(batch, streams) return ProfilingCodeCellTemplateContext( python_executor=CLIToolEnum.benchmark_tool.value['path'], model_xml_path=model_xml_file_path, image_path=profiling_image_path, device=profiling_device, batch=batch, streams=streams, inference_time=inference_time, has_tokenizer_section=self._has_tokenizer_section or self.project.topology.domain is ModelDomainEnum.CV, ) def _get_input_file_mapping_for_profiling(self, batch: int, streams: int) -> str: input_names = [input_['name'] for input_ in self.project.topology.meta.layout_configuration] number_of_samples = min(batch * streams, self.project.dataset.number_images) binary_dataset_path = Path('binary_dataset') file_mapping = { input_name: [str(binary_dataset_path / f'{input_name}_{idx:03d}.bin') for idx in range(number_of_samples)] for input_name in input_names } return ','.join( f'{input_name}:' + ','.join(files) for input_name, files in file_mapping.items() ) @property def _accuracy_docs_cell_template_context(self) -> AccuracyDocsCellTemplateContext: yaml_config_path = AccuracyConfigFileDumper.get_relative_config_file_path() return AccuracyDocsCellTemplateContext(yaml_config_path=str(yaml_config_path)) @property def _accuracy_code_cell_template_context(self) -> AccuracyCodeCellTemplateContext: yaml_config_path = self._accuracy_docs_cell_template_context['yaml_config_path'] model_xml_file_path, _ = self.project.topology.files_paths last_accuracy_job_model = self.project.get_last_job_by_type(job_type=JobTypesEnum.accuracy_type.value) json_config = last_accuracy_job_model.accuracy_config if last_accuracy_job_model else None model_directory_path = os.path.dirname(model_xml_file_path) if model_xml_file_path else None images_directory_path = os.path.dirname( self.project.dataset.single_file_path) if self.project.dataset.single_file_path else None return AccuracyCodeCellTemplateContext(yaml_config_path=str(yaml_config_path), json_config=json_config, model_directory_path=model_directory_path, images_directory_path=images_directory_path) @property def _int8_optimization_docs_cell_template_context(self) -> Int8OptimizationDocsCellTemplateContext: int8_optimization_config_path = Int8OptimizationConfigFileDumper.get_relative_config_file_path() return Int8OptimizationDocsCellTemplateContext( is_optimized_project=self._is_optimized_project, int8_optimization_config_path=str(int8_optimization_config_path)) @property def _int8_optimization_code_cell_template_context(self) -> Int8OptimizationCodeCellTemplateContext: int8_optimization_config_path = self._int8_optimization_docs_cell_template_context[ 'int8_optimization_config_path'] last_int8_job_model = self.project.get_last_job_by_type(job_type=JobTypesEnum.int8calibration_type.value) int8_optimization_config = '' if last_int8_job_model: int8_optimization_config = last_int8_job_model.int8_config_file_content output_directory_path = 'int8_optimization_result' return Int8OptimizationCodeCellTemplateContext(int8_optimization_config_path=str(int8_optimization_config_path), int8_optimization_config=int8_optimization_config, output_directory_path=output_directory_path) @property def _install_requirements_template_context(self) -> InstallRequirementsCodeCellTemplateContext: return InstallRequirementsCodeCellTemplateContext( requirements_file=( 'requirements_nlp.txt' if self.project.topology.domain is ModelDomainEnum.NLP else 'requirements.txt' ) ) @property def _tokenizer_parameters_template_context(self) -> TokenizerParametersTemplateContext: batch = 1 streams = 1 last_profiling_job_model: Optional['ProfilingJobModel'] = self.project.last_compound_inference_job if last_profiling_job_model: last_profiling_result: 'SingleInferenceInfoModel' = last_profiling_job_model.profiling_results[-1] batch = last_profiling_result.batch streams = last_profiling_result.nireq tokenizer = self.project.topology.tokenizer_model tokenizer_path = tokenizer.path if tokenizer else None return TokenizerParametersTemplateContext( dataset_path=self.project.dataset.single_file_path, tokenizer_path=tokenizer_path, batch=batch, streams=streams, ) _job_type_to_update_cell_ids_map = { JobTypesEnum.profiling_type: [ NotebookCellIds.intro_docs, NotebookCellIds.set_original_ir_model_paths_code, NotebookCellIds.tokenizer_parameters_code, NotebookCellIds.profiling_code, NotebookCellIds.accuracy_code, ], JobTypesEnum.accuracy_type: [ NotebookCellIds.intro_docs, NotebookCellIds.accuracy_code, ], JobTypesEnum.int8calibration_type: [ NotebookCellIds.int8_optimization_code, NotebookCellIds.set_optimized_ir_model_paths_code, ], } _orm_event_to_update_cell_ids_map = { 'TokenizerToTopologyModel': { "after_update": [ NotebookCellIds.intro_docs, NotebookCellIds.tokenizer_parameters_code, NotebookCellIds.profiling_code, ] }, 'TokenizerModel': { "after_delete": [ NotebookCellIds.intro_docs, NotebookCellIds.profiling_code, ] }, } _cell_id_to_context_getter_map = { NotebookCellIds.intro_docs: _intro_cell_template_context, NotebookCellIds.obtain_model_docs: _obtain_model_docs_cell_template_context, NotebookCellIds.model_downloader_code: _model_downloader_code_cell_template_context, NotebookCellIds.model_downloader_result_docs: _model_downloader_code_cell_template_context, NotebookCellIds.model_converter_code: _model_converter_code_cell_template_context, NotebookCellIds.model_converter_result_docs: _model_converter_code_cell_template_context, NotebookCellIds.model_optimizer_docs: _obtain_model_docs_cell_template_context, NotebookCellIds.model_optimizer_code: _model_optimizer_code_cell_template_context, NotebookCellIds.model_optimizer_result_docs: _model_optimizer_code_cell_template_context, NotebookCellIds.set_original_ir_model_paths_code: _set_original_ir_model_paths_code_cell_template_context, NotebookCellIds.set_optimized_ir_model_paths_docs: _set_optimized_ir_model_paths_docs_cell_template_context, NotebookCellIds.set_optimized_ir_model_paths_code: _set_optimized_ir_model_paths_code_cell_template_context, NotebookCellIds.profiling_code: _profiling_code_cell_template_context, NotebookCellIds.accuracy_docs: _accuracy_docs_cell_template_context, NotebookCellIds.check_accuracy_config_code: _accuracy_docs_cell_template_context, NotebookCellIds.accuracy_code: _accuracy_code_cell_template_context, NotebookCellIds.int8_optimization_docs: _int8_optimization_docs_cell_template_context, NotebookCellIds.check_int8_optimization_config_code: _int8_optimization_docs_cell_template_context, NotebookCellIds.int8_optimization_code: _int8_optimization_code_cell_template_context, NotebookCellIds.int8_optimization_result_docs: _int8_optimization_code_cell_template_context, NotebookCellIds.tokenizer_parameters_code: _tokenizer_parameters_template_context, NotebookCellIds.install_python_requirements_code: _install_requirements_template_context } @event.listens_for(JupyterNotebookModel, 'after_insert', propagate=True) def create_jupyter_notebook_for_new_project(_: Mapper, connection: Connection, jupyter_notebook: JupyterNotebookModel): session_maker = sessionmaker(bind=connection, autocommit=False) session = session_maker() with closing(session): jupyter_notebook: JupyterNotebookModel = session.query(JupyterNotebookModel).get(jupyter_notebook.id) initial_cells_context_map = jupyter_notebook.initial_cells_context_map notebook_dumper = jupyter_notebook.jupyter_notebook_dumper notebook_dumper.create_notebook(cells_context_map=initial_cells_context_map) @event.listens_for(JupyterNotebookModel, 'after_delete', propagate=True) def handle_after_delete_notebook(_: Mapper, connection: Connection, jupyter_notebook: JupyterNotebookModel): session_maker = sessionmaker(bind=connection, autocommit=False) session = session_maker() with closing(session): notebook_dumper = jupyter_notebook.jupyter_notebook_dumper notebook_dumper.delete_notebook()
""" OpenVINO DL Workbench Class for ORM model described Jupyter notebook abstraction Copyright (c) 2021 Intel Corporation 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 http://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. """ import os from contextlib import closing from pathlib import Path from typing import Dict, Optional, Any from sqlalchemy import Column, String, Integer, ForeignKey, event from sqlalchemy.engine import Connection from sqlalchemy.orm import relationship, backref, Mapper, Session, sessionmaker from config.constants import JUPYTER_NOTEBOOKS_FOLDER, ESSENTIAL_DATA_FOLDER from wb.main.console_tool_wrapper.model_optimizer.tool import ModelOptimizerTool from wb.main.enumerates import ModelPrecisionEnum, JobTypesEnum, StatusEnum, OptimizationTypesEnum, ModelDomainEnum, \ ModelShapeTypeEnum from wb.main.jupyter_notebooks.cell_template_contexts import IntroCellTemplateContext, \ SetIRModelPathsCodeCellTemplateContext, ProfilingCodeCellTemplateContext, AccuracyDocsCellTemplateContext, \ AccuracyCodeCellTemplateContext, Int8OptimizationCodeCellTemplateContext, Int8OptimizationDocsCellTemplateContext, \ ObtainModelDocsCellTemplateContext, ModelDownloaderCodeCellTemplateContext, \ CheckModelFormatDocsCellTemplateContext, ModelConverterCodeCellTemplateContext, \ ModelOptimizerCodeCellTemplateContext, InstallRequirementsCodeCellTemplateContext, \ TokenizerParametersTemplateContext from wb.main.jupyter_notebooks.cli_tools_options import CLIToolEnum from wb.main.jupyter_notebooks.config_file_dumpers import AccuracyConfigFileDumper, Int8OptimizationConfigFileDumper from wb.main.jupyter_notebooks.jupyter_notebook_cell import NotebookCellIds from wb.main.jupyter_notebooks.jupyter_notebook_dumper import JupyterNotebookDumper from wb.main.jupyter_notebooks.notebook_template_creator import NotebookTemplateCreator from wb.main.models.base_model import BaseModel from wb.main.models.model_optimizer_job_model import ModelOptimizerJobModel class JupyterNotebookModel(BaseModel): __tablename__ = 'jupyter_notebooks' id = Column(Integer, primary_key=True, autoincrement=True) project_id = Column(Integer, ForeignKey('projects.id'), nullable=True) name = Column(String, nullable=False) # Relationships project: 'ProjectsModel' = relationship('ProjectsModel', backref=backref('jupyter_notebook', cascade='delete,all', uselist=False), foreign_keys=[project_id]) def __init__(self, project_id: int): self.project_id = project_id self.name = f'project_{self.project_id}.ipynb' @property def notebook_directory_path(self) -> str: return str(Path(JUPYTER_NOTEBOOKS_FOLDER).resolve().absolute() / str(self.id)) @property def notebook_path(self) -> str: return os.path.join(self.notebook_directory_path, self.name) @property def notebook_relative_path(self) -> str: return os.path.relpath(path=self.notebook_path, start=ESSENTIAL_DATA_FOLDER) @property def notebook_exists(self) -> bool: return os.path.isfile(self.notebook_path) @staticmethod def get_jupyter_notebook_model(project_id: int, session: Session) -> 'JupyterNotebookModel': jupyter_notebook_model: JupyterNotebookModel = session.query(JupyterNotebookModel).filter( JupyterNotebookModel.project_id == project_id ).first() if not jupyter_notebook_model: raise Exception(f'Jupyter notebook model not found for project id {project_id}') if not os.path.isfile(jupyter_notebook_model.notebook_path): raise Exception(f'Jupyter notebook file not found in path {jupyter_notebook_model.notebook_path}') return jupyter_notebook_model @property def jupyter_notebook_dumper(self) -> JupyterNotebookDumper: topology: 'TopologiesModel' = self.project.topology.optimized_from_record or self.project.topology is_nlp = topology.domain == ModelDomainEnum.NLP has_tokenizer = topology.tokenizer_model is not None notebook_template_creator = NotebookTemplateCreator(notebook_type=self.project.optimization_type, original_model_source=topology.source, original_model_framework=topology.original_model_framework, is_nlp=is_nlp, has_tokenizer=has_tokenizer,) return JupyterNotebookDumper(notebook_path=self.notebook_path, notebook_template_creator=notebook_template_creator) @property def initial_cells_context_map(self) -> Dict[NotebookCellIds, dict]: return { key: getter.__get__(self) for key, getter in self._cell_id_to_context_getter_map.items() } def _get_cell_template_context(self, cell_id: NotebookCellIds) -> dict: cell_context_getter = self._cell_id_to_context_getter_map.get(cell_id) if not cell_context_getter: raise Exception(f'No template context found for cell with id {cell_id}') return cell_context_getter.__get__(self) def update_cell_by_job_type(self, job_type: JobTypesEnum): cell_ids_to_update = self._job_type_to_update_cell_ids_map.get(job_type) if not cell_ids_to_update: raise Exception(f'No Jupyter notebook cell found to update for job with type {job_type}') notebook_dumper = self.jupyter_notebook_dumper cell_ids_to_update = [cell for cell in cell_ids_to_update if cell in notebook_dumper] for cell_id_to_update in cell_ids_to_update: cell_template_context = self._get_cell_template_context(cell_id=cell_id_to_update) notebook_dumper.update_cell(cell_id=cell_id_to_update, cell_template_context=cell_template_context) # Update int8 optimization cell for parent project notebook if cell_id_to_update == NotebookCellIds.int8_optimization_code: current_session = Session.object_session(self) parent_project = self.project.get_parent_project(session=current_session) if not parent_project: continue parent_project_notebook: JupyterNotebookModel = parent_project.jupyter_notebook if not parent_project_notebook or not parent_project_notebook.notebook_exists: continue parent_project_notebook_dumper: JupyterNotebookDumper = parent_project_notebook.jupyter_notebook_dumper parent_project_notebook_dumper.update_cell(cell_id=cell_id_to_update, cell_template_context=cell_template_context) def update_notebook_by_orm_event(self, model_class: BaseModel, orm_event: str): cell_ids_to_update = self._orm_event_to_update_cell_ids_map[model_class][orm_event] notebook_dumper = self.jupyter_notebook_dumper self.jupyter_notebook_dumper.update_notebook_cells() for cell_id_to_update in cell_ids_to_update: cell_template_context = self._get_cell_template_context(cell_id=cell_id_to_update) notebook_dumper.update_cell( cell_id=cell_id_to_update, cell_template_context=cell_template_context ) @property def _original_project(self) -> 'ProjectsModel': current_session = Session.object_session(self) return self.project.get_parent_project(session=current_session) or self.project @property def _is_optimized_project(self) -> bool: return self.project.optimization_type == OptimizationTypesEnum.int8calibration @property def _has_accuracy_checker_section(self) -> bool: return NotebookCellIds.accuracy_code in self.jupyter_notebook_dumper @property def _has_int8_calibration_section(self) -> bool: return NotebookCellIds.int8_optimization_code in self.jupyter_notebook_dumper @property def _has_tokenizer_section(self) -> bool: return NotebookCellIds.load_tokenizer_code in self.jupyter_notebook_dumper @property def _intro_cell_template_context(self) -> IntroCellTemplateContext: original_project: 'ProjectsModel' = self._original_project topology: 'TopologiesModel' = original_project.topology topology_json: dict = topology.json() model_task_type = topology_json.get('accuracyConfiguration', {}).get('taskType') project_model_framework = topology.original_model_framework.value model_precisions = topology.get_precisions() mo_params = topology_json.get('analysis', {}).get('moParams', {}) topology_analysis_precision = ModelPrecisionEnum.fp16.value if mo_params: topology_analysis_precision = mo_params['dataType'] model_precisions = ', '.join(model_precisions) if model_precisions else topology_analysis_precision return IntroCellTemplateContext( is_optimized_project=self._is_optimized_project, project_model_name=topology.name, project_model_domain=topology.domain.value if topology.domain else "Generic", project_device_name=original_project.device.device_name, project_model_task_type=model_task_type, project_model_framework=project_model_framework, project_model_precisions=model_precisions, has_tokenizer_section=self._has_tokenizer_section, has_accuracy_checker_section=self._has_accuracy_checker_section, has_int8_calibration_section=self._has_int8_calibration_section, ) @property def _python_executable(self) -> str: topology = self._original_project.topology python_executable = '' environment: 'EnvironmentModel' = topology.environment if environment: python_executable = environment.python_executable return str(python_executable) @property def _obtain_model_docs_cell_template_context(self) -> ObtainModelDocsCellTemplateContext: topology: 'TopologiesModel' = self._original_project.topology project_model_framework = topology.original_model_framework.value if topology.original_model_framework else None project_model_source = topology.source.value if topology.source else None return ObtainModelDocsCellTemplateContext( project_model_name=topology.name, project_model_framework=project_model_framework, project_model_source=project_model_source) @property def _model_downloader_code_cell_template_context(self) -> ModelDownloaderCodeCellTemplateContext: output_directory_path = 'downloaded_model' return ModelDownloaderCodeCellTemplateContext( omz_model_name=self.project.topology.name, output_directory_path=output_directory_path) @property def _model_converter_code_cell_template_context(self) -> ModelConverterCodeCellTemplateContext: model_downloader_cell_context = self._model_downloader_code_cell_template_context output_directory_path = 'ir_model' return ModelConverterCodeCellTemplateContext( omz_model_name=model_downloader_cell_context['omz_model_name'], download_directory_path=model_downloader_cell_context['output_directory_path'], output_directory_path=output_directory_path) def _add_layout_to_mo_args(self, mo_args: Dict[str, Any]) -> None: layout_from_mo_args = mo_args.get('layout') layout_from_topology = self.project.topology.meta.layout_configuration if not layout_from_mo_args and layout_from_topology: mo_args['layout'] = ','.join( f'{layer["name"]}({"".join(map(str.lower, layer["layout"]))})' for layer in layout_from_topology ) def _add_shape_to_mo_args(self, mo_args: Dict[str, Any]) -> None: if 'input' in mo_args and 'input_shape' in mo_args: return static_shapes = [ shape for shape in self.project.topology.shapes if shape.shape_type is ModelShapeTypeEnum.static ] if static_shapes: last_shape = static_shapes[-1] mo_args['input'] = ','.join( f'{input_["name"]}[{" ".join(map(str, input_["shape"]))}]' for input_ in last_shape.shape_configuration ) @property def _model_optimizer_code_cell_template_context(self) -> ModelOptimizerCodeCellTemplateContext: output_directory_path = 'ir_model' mo_arguments = '' python_executable = '' mo_jobs = self._original_project.topology.mo_jobs_from_result if mo_jobs: ready_mo_jobs = [job for job in mo_jobs if job.status == StatusEnum.ready] if ready_mo_jobs: last_ready_mo_job: ModelOptimizerJobModel = sorted(ready_mo_jobs, key=lambda job: job.job_id)[-1] mo_args = last_ready_mo_job.get_mo_args_for_tool(output_directory_path=output_directory_path) mo_args.pop('stream_output', None) self._add_shape_to_mo_args(mo_args) self._add_layout_to_mo_args(mo_args) original_topology: 'TopologiesModel' = last_ready_mo_job.original_topology environment: 'EnvironmentModel' = original_topology.environment if environment: python_executable = str(environment.python_executable) mo_tool = ModelOptimizerTool(python_executable, mo_args, original_topology.framework) mo_arguments = mo_tool.console_command_params python_executable += f" -m {mo_tool.exe}" return ModelOptimizerCodeCellTemplateContext(python_executor=python_executable, mo_arguments=mo_arguments, output_directory_path=output_directory_path) @property def _set_optimized_ir_model_paths_docs_cell_template_context(self) -> CheckModelFormatDocsCellTemplateContext: return CheckModelFormatDocsCellTemplateContext(is_optimized_project=self._is_optimized_project) @property def _set_original_ir_model_paths_code_cell_template_context(self) -> SetIRModelPathsCodeCellTemplateContext: original_model_xml_file_path, original_model_bin_file_path = self._original_project.topology.files_paths return SetIRModelPathsCodeCellTemplateContext(model_xml_file_path=original_model_xml_file_path, model_bin_file_path=original_model_bin_file_path) @property def _set_optimized_ir_model_paths_code_cell_template_context(self) -> SetIRModelPathsCodeCellTemplateContext: optimized_model_xml_file_path, optimized_model_bin_file_path = self.project.topology.files_paths return SetIRModelPathsCodeCellTemplateContext(model_xml_file_path=optimized_model_xml_file_path, model_bin_file_path=optimized_model_bin_file_path) @property def _profiling_code_cell_template_context(self) -> ProfilingCodeCellTemplateContext: model_xml_file_path, _ = self.project.topology.files_paths profiling_image_path = self.project.dataset.single_file_path profiling_device = self.project.device.device_name batch = 1 streams = 1 inference_time = 20 last_profiling_job_model: Optional['ProfilingJobModel'] = self.project.last_compound_inference_job if last_profiling_job_model: last_profiling_result: 'SingleInferenceInfoModel' = last_profiling_job_model.profiling_results[-1] batch = last_profiling_result.batch streams = last_profiling_result.nireq inference_time = last_profiling_job_model.inference_time if self._has_tokenizer_section: profiling_image_path = self._get_input_file_mapping_for_profiling(batch, streams) return ProfilingCodeCellTemplateContext( python_executor=CLIToolEnum.benchmark_tool.value['path'], model_xml_path=model_xml_file_path, image_path=profiling_image_path, device=profiling_device, batch=batch, streams=streams, inference_time=inference_time, has_tokenizer_section=self._has_tokenizer_section or self.project.topology.domain is ModelDomainEnum.CV, ) def _get_input_file_mapping_for_profiling(self, batch: int, streams: int) -> str: input_names = [input_['name'] for input_ in self.project.topology.meta.layout_configuration] number_of_samples = min(batch * streams, self.project.dataset.number_images) binary_dataset_path = Path('binary_dataset') file_mapping = { input_name: [str(binary_dataset_path / f'{input_name}_{idx:03d}.bin') for idx in range(number_of_samples)] for input_name in input_names } return ','.join( f'{input_name}:' + ','.join(files) for input_name, files in file_mapping.items() ) @property def _accuracy_docs_cell_template_context(self) -> AccuracyDocsCellTemplateContext: yaml_config_path = AccuracyConfigFileDumper.get_relative_config_file_path() return AccuracyDocsCellTemplateContext(yaml_config_path=str(yaml_config_path)) @property def _accuracy_code_cell_template_context(self) -> AccuracyCodeCellTemplateContext: yaml_config_path = self._accuracy_docs_cell_template_context['yaml_config_path'] model_xml_file_path, _ = self.project.topology.files_paths last_accuracy_job_model = self.project.get_last_job_by_type(job_type=JobTypesEnum.accuracy_type.value) json_config = last_accuracy_job_model.accuracy_config if last_accuracy_job_model else None model_directory_path = os.path.dirname(model_xml_file_path) if model_xml_file_path else None images_directory_path = os.path.dirname( self.project.dataset.single_file_path) if self.project.dataset.single_file_path else None return AccuracyCodeCellTemplateContext(yaml_config_path=str(yaml_config_path), json_config=json_config, model_directory_path=model_directory_path, images_directory_path=images_directory_path) @property def _int8_optimization_docs_cell_template_context(self) -> Int8OptimizationDocsCellTemplateContext: int8_optimization_config_path = Int8OptimizationConfigFileDumper.get_relative_config_file_path() return Int8OptimizationDocsCellTemplateContext( is_optimized_project=self._is_optimized_project, int8_optimization_config_path=str(int8_optimization_config_path)) @property def _int8_optimization_code_cell_template_context(self) -> Int8OptimizationCodeCellTemplateContext: int8_optimization_config_path = self._int8_optimization_docs_cell_template_context[ 'int8_optimization_config_path'] last_int8_job_model = self.project.get_last_job_by_type(job_type=JobTypesEnum.int8calibration_type.value) int8_optimization_config = '' if last_int8_job_model: int8_optimization_config = last_int8_job_model.int8_config_file_content output_directory_path = 'int8_optimization_result' return Int8OptimizationCodeCellTemplateContext(int8_optimization_config_path=str(int8_optimization_config_path), int8_optimization_config=int8_optimization_config, output_directory_path=output_directory_path) @property def _install_requirements_template_context(self) -> InstallRequirementsCodeCellTemplateContext: return InstallRequirementsCodeCellTemplateContext( requirements_file=( 'requirements_nlp.txt' if self.project.topology.domain is ModelDomainEnum.NLP else 'requirements.txt' ) ) @property def _tokenizer_parameters_template_context(self) -> TokenizerParametersTemplateContext: batch = 1 streams = 1 last_profiling_job_model: Optional['ProfilingJobModel'] = self.project.last_compound_inference_job if last_profiling_job_model: last_profiling_result: 'SingleInferenceInfoModel' = last_profiling_job_model.profiling_results[-1] batch = last_profiling_result.batch streams = last_profiling_result.nireq tokenizer = self.project.topology.tokenizer_model tokenizer_path = tokenizer.path if tokenizer else None return TokenizerParametersTemplateContext( dataset_path=self.project.dataset.single_file_path, tokenizer_path=tokenizer_path, batch=batch, streams=streams, ) _job_type_to_update_cell_ids_map = { JobTypesEnum.profiling_type: [ NotebookCellIds.intro_docs, NotebookCellIds.set_original_ir_model_paths_code, NotebookCellIds.tokenizer_parameters_code, NotebookCellIds.profiling_code, NotebookCellIds.accuracy_code, ], JobTypesEnum.accuracy_type: [ NotebookCellIds.intro_docs, NotebookCellIds.accuracy_code, ], JobTypesEnum.int8calibration_type: [ NotebookCellIds.int8_optimization_code, NotebookCellIds.set_optimized_ir_model_paths_code, ], } _orm_event_to_update_cell_ids_map = { 'TokenizerToTopologyModel': { "after_update": [ NotebookCellIds.intro_docs, NotebookCellIds.tokenizer_parameters_code, NotebookCellIds.profiling_code, ] }, 'TokenizerModel': { "after_delete": [ NotebookCellIds.intro_docs, NotebookCellIds.profiling_code, ] }, } _cell_id_to_context_getter_map = { NotebookCellIds.intro_docs: _intro_cell_template_context, NotebookCellIds.obtain_model_docs: _obtain_model_docs_cell_template_context, NotebookCellIds.model_downloader_code: _model_downloader_code_cell_template_context, NotebookCellIds.model_downloader_result_docs: _model_downloader_code_cell_template_context, NotebookCellIds.model_converter_code: _model_converter_code_cell_template_context, NotebookCellIds.model_converter_result_docs: _model_converter_code_cell_template_context, NotebookCellIds.model_optimizer_docs: _obtain_model_docs_cell_template_context, NotebookCellIds.model_optimizer_code: _model_optimizer_code_cell_template_context, NotebookCellIds.model_optimizer_result_docs: _model_optimizer_code_cell_template_context, NotebookCellIds.set_original_ir_model_paths_code: _set_original_ir_model_paths_code_cell_template_context, NotebookCellIds.set_optimized_ir_model_paths_docs: _set_optimized_ir_model_paths_docs_cell_template_context, NotebookCellIds.set_optimized_ir_model_paths_code: _set_optimized_ir_model_paths_code_cell_template_context, NotebookCellIds.profiling_code: _profiling_code_cell_template_context, NotebookCellIds.accuracy_docs: _accuracy_docs_cell_template_context, NotebookCellIds.check_accuracy_config_code: _accuracy_docs_cell_template_context, NotebookCellIds.accuracy_code: _accuracy_code_cell_template_context, NotebookCellIds.int8_optimization_docs: _int8_optimization_docs_cell_template_context, NotebookCellIds.check_int8_optimization_config_code: _int8_optimization_docs_cell_template_context, NotebookCellIds.int8_optimization_code: _int8_optimization_code_cell_template_context, NotebookCellIds.int8_optimization_result_docs: _int8_optimization_code_cell_template_context, NotebookCellIds.tokenizer_parameters_code: _tokenizer_parameters_template_context, NotebookCellIds.install_python_requirements_code: _install_requirements_template_context } @event.listens_for(JupyterNotebookModel, 'after_insert', propagate=True) def create_jupyter_notebook_for_new_project(_: Mapper, connection: Connection, jupyter_notebook: JupyterNotebookModel): session_maker = sessionmaker(bind=connection, autocommit=False) session = session_maker() with closing(session): jupyter_notebook: JupyterNotebookModel = session.query(JupyterNotebookModel).get(jupyter_notebook.id) initial_cells_context_map = jupyter_notebook.initial_cells_context_map notebook_dumper = jupyter_notebook.jupyter_notebook_dumper notebook_dumper.create_notebook(cells_context_map=initial_cells_context_map) @event.listens_for(JupyterNotebookModel, 'after_delete', propagate=True) def handle_after_delete_notebook(_: Mapper, connection: Connection, jupyter_notebook: JupyterNotebookModel): session_maker = sessionmaker(bind=connection, autocommit=False) session = session_maker() with closing(session): notebook_dumper = jupyter_notebook.jupyter_notebook_dumper notebook_dumper.delete_notebook()
#AUTOGENERATED! DO NOT EDIT! File to edit: dev/15_callback.hook.ipynb (unless otherwise specified). __all__ = ['Hook', 'hook_output', 'Hooks', 'hook_outputs', 'dummy_eval', 'model_sizes', 'num_features_model', 'has_params', 'HookCallback', 'total_params', 'layer_info', 'ActivationStats'] #Cell from ..test import * from ..basics import * #Cell @docs class Hook(): "Create a hook on `m` with `hook_func`." def __init__(self, m, hook_func, is_forward=True, detach=True, cpu=False, gather=False): store_attr(self,'hook_func,detach,cpu,gather') f = m.register_forward_hook if is_forward else m.register_backward_hook self.hook = f(self.hook_fn) self.stored,self.removed = None,False def hook_fn(self, module, input, output): "Applies `hook_func` to `module`, `input`, `output`." if self.detach: input,output = to_detach(input, cpu=self.cpu, gather=self.gather),to_detach(output, cpu=self.cpu, gather=self.gather) self.stored = self.hook_func(module, input, output) def remove(self): "Remove the hook from the model." if not self.removed: self.hook.remove() self.removed=True def __enter__(self, *args): return self def __exit__(self, *args): self.remove() _docs = dict(__enter__="Register the hook", __exit__="Remove the hook") #Cell def _hook_inner(m,i,o): return o if isinstance(o,Tensor) or is_listy(o) else list(o) def hook_output(module, detach=True, cpu=False, grad=False): "Return a `Hook` that stores activations of `module` in `self.stored`" return Hook(module, _hook_inner, detach=detach, cpu=cpu, is_forward=not grad) #Cell @docs class Hooks(): "Create several hooks on the modules in `ms` with `hook_func`." def __init__(self, ms, hook_func, is_forward=True, detach=True, cpu=False): self.hooks = [Hook(m, hook_func, is_forward, detach, cpu) for m in ms] def __getitem__(self,i): return self.hooks[i] def __len__(self): return len(self.hooks) def __iter__(self): return iter(self.hooks) @property def stored(self): return L(o.stored for o in self) def remove(self): "Remove the hooks from the model." for h in self.hooks: h.remove() def __enter__(self, *args): return self def __exit__ (self, *args): self.remove() _docs = dict(stored = "The states saved in each hook.", __enter__="Register the hooks", __exit__="Remove the hooks") #Cell def hook_outputs(modules, detach=True, cpu=False, grad=False): "Return `Hooks` that store activations of all `modules` in `self.stored`" return Hooks(modules, _hook_inner, detach=detach, cpu=cpu, is_forward=not grad) #Cell def dummy_eval(m, size=(64,64)): "Evaluate `m` on a dummy input of a certain `size`" ch_in = in_channels(m) x = one_param(m).new(1, ch_in, *size).requires_grad_(False).uniform_(-1.,1.) with torch.no_grad(): return m.eval()(x) #Cell def model_sizes(m, size=(64,64)): "Pass a dummy input through the model `m` to get the various sizes of activations." with hook_outputs(m) as hooks: _ = dummy_eval(m, size=size) return [o.stored.shape for o in hooks] #Cell def num_features_model(m): "Return the number of output features for `m`." sz,ch_in = 32,in_channels(m) while True: #Trying for a few sizes in case the model requires a big input size. try: return model_sizes(m, (sz,sz))[-1][1] except Exception as e: sz *= 2 if sz > 2048: raise e #Cell def has_params(m): "Check if `m` has at least one parameter" return len(list(m.parameters())) > 0 #Cell @funcs_kwargs class HookCallback(Callback): "`Callback` that can be used to register hooks on `modules`" _methods = ["hook"] hook = noops def __init__(self, modules=None, every=None, remove_end=True, is_forward=True, detach=True, cpu=True, **kwargs): store_attr(self, 'modules,every,remove_end,is_forward,detach,cpu') assert not kwargs def begin_fit(self): "Register the `Hooks` on `self.modules`." if self.modules is None: self.modules = [m for m in flatten_model(self.model) if has_params(m)] if self.every is None: self._register() def begin_batch(self): if self.every is None: return if self.training and self.train_iter%self.every==0: self._register() def after_batch(self): if self.every is None: return if self.training and self.train_iter%self.every==0: self._remove() def after_fit(self): "Remove the `Hooks`." if self.remove_end: self._remove() def _register(self): self.hooks = Hooks(self.modules, self.hook, self.is_forward, self.detach, self.cpu) def _remove(self): if getattr(self, 'hooks', None): self.hooks.remove() def __del__(self): self._remove() #Cell def total_params(m): "Give the number of parameters of a module and if it's trainable or not" params = sum([p.numel() for p in m.parameters()]) trains = [p.requires_grad for p in m.parameters()] return params, (False if len(trains)==0 else trains[0]) #Cell def layer_info(learn): def _track(m, i, o): return (m.__class__.__name__,)+total_params(m)+(apply(lambda x:x.shape, o),) layers = [m for m in flatten_model(learn.model)] xb,_ = learn.dbunch.train_dl.one_batch() with Hooks(layers, _track) as h: _ = learn.model.eval()(apply(lambda o:o[:1], xb)) return xb,h.stored #Cell def _print_shapes(o, bs): if isinstance(o, torch.Size): return ' x '.join([str(bs)] + [str(t) for t in o[1:]]) else: return [_print_shapes(x, bs) for x in o] #Cell @patch def summary(self:Learner): "Print a summary of the model, optimizer and loss function." xb,infos = layer_info(self) n,bs = 64,find_bs(xb) inp_sz = _print_shapes(apply(lambda x:x.shape, xb), bs) res = f"{self.model.__class__.__name__} (Input shape: {inp_sz})\n" res += "=" * n + "\n" res += f"{"Layer (type)":<20} {"Output Shape":<20} {"Param #":<10} {"Trainable":<10}\n" res += "=" * n + "\n" ps,trn_ps = 0,0 infos = [o for o in infos if o is not None] #see comment in previous cell for typ,np,trn,sz in infos: if sz is None: continue ps += np if trn: trn_ps += np res += f"{typ:<20} {_print_shapes(sz, bs):<20} {np:<10,} {str(trn):<10}\n" res += "_" * n + "\n" res += f"\nTotal params: {ps:,}\n" res += f"Total trainable params: {trn_ps:,}\n" res += f"Total non-trainable params: {ps - trn_ps:,}\n\n" res += f"Optimizer used: {self.opt_func}\nLoss function: {self.loss_func}\n\n" if self.opt is not None: res += f"Model " + ("unfrozen\n\n" if self.opt.frozen_idx==0 else f"frozen up to parameter group number {self.opt.frozen_idx}\n\n") res += "Callbacks:\n" + '\n'.join(f" - {cb}" for cb in sort_by_run(self.cbs)) return PrettyString(res) #Cell @delegates() class ActivationStats(HookCallback): "Callback that record the mean and std of activations." run_before=TrainEvalCallback def __init__(self, with_hist=False, **kwargs): super().__init__(**kwargs) self.with_hist = with_hist def begin_fit(self): "Initialize stats." super().begin_fit() self.stats = L() def hook(self, m, i, o): o = o.float() res = {'mean': o.mean().item(), 'std': o.std().item(), 'percent_null': (o<=0.05).long().sum().item()/o.numel()} if self.with_hist: res['hist'] = o.histc(40,0,10) return res def after_batch(self): "Take the stored results and puts it in `self.stats`" if self.training and (self.every is None or self.train_iter%self.every != 0): self.stats.append(self.hooks.stored) super().after_batch()
#AUTOGENERATED! DO NOT EDIT! File to edit: dev/15_callback.hook.ipynb (unless otherwise specified). __all__ = ['Hook', 'hook_output', 'Hooks', 'hook_outputs', 'dummy_eval', 'model_sizes', 'num_features_model', 'has_params', 'HookCallback', 'total_params', 'layer_info', 'ActivationStats'] #Cell from ..test import * from ..basics import * #Cell @docs class Hook(): "Create a hook on `m` with `hook_func`." def __init__(self, m, hook_func, is_forward=True, detach=True, cpu=False, gather=False): store_attr(self,'hook_func,detach,cpu,gather') f = m.register_forward_hook if is_forward else m.register_backward_hook self.hook = f(self.hook_fn) self.stored,self.removed = None,False def hook_fn(self, module, input, output): "Applies `hook_func` to `module`, `input`, `output`." if self.detach: input,output = to_detach(input, cpu=self.cpu, gather=self.gather),to_detach(output, cpu=self.cpu, gather=self.gather) self.stored = self.hook_func(module, input, output) def remove(self): "Remove the hook from the model." if not self.removed: self.hook.remove() self.removed=True def __enter__(self, *args): return self def __exit__(self, *args): self.remove() _docs = dict(__enter__="Register the hook", __exit__="Remove the hook") #Cell def _hook_inner(m,i,o): return o if isinstance(o,Tensor) or is_listy(o) else list(o) def hook_output(module, detach=True, cpu=False, grad=False): "Return a `Hook` that stores activations of `module` in `self.stored`" return Hook(module, _hook_inner, detach=detach, cpu=cpu, is_forward=not grad) #Cell @docs class Hooks(): "Create several hooks on the modules in `ms` with `hook_func`." def __init__(self, ms, hook_func, is_forward=True, detach=True, cpu=False): self.hooks = [Hook(m, hook_func, is_forward, detach, cpu) for m in ms] def __getitem__(self,i): return self.hooks[i] def __len__(self): return len(self.hooks) def __iter__(self): return iter(self.hooks) @property def stored(self): return L(o.stored for o in self) def remove(self): "Remove the hooks from the model." for h in self.hooks: h.remove() def __enter__(self, *args): return self def __exit__ (self, *args): self.remove() _docs = dict(stored = "The states saved in each hook.", __enter__="Register the hooks", __exit__="Remove the hooks") #Cell def hook_outputs(modules, detach=True, cpu=False, grad=False): "Return `Hooks` that store activations of all `modules` in `self.stored`" return Hooks(modules, _hook_inner, detach=detach, cpu=cpu, is_forward=not grad) #Cell def dummy_eval(m, size=(64,64)): "Evaluate `m` on a dummy input of a certain `size`" ch_in = in_channels(m) x = one_param(m).new(1, ch_in, *size).requires_grad_(False).uniform_(-1.,1.) with torch.no_grad(): return m.eval()(x) #Cell def model_sizes(m, size=(64,64)): "Pass a dummy input through the model `m` to get the various sizes of activations." with hook_outputs(m) as hooks: _ = dummy_eval(m, size=size) return [o.stored.shape for o in hooks] #Cell def num_features_model(m): "Return the number of output features for `m`." sz,ch_in = 32,in_channels(m) while True: #Trying for a few sizes in case the model requires a big input size. try: return model_sizes(m, (sz,sz))[-1][1] except Exception as e: sz *= 2 if sz > 2048: raise e #Cell def has_params(m): "Check if `m` has at least one parameter" return len(list(m.parameters())) > 0 #Cell @funcs_kwargs class HookCallback(Callback): "`Callback` that can be used to register hooks on `modules`" _methods = ["hook"] hook = noops def __init__(self, modules=None, every=None, remove_end=True, is_forward=True, detach=True, cpu=True, **kwargs): store_attr(self, 'modules,every,remove_end,is_forward,detach,cpu') assert not kwargs def begin_fit(self): "Register the `Hooks` on `self.modules`." if self.modules is None: self.modules = [m for m in flatten_model(self.model) if has_params(m)] if self.every is None: self._register() def begin_batch(self): if self.every is None: return if self.training and self.train_iter%self.every==0: self._register() def after_batch(self): if self.every is None: return if self.training and self.train_iter%self.every==0: self._remove() def after_fit(self): "Remove the `Hooks`." if self.remove_end: self._remove() def _register(self): self.hooks = Hooks(self.modules, self.hook, self.is_forward, self.detach, self.cpu) def _remove(self): if getattr(self, 'hooks', None): self.hooks.remove() def __del__(self): self._remove() #Cell def total_params(m): "Give the number of parameters of a module and if it's trainable or not" params = sum([p.numel() for p in m.parameters()]) trains = [p.requires_grad for p in m.parameters()] return params, (False if len(trains)==0 else trains[0]) #Cell def layer_info(learn): def _track(m, i, o): return (m.__class__.__name__,)+total_params(m)+(apply(lambda x:x.shape, o),) layers = [m for m in flatten_model(learn.model)] xb,_ = learn.dbunch.train_dl.one_batch() with Hooks(layers, _track) as h: _ = learn.model.eval()(apply(lambda o:o[:1], xb)) return xb,h.stored #Cell def _print_shapes(o, bs): if isinstance(o, torch.Size): return ' x '.join([str(bs)] + [str(t) for t in o[1:]]) else: return [_print_shapes(x, bs) for x in o] #Cell @patch def summary(self:Learner): "Print a summary of the model, optimizer and loss function." xb,infos = layer_info(self) n,bs = 64,find_bs(xb) inp_sz = _print_shapes(apply(lambda x:x.shape, xb), bs) res = f"{self.model.__class__.__name__} (Input shape: {inp_sz})\n" res += "=" * n + "\n" res += f"{'Layer (type)':<20} {'Output Shape':<20} {'Param #':<10} {'Trainable':<10}\n" res += "=" * n + "\n" ps,trn_ps = 0,0 infos = [o for o in infos if o is not None] #see comment in previous cell for typ,np,trn,sz in infos: if sz is None: continue ps += np if trn: trn_ps += np res += f"{typ:<20} {_print_shapes(sz, bs):<20} {np:<10,} {str(trn):<10}\n" res += "_" * n + "\n" res += f"\nTotal params: {ps:,}\n" res += f"Total trainable params: {trn_ps:,}\n" res += f"Total non-trainable params: {ps - trn_ps:,}\n\n" res += f"Optimizer used: {self.opt_func}\nLoss function: {self.loss_func}\n\n" if self.opt is not None: res += f"Model " + ("unfrozen\n\n" if self.opt.frozen_idx==0 else f"frozen up to parameter group number {self.opt.frozen_idx}\n\n") res += "Callbacks:\n" + '\n'.join(f" - {cb}" for cb in sort_by_run(self.cbs)) return PrettyString(res) #Cell @delegates() class ActivationStats(HookCallback): "Callback that record the mean and std of activations." run_before=TrainEvalCallback def __init__(self, with_hist=False, **kwargs): super().__init__(**kwargs) self.with_hist = with_hist def begin_fit(self): "Initialize stats." super().begin_fit() self.stats = L() def hook(self, m, i, o): o = o.float() res = {'mean': o.mean().item(), 'std': o.std().item(), 'percent_null': (o<=0.05).long().sum().item()/o.numel()} if self.with_hist: res['hist'] = o.histc(40,0,10) return res def after_batch(self): "Take the stored results and puts it in `self.stats`" if self.training and (self.every is None or self.train_iter%self.every != 0): self.stats.append(self.hooks.stored) super().after_batch()
import fasttext import os import pandas as pd from dateutil import parser from typing import Union from bso.server.main.apc.apc_detect import detect_apc from bso.server.main.config import MOUNTED_VOLUME from bso.server.main.affiliation_matcher import get_matcher_parallel from bso.server.main.field_detect import detect_fields from bso.server.main.logger import get_logger from bso.server.main.predatory.predatory_detect import detect_predatory from bso.server.main.publisher.publisher_detect import detect_publisher from bso.server.main.strings import dedup_sort, normalize, remove_punction, get_words from bso.server.main.unpaywall_mongo import get_doi_full from bso.server.main.utils import download_file, FRENCH_ALPHA2 from bso.server.main.utils_upw import chunks, format_upw_millesime from bso.server.main.entity_fishing import get_entity_fishing logger = get_logger(__name__) models = {} project_id = os.getenv('OS_TENANT_ID') def init_model_lang() -> None: logger.debug('Init model lang') os.makedirs(MOUNTED_VOLUME, exist_ok=True) lid_model_name = f'{MOUNTED_VOLUME}lid.176.bin' if not os.path.exists(lid_model_name): download_file(f'https://storage.gra.cloud.ovh.net/v1/AUTH_{project_id}/models/lid.176.bin', upload_to_object_storage=False, destination=lid_model_name) lid_model = fasttext.load_model(lid_model_name) models['lid'] = lid_model def identify_language(text: str) -> Union[str, None]: if 'lid' not in models: init_model_lang() if text is None or len(text) < 3: return None text = remove_punction(text.replace('\n', ' ').replace('\xa0', ' ')).strip() return (models['lid'].predict(text, 1)[0][0]).replace('__label__', '') def normalize_genre(genre, publisher) -> str: if publisher in ['Cold Spring Harbor Laboratory', 'Research Square']: return 'preprint' if genre in ['journal-article', 'book-chapter']: return genre if 'proceedings' in genre: return 'proceedings' if genre in ['book', 'monograph']: return 'book' return 'other' def get_affiliation_types(affiliation: str) -> dict: normalized_affiliation = normalize(affiliation) is_university = False if 'centre hospitalier univ' in normalized_affiliation: is_university = False else: for word in ['universite', 'université', 'university', 'univ']: if word in normalized_affiliation: is_university = True is_hospital = False for word in ['hospit', 'hopit', 'ch ', 'chu', 'chru', 'aphp', 'aphm']: if word in normalized_affiliation: is_hospital = True is_inserm = False for word in ['inserm', 'institut national de la sante']: if word in normalized_affiliation: is_inserm = True is_cnrs = False for word in ['cnrs', 'umr']: if word in normalized_affiliation: is_cnrs = True return { 'is_cnrs': is_cnrs, 'is_hospital': is_hospital, 'is_inserm': is_inserm, 'is_university': is_university } def compute_affiliations_types(affiliations: list) -> list: result = [] for affiliation in affiliations: res = get_affiliation_types(affiliation) if res.get('is_university'): result.append('university') if res.get('is_hospital'): result.append('hospital') if res.get('is_inserm'): result.append('inserm') if res.get('is_cnrs'): result.append('cnrs') result = dedup_sort(result) return result def has_fr(countries: list) -> bool: if not countries or not isinstance(countries, list): return False for country in countries: if country.lower() in FRENCH_ALPHA2: return True return False def format_upw(dois_infos: dict, extra_data: dict, entity_fishing: bool) -> list: final = [] for doi in dois_infos: if 'global' not in dois_infos[doi]: continue #res = {'doi': doi} else: res = dois_infos[doi]['global'] if doi in extra_data: res.update(extra_data[doi]) if 'z_authors' in res and isinstance(res['z_authors'], list): for a in res['z_authors']: full_name = '' last_name = a.get('family') first_name = a.get('given') if isinstance(first_name, str): full_name = f'{first_name} ' if isinstance(last_name, str): full_name += last_name full_name = full_name.strip() if full_name: a['full_name'] = full_name # todo implement a merge if 'authors' is in res if (not isinstance(res.get('authors'), list)) and isinstance(res['z_authors'], list): res['authors'] = res['z_authors'] del res['z_authors'] # Fields detection #logger.debug('fields1') classification_types = ['bso'] domains = res.get('domains', []) if not isinstance(domains, list): domains = [] if 'health' in domains: classification_types.append('bsso') res = detect_fields(res, classification_types) #logger.debug('fieldsEND') # APC published_date_for_apc = res.get('published_date') if not isinstance(published_date_for_apc, str): published_date_for_apc = '2100-01-01' logger.debug(f"missing published date ({res.get("published_date")}) for doi {doi}, using a fallback in future for apc") info_apc = detect_apc(doi, res.get('journal_issns'), res.get('publisher'), published_date_for_apc, dois_infos[doi]) res.update(info_apc) #logger.debug('APC_END') # Language lang_mapping = { 'english': 'en', 'french': 'fr', 'spanish': 'es', 'german': 'de', 'dutch': 'nl', 'italian': 'it' } if isinstance(res.get('lang'), str) and res.get('lang').lower() in lang_mapping: res['lang'] = lang_mapping[res['lang'].lower()] elif (not(isinstance(res.get('lang'), str))) or (len(res['lang']) != 2) or (res['lang'] != res['lang'].lower()): publi_title_abstract = '' words_title = get_words(res.get('title')) if isinstance(words_title, str): publi_title_abstract += words_title + ' ' words_abstract = get_words(res.get('abstract')) if isinstance(words_abstract, str): publi_title_abstract += words_abstract publi_title_abstract = publi_title_abstract.strip() if len(publi_title_abstract) > 5: res['lang'] = identify_language(publi_title_abstract.strip()) else: logger.debug(f'not enough info title / abstract for doi {doi} : {publi_title_abstract}') # Entity fishing if entity_fishing: ef_info = get_entity_fishing(res) if ef_info: res.update(ef_info) # Predatory info pred_info = detect_predatory(res.get('publisher'), res.get('journal_name')) res.update(pred_info) #logger.debug('PREDA_END') # Language # normalisation des editeurs published_year = None if isinstance(res.get('published_date'), str): published_year = res.get('published_date')[0:4] publisher_raw = res.get('publisher') if not publisher_raw: publisher_raw = 'unknown' publisher_clean = detect_publisher(publisher_raw, published_year, doi) res.update(publisher_clean) #logger.debug('PUBLISHER_END') #if res.get('publisher_normalized') in ['Cold Spring Harbor Laboratory']: # res['domains'] = ['health'] # Genre if isinstance(res.get('genre'), str): res['genre_raw'] = res['genre'] res['genre'] = normalize_genre(res['genre'], res.get('publisher_normalized')) # Affiliations affiliations = res.get('affiliations', []) affiliations = [] if affiliations is None else affiliations fr_affil = [a.get('name', '') for a in affiliations if has_fr(a.get('detected_countries'))] fr_affil_types = compute_affiliations_types(fr_affil) res['french_affiliations_types'] = fr_affil_types # Authors useful rank author_useful_rank_countries = [] authors = res.get('authors', []) if not isinstance(authors, list): authors = [] nb_authors = len(authors) for index, author in enumerate(authors): affiliations = author.get('affiliations', []) if not isinstance(affiliations, list): affiliations = [] for affiliation in affiliations: if index == 0 or index == nb_authors - 1: author_useful_rank_countries += affiliation.get('detected_countries', []) author_useful_rank_countries = list(set(author_useful_rank_countries)) author_useful_rank_fr = has_fr(author_useful_rank_countries) res['author_useful_rank_fr'] = author_useful_rank_fr res['author_useful_rank_countries'] = author_useful_rank_countries # OA Details res['observation_dates'] = [] res['oa_details'] = {} last_millesime = None for asof in dois_infos[doi]: if asof == 'global': continue else: tmp = format_upw_millesime(dois_infos[doi][asof], asof, res['has_apc']) res['oa_details'].update(tmp) res['observation_dates'].append(list(tmp.keys())[0]) # getting the key that is the observation date if last_millesime: last_millesime = max(last_millesime, asof) else: last_millesime = asof #logger.debug('MILLESIME_END') # get hal_id if present in one of the last oa locations if last_millesime: last_oa_loc = dois_infos[doi][last_millesime].get('oa_locations', []) if isinstance(last_oa_loc, list): for loc in last_oa_loc: if loc.get('repository_normalized') == 'HAL' or 'archives-ouvertes.fr' in loc.get('url'): hal_id = None if isinstance(loc.get('pmh_id'), str): hal_id = loc['pmh_id'].split(':')[2].strip().lower() if hal_id[-2] == 'v': # remove version hal_id = hal_id[:-2] if hal_id is None and isinstance(loc.get('url_for_pdf'), str) and '/document' in loc['url_for_pdf'].lower(): try: url_split = loc['url_for_pdf'].lower().split('/')[-2] if '-' in url_split: hal_id = url_split except: pass if hal_id: external_ids = [] external_ids.append({'id_type': 'hal_id', 'id_value': hal_id}) res['external_ids'] = external_ids res['hal_id'] = hal_id #logger.debug('HAL_END') for field in ['amount_apc_doaj', 'amount_apc_doaj_EUR', 'amount_apc_EUR', 'is_paratext', 'issn_print', 'has_coi', 'has_grant', 'pmid', 'publication_year', 'year']: if pd.isna(res.get(field)): res[field] = None for field in ['has_coi', 'has_grant', 'is_paratext']: if res.get(field, 0.0) == 0.0: res[field] = False # not exposing some fields in index # for f in ['authors', 'references', 'abstract', 'incipit']: # if f in res: # del res[f] #if 'affiliations' in res and isinstance(res['affiliations'], list): # for aff in res['affiliations']: # if 'name' in aff: # del aff['name'] final.append(res) logger.debug(f'format_upw DONE') return final def enrich(publications: list, observations: list, datasource: str, affiliation_matching: bool, last_observation_date_only:bool, entity_fishing: bool) -> list: publis_dict = {} # affiliation matcher publicationsWithAffiliations = [] if affiliation_matching: NB_PARALLEL_JOBS = 20 PUBLI_GROUP_SIZE = 100 logger.debug(f'affiliation matching for {len(publications)} publications') publis_chunks = list(chunks(lst=publications, n=PUBLI_GROUP_SIZE)) groups = list(chunks(lst=publis_chunks, n=NB_PARALLEL_JOBS)) for chunk in groups: publicationsWithAffiliations += get_matcher_parallel(chunk) publications = publicationsWithAffiliations for p in publications: if datasource: p['datasource'] = datasource if 'doi' in p and isinstance(p['doi'], str): doi = p['doi'].lower() publis_dict[doi] = p all_updated = [] logger.debug(f'Enriching {len(publications)} publications') for publi_chunk in chunks(lst=publications, n=20000): doi_chunk = [p.get('doi') for p in publi_chunk if p and isinstance(p.get('doi'), str) and '10' in p['doi']] data = get_doi_full(dois=doi_chunk, observations=observations, last_observation_date_only=last_observation_date_only) # Remove data with no oa details info (not indexed in unpaywall) new_updated = format_upw(dois_infos=data, extra_data=publis_dict, entity_fishing=entity_fishing) for d in new_updated: if len(d.get('oa_details', {})) == 0: continue # some post-filtering if d.get('publisher_group') in ['United Nations', 'World Trade Organization']: continue if d.get('genre') == 'other': continue all_updated.append(d) logger.debug(f'{len(publi_chunk)} / {len(publications)} enriched') for p in all_updated: field_to_del = [] for field in p: if isinstance(p.get(field), str) and field.endswith('_date'): try: p[field] = parser.parse(p[field]).isoformat() except: logger.debug(f"error for field {field} : {p[field]} of type {type(p[field])}, deleting field") field_to_del.append(field) for field in field_to_del: del p[field] return all_updated
import fasttext import os import pandas as pd from dateutil import parser from typing import Union from bso.server.main.apc.apc_detect import detect_apc from bso.server.main.config import MOUNTED_VOLUME from bso.server.main.affiliation_matcher import get_matcher_parallel from bso.server.main.field_detect import detect_fields from bso.server.main.logger import get_logger from bso.server.main.predatory.predatory_detect import detect_predatory from bso.server.main.publisher.publisher_detect import detect_publisher from bso.server.main.strings import dedup_sort, normalize, remove_punction, get_words from bso.server.main.unpaywall_mongo import get_doi_full from bso.server.main.utils import download_file, FRENCH_ALPHA2 from bso.server.main.utils_upw import chunks, format_upw_millesime from bso.server.main.entity_fishing import get_entity_fishing logger = get_logger(__name__) models = {} project_id = os.getenv('OS_TENANT_ID') def init_model_lang() -> None: logger.debug('Init model lang') os.makedirs(MOUNTED_VOLUME, exist_ok=True) lid_model_name = f'{MOUNTED_VOLUME}lid.176.bin' if not os.path.exists(lid_model_name): download_file(f'https://storage.gra.cloud.ovh.net/v1/AUTH_{project_id}/models/lid.176.bin', upload_to_object_storage=False, destination=lid_model_name) lid_model = fasttext.load_model(lid_model_name) models['lid'] = lid_model def identify_language(text: str) -> Union[str, None]: if 'lid' not in models: init_model_lang() if text is None or len(text) < 3: return None text = remove_punction(text.replace('\n', ' ').replace('\xa0', ' ')).strip() return (models['lid'].predict(text, 1)[0][0]).replace('__label__', '') def normalize_genre(genre, publisher) -> str: if publisher in ['Cold Spring Harbor Laboratory', 'Research Square']: return 'preprint' if genre in ['journal-article', 'book-chapter']: return genre if 'proceedings' in genre: return 'proceedings' if genre in ['book', 'monograph']: return 'book' return 'other' def get_affiliation_types(affiliation: str) -> dict: normalized_affiliation = normalize(affiliation) is_university = False if 'centre hospitalier univ' in normalized_affiliation: is_university = False else: for word in ['universite', 'université', 'university', 'univ']: if word in normalized_affiliation: is_university = True is_hospital = False for word in ['hospit', 'hopit', 'ch ', 'chu', 'chru', 'aphp', 'aphm']: if word in normalized_affiliation: is_hospital = True is_inserm = False for word in ['inserm', 'institut national de la sante']: if word in normalized_affiliation: is_inserm = True is_cnrs = False for word in ['cnrs', 'umr']: if word in normalized_affiliation: is_cnrs = True return { 'is_cnrs': is_cnrs, 'is_hospital': is_hospital, 'is_inserm': is_inserm, 'is_university': is_university } def compute_affiliations_types(affiliations: list) -> list: result = [] for affiliation in affiliations: res = get_affiliation_types(affiliation) if res.get('is_university'): result.append('university') if res.get('is_hospital'): result.append('hospital') if res.get('is_inserm'): result.append('inserm') if res.get('is_cnrs'): result.append('cnrs') result = dedup_sort(result) return result def has_fr(countries: list) -> bool: if not countries or not isinstance(countries, list): return False for country in countries: if country.lower() in FRENCH_ALPHA2: return True return False def format_upw(dois_infos: dict, extra_data: dict, entity_fishing: bool) -> list: final = [] for doi in dois_infos: if 'global' not in dois_infos[doi]: continue #res = {'doi': doi} else: res = dois_infos[doi]['global'] if doi in extra_data: res.update(extra_data[doi]) if 'z_authors' in res and isinstance(res['z_authors'], list): for a in res['z_authors']: full_name = '' last_name = a.get('family') first_name = a.get('given') if isinstance(first_name, str): full_name = f'{first_name} ' if isinstance(last_name, str): full_name += last_name full_name = full_name.strip() if full_name: a['full_name'] = full_name # todo implement a merge if 'authors' is in res if (not isinstance(res.get('authors'), list)) and isinstance(res['z_authors'], list): res['authors'] = res['z_authors'] del res['z_authors'] # Fields detection #logger.debug('fields1') classification_types = ['bso'] domains = res.get('domains', []) if not isinstance(domains, list): domains = [] if 'health' in domains: classification_types.append('bsso') res = detect_fields(res, classification_types) #logger.debug('fieldsEND') # APC published_date_for_apc = res.get('published_date') if not isinstance(published_date_for_apc, str): published_date_for_apc = '2100-01-01' logger.debug(f"missing published date ({res.get('published_date')}) for doi {doi}, using a fallback in future for apc") info_apc = detect_apc(doi, res.get('journal_issns'), res.get('publisher'), published_date_for_apc, dois_infos[doi]) res.update(info_apc) #logger.debug('APC_END') # Language lang_mapping = { 'english': 'en', 'french': 'fr', 'spanish': 'es', 'german': 'de', 'dutch': 'nl', 'italian': 'it' } if isinstance(res.get('lang'), str) and res.get('lang').lower() in lang_mapping: res['lang'] = lang_mapping[res['lang'].lower()] elif (not(isinstance(res.get('lang'), str))) or (len(res['lang']) != 2) or (res['lang'] != res['lang'].lower()): publi_title_abstract = '' words_title = get_words(res.get('title')) if isinstance(words_title, str): publi_title_abstract += words_title + ' ' words_abstract = get_words(res.get('abstract')) if isinstance(words_abstract, str): publi_title_abstract += words_abstract publi_title_abstract = publi_title_abstract.strip() if len(publi_title_abstract) > 5: res['lang'] = identify_language(publi_title_abstract.strip()) else: logger.debug(f'not enough info title / abstract for doi {doi} : {publi_title_abstract}') # Entity fishing if entity_fishing: ef_info = get_entity_fishing(res) if ef_info: res.update(ef_info) # Predatory info pred_info = detect_predatory(res.get('publisher'), res.get('journal_name')) res.update(pred_info) #logger.debug('PREDA_END') # Language # normalisation des editeurs published_year = None if isinstance(res.get('published_date'), str): published_year = res.get('published_date')[0:4] publisher_raw = res.get('publisher') if not publisher_raw: publisher_raw = 'unknown' publisher_clean = detect_publisher(publisher_raw, published_year, doi) res.update(publisher_clean) #logger.debug('PUBLISHER_END') #if res.get('publisher_normalized') in ['Cold Spring Harbor Laboratory']: # res['domains'] = ['health'] # Genre if isinstance(res.get('genre'), str): res['genre_raw'] = res['genre'] res['genre'] = normalize_genre(res['genre'], res.get('publisher_normalized')) # Affiliations affiliations = res.get('affiliations', []) affiliations = [] if affiliations is None else affiliations fr_affil = [a.get('name', '') for a in affiliations if has_fr(a.get('detected_countries'))] fr_affil_types = compute_affiliations_types(fr_affil) res['french_affiliations_types'] = fr_affil_types # Authors useful rank author_useful_rank_countries = [] authors = res.get('authors', []) if not isinstance(authors, list): authors = [] nb_authors = len(authors) for index, author in enumerate(authors): affiliations = author.get('affiliations', []) if not isinstance(affiliations, list): affiliations = [] for affiliation in affiliations: if index == 0 or index == nb_authors - 1: author_useful_rank_countries += affiliation.get('detected_countries', []) author_useful_rank_countries = list(set(author_useful_rank_countries)) author_useful_rank_fr = has_fr(author_useful_rank_countries) res['author_useful_rank_fr'] = author_useful_rank_fr res['author_useful_rank_countries'] = author_useful_rank_countries # OA Details res['observation_dates'] = [] res['oa_details'] = {} last_millesime = None for asof in dois_infos[doi]: if asof == 'global': continue else: tmp = format_upw_millesime(dois_infos[doi][asof], asof, res['has_apc']) res['oa_details'].update(tmp) res['observation_dates'].append(list(tmp.keys())[0]) # getting the key that is the observation date if last_millesime: last_millesime = max(last_millesime, asof) else: last_millesime = asof #logger.debug('MILLESIME_END') # get hal_id if present in one of the last oa locations if last_millesime: last_oa_loc = dois_infos[doi][last_millesime].get('oa_locations', []) if isinstance(last_oa_loc, list): for loc in last_oa_loc: if loc.get('repository_normalized') == 'HAL' or 'archives-ouvertes.fr' in loc.get('url'): hal_id = None if isinstance(loc.get('pmh_id'), str): hal_id = loc['pmh_id'].split(':')[2].strip().lower() if hal_id[-2] == 'v': # remove version hal_id = hal_id[:-2] if hal_id is None and isinstance(loc.get('url_for_pdf'), str) and '/document' in loc['url_for_pdf'].lower(): try: url_split = loc['url_for_pdf'].lower().split('/')[-2] if '-' in url_split: hal_id = url_split except: pass if hal_id: external_ids = [] external_ids.append({'id_type': 'hal_id', 'id_value': hal_id}) res['external_ids'] = external_ids res['hal_id'] = hal_id #logger.debug('HAL_END') for field in ['amount_apc_doaj', 'amount_apc_doaj_EUR', 'amount_apc_EUR', 'is_paratext', 'issn_print', 'has_coi', 'has_grant', 'pmid', 'publication_year', 'year']: if pd.isna(res.get(field)): res[field] = None for field in ['has_coi', 'has_grant', 'is_paratext']: if res.get(field, 0.0) == 0.0: res[field] = False # not exposing some fields in index # for f in ['authors', 'references', 'abstract', 'incipit']: # if f in res: # del res[f] #if 'affiliations' in res and isinstance(res['affiliations'], list): # for aff in res['affiliations']: # if 'name' in aff: # del aff['name'] final.append(res) logger.debug(f'format_upw DONE') return final def enrich(publications: list, observations: list, datasource: str, affiliation_matching: bool, last_observation_date_only:bool, entity_fishing: bool) -> list: publis_dict = {} # affiliation matcher publicationsWithAffiliations = [] if affiliation_matching: NB_PARALLEL_JOBS = 20 PUBLI_GROUP_SIZE = 100 logger.debug(f'affiliation matching for {len(publications)} publications') publis_chunks = list(chunks(lst=publications, n=PUBLI_GROUP_SIZE)) groups = list(chunks(lst=publis_chunks, n=NB_PARALLEL_JOBS)) for chunk in groups: publicationsWithAffiliations += get_matcher_parallel(chunk) publications = publicationsWithAffiliations for p in publications: if datasource: p['datasource'] = datasource if 'doi' in p and isinstance(p['doi'], str): doi = p['doi'].lower() publis_dict[doi] = p all_updated = [] logger.debug(f'Enriching {len(publications)} publications') for publi_chunk in chunks(lst=publications, n=20000): doi_chunk = [p.get('doi') for p in publi_chunk if p and isinstance(p.get('doi'), str) and '10' in p['doi']] data = get_doi_full(dois=doi_chunk, observations=observations, last_observation_date_only=last_observation_date_only) # Remove data with no oa details info (not indexed in unpaywall) new_updated = format_upw(dois_infos=data, extra_data=publis_dict, entity_fishing=entity_fishing) for d in new_updated: if len(d.get('oa_details', {})) == 0: continue # some post-filtering if d.get('publisher_group') in ['United Nations', 'World Trade Organization']: continue if d.get('genre') == 'other': continue all_updated.append(d) logger.debug(f'{len(publi_chunk)} / {len(publications)} enriched') for p in all_updated: field_to_del = [] for field in p: if isinstance(p.get(field), str) and field.endswith('_date'): try: p[field] = parser.parse(p[field]).isoformat() except: logger.debug(f"error for field {field} : {p[field]} of type {type(p[field])}, deleting field") field_to_del.append(field) for field in field_to_del: del p[field] return all_updated
import sys import stellargraph as sg import matplotlib.pyplot as plt from math import isclose import sklearn from sklearn.decomposition import PCA import os import networkx as nx import numpy as np import pandas as pd from stellargraph import StellarGraph, datasets from stellargraph.data import EdgeSplitter from collections import Counter import multiprocessing from IPython.display import display, HTML from sklearn.model_selection import train_test_split from src.main import * from sklearn.pipeline import Pipeline from sklearn.linear_model import LogisticRegressionCV from sklearn.metrics import roc_auc_score from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LogisticRegression from sklearn import model_selection from sklearn.multiclass import OneVsRestClassifier from sklearn import preprocessing from sklearn.model_selection import GridSearchCV from sklearn.metrics import accuracy_score import dill # is_dill = True # if is_dill: # dill.load_session('./cora/beforeRB.pkl') p = 1.0 q = 1.0 dimensions = 128 num_walks = 10 walk_length = 80 window_size = 10 num_iter = 1 import argparse parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('--reg1', type=float, help='sym reg') parser.add_argument('--reg2', type=float, help='sym reg') args = parser.parse_args() reg1 = args.reg1 reg2 = args.reg2 workers = multiprocessing.cpu_count() from stellargraph.data import BiasedRandomWalk from gensim.models import Word2Vec dill.load_session(f'./cora/node_adj_{reg1}_{reg2}.pkl') drop_weight = 0.45 emd_weight = 0.19 def RB(get_embedding, feat, name, kfold=5): embeddings = [] s = [] for i in range(len(feat.values())): embeddings.append(get_embedding(i)) s.append(str(feat[i])) X = embeddings y = s X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.3, random_state=1121218 ) from sklearn.svm import SVC clf = OneVsRestClassifier(SVC(probability=True)) # clf = LogisticRegression(solver='lbfgs') clf.fit(X_train, y_train) y_pred_probs = clf.predict_proba(X_test) # Calculate ROC_AUC results_lap = roc_auc_score( y_test, y_pred_probs, multi_class="ovr", average="weighted" ) predict_lables = clf.predict(X_test) print(f"RB on the {name} graph is: {results_lap.mean()}") acc = accuracy_score(y_test, predict_lables) return results_lap, acc def ERB(get_embedding, feat, name, kfold=5): embeddings = [] s = [] for i in range(len(feat.values())): embeddings.append(get_embedding(i)) s.append(str(feat[i])) X = embeddings y = s X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=1121218 ) from sklearn.svm import SVC clf = OneVsRestClassifier(SVC(probability=True)) # clf = LogisticRegression(solver='lbfgs') clf.fit(X_train, y_train) y_pred_probs = clf.predict_proba(X_test) # Calculate ROC_AUC results_lap = roc_auc_score( y_test, y_pred_probs, multi_class="ovr", average="weighted" ) y_predict = clf.predict(X_test) acc = accuracy_score(y_test, y_predict) print(f"RB on the {name} graph is: {results_lap.mean()}") return results_lap, acc def vis_pca(name, best_result, examples_test, embedding_test): link_features = link_examples_to_features( examples_test, embedding_test, best_result["binary_operator"] ) # Learn a projection from 128 dimensions to 2 pca = PCA(n_components=2) X_transformed = pca.fit_transform(link_features) # plot the 2-dimensional points plt.figure(figsize=(16, 12)) plt.scatter( X_transformed[:, 0], X_transformed[:, 1], c=np.where(labels_test == 1, "b", "r"), alpha=0.5, ) plt.tight_layout() plt.savefig(f'figs/dblp/{name}-pca.jpg') def vis_nx(name, g): # Visualisation of the generated graph #Retrieve indexes of node in each group s = nx.get_node_attributes(g, 's') idx_ps = [] labels = list(set(s.values())) for val in labels: idx_ps.append(get_keys_from_value(s, val)) # Draw the graph pos = nx.spring_layout(g) i = 0 colors = ['steelblue', 'gold', 'green', 'red', 'orange'] for idx_p in idx_ps: nx.draw_networkx_nodes(g, pos=pos, node_size=0.1, nodelist=idx_p, node_color=colors[i], label=f'S = {labels[i]}') nx.draw_networkx_edges(g, pos=pos) plt.legend(loc="upper left", scatterpoints=1, prop={'size': 15}) plt.tight_layout() plt.savefig(f'figs/dblp/{name}-nx.jpg') def node2vec_embedding(graph, name): rw = BiasedRandomWalk(graph) walks = rw.run(graph.nodes(), n=num_walks, length=walk_length, p=p, q=q) print(f"Number of random walks for '{name}': {len(walks)}") model = Word2Vec( walks, vector_size=dimensions, window=window_size, min_count=0, sg=1, workers=workers, # iter=num_iter, ) def get_embedding(u): return model.wv[u] return get_embedding # 1. link embeddings def link_examples_to_features(link_examples, transform_node, binary_operator): return [ binary_operator(transform_node(src), transform_node(dst)) for src, dst in link_examples ] # 2. training classifier def train_link_prediction_model( link_examples, link_labels, get_embedding, binary_operator, num_iter ): clf = link_prediction_classifier(max_iter=num_iter) link_features = link_examples_to_features( link_examples, get_embedding, binary_operator ) clf.fit(link_features, link_labels) return clf def link_prediction_classifier(max_iter=3000): lr_clf = LogisticRegressionCV(Cs=10, cv=10, scoring="roc_auc", max_iter=max_iter) return Pipeline(steps=[("sc", StandardScaler()), ("clf", lr_clf)]) # 3. and 4. evaluate classifier def evaluate_link_prediction_model( clf, link_examples_test, link_labels_test, get_embedding, binary_operator ): link_features_test = link_examples_to_features( link_examples_test, get_embedding, binary_operator ) score, acc = evaluate_roc_auc(clf, link_features_test, link_labels_test) return score, acc def evaluate_roc_auc(clf, link_features, link_labels): predicted = clf.predict_proba(link_features) # check which class corresponds to positive links positive_column = list(clf.classes_).index(1) predicted_labels = clf.predict(link_features) return roc_auc_score(link_labels, predicted[:, positive_column]), accuracy_score(link_labels, predicted_labels) def operator_hadamard(u, v): return u * v def operator_l1(u, v): return np.abs(u - v) def operator_l2(u, v): return (u - v) ** 2 def operator_avg(u, v): return (u + v) / 2.0 def run_link_prediction(embedding_train, binary_operator, examples_train, labels_train, examples_model_selection, labels_model_selection, num_iter): clf = train_link_prediction_model( examples_train, labels_train, embedding_train, binary_operator, num_iter=num_iter ) score, acc = evaluate_link_prediction_model( clf, examples_model_selection, labels_model_selection, embedding_train, binary_operator, ) return { "classifier": clf, "binary_operator": binary_operator, "score": score, 'acc': acc } def AUC_print(results): print(pd.DataFrame( [(result["binary_operator"].__name__, result["score"]) for result in results], columns=("name", "ROC AUC score"), ).set_index("name")) def DI(best_result, examples_test, g, embedding_test): link_features_test = link_examples_to_features( examples_test, embedding_test, best_result["binary_operator"] ) xor0, xor1 = [], [] feat = nx.get_node_attributes(g, 's') for i in range(len(examples_test)): if feat[examples_test[i][0]] == feat[examples_test[i][1]]: xor0.append(link_features_test[i]) else: xor1.append(link_features_test[i]) y0 = best_result["classifier"].predict(xor0) score0 = sklearn.metrics.accuracy_score(y0, np.ones_like(y0)) y1 = best_result["classifier"].predict(xor1) score1 = sklearn.metrics.accuracy_score(y1, np.ones_like(y1)) return score1/score0 binary_operators = [operator_hadamard, operator_l1, operator_l2, operator_avg] def parse_cora(plot=False): path = "./data/cora/" id2index = {} label2index = { 'Case_Based': 0, 'Genetic_Algorithms': 1, 'Neural_Networks': 2, 'Probabilistic_Methods': 3, 'Reinforcement_Learning': 4, 'Rule_Learning': 5, 'Theory': 6 } features = [] labels = [] with open(path + 'cora.content', 'r') as f: i = 0 for line in f.readlines(): items = line.strip().split('\t') id = items[0] # 1-hot encode labels label = np.zeros(len(label2index)) label[label2index[items[-1]]] = 1 labels.append(items[-1]) # parse features features.append([int(x) for x in items[1:-1]]) id2index[id] = i i += 1 features = np.asarray(features, dtype='float32') labels = np.array(labels) # labels = np.asarray(labels, dtype='int32') n_papers = len(id2index) adj = np.zeros((n_papers, n_papers), dtype='float32') with open(path + 'cora.cites', 'r') as f: for line in f.readlines(): items = line.strip().split('\t') adj[ id2index[items[0]], id2index[items[1]] ] = 1.0 # undirected adj[ id2index[items[1]], id2index[items[0]] ] = 1.0 G = nx.from_numpy_matrix(adj, nx.Graph()) feat_dict, label_dict = {}, {} for i in range(features.shape[0]): feat_dict[i] = features[i] label_dict[i] = labels[i] nx.set_node_attributes(G, feat_dict, name='feat') nx.set_node_attributes(G, label_dict, name='s') return G def load_data(): G = parse_cora() # G = nx.relabel.convert_node_labels_to_integers(G, first_label=0, ordering='default') return G def emd_repair(graph_train, num_iter=1e6, edge_weight=0.2): emd_adj, s_emd, gamma, M = multi_total_repair(graph_train, num_iter=num_iter, metric='euclidean', log=False) print('emd edges', np.sum(np.array(emd_adj) >= edge_weight)) emd_g = nx.from_numpy_matrix(emd_adj) # Filter out the smallest weights to keep a reasonable density list_edge = [(u, v) for (u, v, d) in emd_g.edges(data=True) if d['weight'] < edge_weight] emd_g.remove_edges_from(list_edge) nx.set_node_attributes(emd_g, nx.get_node_attributes(graph_train, 's'), name='s') print('Assortativity coeffcient on the emd graph: %0.3f' % nx.attribute_assortativity_coefficient(emd_g, 's')) return emd_g def drop_repair(graph_train, edge_weight=0.2): sens = nx.get_node_attributes(graph_train, 's') sens_ls = [] for i in range(len(sens)): sens_ls.append(sens[i]) sens_ls = np.array(sens_ls) mij = np.random.rand(len(sens_ls)*len(sens_ls)).reshape(len(sens_ls), len(sens_ls)) for i in range(0, len(sens_ls)): # import pdb; pdb.set_trace() mij[i][sens_ls == sens_ls[i]] = 0 mij[i][sens_ls != sens_ls[i]] = 1 myrand = np.random.rand(len(sens_ls)) mij[i][myrand < 0.5 - edge_weight] = 1- mij[i][myrand < 0.5 - edge_weight] drop_adj = nx.adjacency_matrix(graph_train) * mij drop_g = nx.from_numpy_matrix(drop_adj) # Filter out the smallest weights to keep a reasonable density nx.set_node_attributes(drop_g, nx.get_node_attributes(graph_train, 's'), name='s') print('Assortativity coeffcient on the drop graph: %0.3f' % nx.attribute_assortativity_coefficient(drop_g, 's')) return drop_g def sym_repair_adj(graph_train, num_iter=1e6, reg=1e-9): emd_adj, emd_nodes, s_emd, gamma, M = multi_node_sym_total_repair(graph_train, num_iter=num_iter, metric='euclidean', log=False, reg=reg, reg1=reg1, reg2=reg2) return emd_adj, emd_nodes def node_repair_adj(graph_train, num_iter=1e6, reg=1e-9): emd_adj, emd_nodes, s_emd, gamma, M = multi_node_total_repair(graph_train, num_iter=num_iter, metric='euclidean', log=False, reg=reg, reg1=reg1, reg2=reg2) return emd_adj, emd_nodes def node_repair(graph_train, emd_adj, emd_nodes, edge_weight=0.2): print('emd edges', np.sum(np.array(emd_adj) >= edge_weight)) emd_g = nx.from_numpy_matrix(emd_adj) # Filter out the smallest weights to keep a reasonable density list_edge = [(u, v) for (u, v, d) in emd_g.edges(data=True) if d['weight'] < edge_weight] emd_g.remove_edges_from(list_edge) emd_nodes_dict = {} for i in range(emd_nodes.shape[0]): emd_nodes_dict[i] = emd_nodes[i] nx.set_node_attributes(emd_g, emd_nodes_dict, name='feat') # import pdb; pdb.set_trace() nx.set_node_attributes(emd_g, nx.get_node_attributes(graph_train, 's'),name='s') print('Assortativity coeffcient on the node repair graph: %0.3f' % nx.attribute_assortativity_coefficient(emd_g, 's')) return emd_g def sym_repair(graph_train, emd_adj, emd_nodes, edge_weight=0.2): print('emd edges', np.sum(np.array(emd_adj) >= edge_weight)) emd_g = nx.from_numpy_matrix(emd_adj) # Filter out the smallest weights to keep a reasonable density list_edge = [(u, v) for (u, v, d) in emd_g.edges(data=True) if d['weight'] < edge_weight] emd_g.remove_edges_from(list_edge) emd_nodes_dict = {} for i in range(emd_nodes.shape[0]): emd_nodes_dict[i] = emd_nodes[i] nx.set_node_attributes(emd_g, emd_nodes_dict, name='feat') # import pdb; pdb.set_trace() nx.set_node_attributes(emd_g, nx.get_node_attributes(graph_train, 's'),name='s') print('Assortativity coeffcient on the emd graph: %0.3f' % nx.attribute_assortativity_coefficient(emd_g, 's')) return emd_g def AUC_test(best_result, examples_test,labels_test, embedding_test): test_score = evaluate_link_prediction_model( best_result["classifier"], examples_test, labels_test, embedding_test, best_result["binary_operator"], ) print( f"ROC AUC score on test set using '{best_result["binary_operator"].__name__}': {test_score}" ) def edge_pred(examples_train, examples_model_selection, labels_train, labels_model_selection, embedding_train, num_iter=2000): results = [run_link_prediction(embedding_train, op, examples_train, labels_train, examples_model_selection, labels_model_selection, num_iter = num_iter) for op in binary_operators] best_result = max(results, key=lambda result: result["score"]) AUC_print(results) return best_result def get_xor_label(examples_train, graph_train): feat = nx.get_node_attributes(graph_train, 's') xor_labels = [] for example in examples_train: if feat[example[0]] == feat[example[1]]: xor_labels.append(0) else: xor_labels.append(1) return xor_labels is_dill = True if not is_dill: G = load_data() # nx.set_node_attributes(G, node_feat, 's') print('Assortativity coeffcient on the origin graph: %0.3f' % nx.attribute_assortativity_coefficient(G, 's')) print("Correcting the graph with EMD") edge_splitter_test = EdgeSplitter(G) # Randomly sample a fraction p=0.1 of all positive links, and same number of negative links, from graph, and obtain the # reduced graph graph_test with the sampled links removed: graph_test, examples_test, labels_test = edge_splitter_test.train_test_split( p=0.1, method="global" ) # Do the same process to compute a training subset from within the test graph edge_splitter_train = EdgeSplitter(graph_test, G) graph_train, examples, labels = edge_splitter_train.train_test_split( p=0.1, method="global" ) # REPAIRG drop_g = drop_repair(graph_train, edge_weight=drop_weight) emd_g = emd_repair(graph_train, num_iter=1e6, edge_weight=0.12) # EMBEDDING with node2vec embedding_train = node2vec_embedding(StellarGraph.from_networkx(graph_train, node_features='feat'), "Train Graph") emd_embedding_train = node2vec_embedding(StellarGraph.from_networkx(emd_g, node_features='feat'), "EMD Train Graph") drop_embedding_train = node2vec_embedding(StellarGraph.from_networkx(drop_g), "Drop Train Graph") # TRAIN and VAL ( examples_train, examples_model_selection, labels_train, labels_model_selection, ) = train_test_split(examples, labels, train_size=0.75, test_size=0.25) print('origin') ori_best_result = edge_pred(examples_train, examples_model_selection, labels_train, labels_model_selection, embedding_train) print('drop') drop_best_result = edge_pred(examples_train, examples_model_selection, labels_train, labels_model_selection, drop_embedding_train) print('emd') emd_best_result = edge_pred(examples_train, examples_model_selection, labels_train, labels_model_selection, emd_embedding_train) embedding_test = node2vec_embedding(StellarGraph.from_networkx(graph_test), "Test Graph") print('origin graph') AUC_test(ori_best_result, examples_test,labels_test, embedding_test) print('drop graph') drop_graph_test = drop_repair(graph_test, edge_weight=drop_weight) drop_embedding_test = node2vec_embedding(StellarGraph.from_networkx(drop_graph_test), "Drop Test Graph") AUC_test(drop_best_result, examples_test,labels_test, drop_embedding_test) print('emd graph') emd_graph_test = emd_repair(graph_test, num_iter=1e6, edge_weight=emd_weight) emd_embedding_test = node2vec_embedding(StellarGraph.from_networkx(emd_graph_test), "EMD Test Graph") AUC_test(emd_best_result, examples_test,labels_test, emd_embedding_test) # RB ori_feat = nx.get_node_attributes(graph_train, 's') RB(embedding_train, ori_feat, 'origin', kfold=5) drop_feat = nx.get_node_attributes(drop_g, 's') RB(drop_embedding_train, drop_feat, 'emd', kfold=5) emd_feat = nx.get_node_attributes(emd_g, 's') RB(emd_embedding_train, emd_feat, 'emd', kfold=5) # DI ori_di = DI(ori_best_result, examples_test, graph_test, embedding_test) drop_di = DI(drop_best_result, examples_test, graph_test, drop_embedding_test) emd_di = DI(emd_best_result, examples_test, graph_test, emd_embedding_test) print(f'ori_DI: {ori_di}, drop_DI: {drop_di}, emd_DI: {emd_di}') dill.dump_session('./cora/beforeERB.pkl') # ERB print('Edge RB') xor_train_label, xor_val_label = get_xor_label(examples_train, graph_train), get_xor_label(examples_model_selection, graph_train) print('ori') edge_pred(examples_train, examples_model_selection, xor_train_label, xor_val_label, embedding_train) print('drop') edge_pred(examples_train, examples_model_selection, xor_train_label, xor_val_label, drop_embedding_train) print('emd') edge_pred(examples_train, examples_model_selection, xor_train_label, xor_val_label, emd_embedding_train) # VISUALIZATION # Calculate edge features for test data vis_pca('origin', ori_best_result, examples_test, embedding_test) vis_pca('drop', drop_best_result, examples_test, drop_embedding_test) vis_pca('emd', emd_best_result, examples_test, emd_embedding_test) vis_nx('origin', graph_train) vis_nx('drop', drop_g) vis_nx('emd', emd_g) dill.dump_session('./cora/beforeSym.pkl') exit() # else: # dill.load_session(f'./cora/sym_adj_{reg}.pkl') # reg = 1e-3 # sym_g = sym_repair_adj(graph_train, num_iter=1e4, reg=reg) # sym_testg = sym_repair_adj(graph_test, num_iter=1e4, reg=reg) # results = [run_link_prediction(embedding_train, op, examples_train, labels_train, examples_model_selection, # labels_model_selection,) for op in binary_operators] # best_result = max(results, key=lambda result: result["score"]) # AUC_print(results) # emd_results = [run_link_prediction(emd_embedding_train, op, examples_train, labels_train, examples_model_selection, # labels_model_selection,) for op in binary_operators] # emd_best_result = max(emd_results, key=lambda result: result["score"]) # print('emd repair') # AUC_print(emd_results) # # TEST AUC # embedding_test = node2vec_embedding(StellarGraph.from_networkx(graph_test, node_features='feat'), "Test Graph") # print('origin graph') # AUC_test(best_result, examples_test,labels_test, embedding_test) # print('emd graph') # emd_graph_test = emd_repair(graph_test) # emd_embedding_test = node2vec_embedding(StellarGraph.from_networkx(emd_graph_test, node_features='feat'), "EMD Test Graph") # AUC_test(emd_best_result, examples_test,labels_test, emd_embedding_test) # ori_feat = nx.get_node_attributes(graph_test, 's') # RB(embedding_test, ori_feat, 'origin', kfold=5) # emd_feat = nx.get_node_attributes(emd_graph_test, 's') # RB(emd_embedding_test, emd_feat, 'emd', kfold=5) # # DI # ori_di = DI(best_result, examples_test, graph_test, embedding_test) # emd_di = DI(emd_best_result, examples_test, graph_test, emd_embedding_test) # print(f'ori_DI: {ori_di}, emd_DI: {emd_di}') # # VISUALIZATION # # Calculate edge features for test data # vis_pca('origin', best_result, examples_test, embedding_test) # vis_pca('emd', emd_best_result, examples_test, embedding_test) # vis_nx('origin', graph_train) # vis_nx('emd', emd_g) # dill.dump_session('./cora/beforeRB.pkl') # reg = 1e-3 # sym_g = sym_repair_adj(graph_train, num_iter=1e4, reg=reg) # sym_testg = sym_repair_adj(graph_test, num_iter=1e4, reg=reg) # multi_adj, multi_nodes = node_repair_adj(graph_train, num_iter=1e4, reg=0) # sym_test_adj, sym_test_nodes = node_repair_adj(graph_test, num_iter=1e4, reg=0) # dill.dump_session(f'./cora/node_adj_{reg1}_{reg2}.pkl') edge_weight = 0.15872583472031107 AUCs = [] ACCs = [] RBs = [] RB_ACCs = [] DIs = [] ERBs = [] ERB_ACCs = [] sym_g = node_repair(graph_train, multi_adj, multi_nodes, edge_weight=edge_weight) for i in range(5): sym_embedding_train = node2vec_embedding(StellarGraph.from_networkx(sym_g, node_features='feat'), "Train Sym Graph") sym_best_result = edge_pred(examples_train, examples_model_selection, labels_train, labels_model_selection, sym_embedding_train, num_iter=5000) test_auc = sym_best_result['score'] test_acc = sym_best_result['acc'] AUCs.append(test_auc) ACCs.append(test_acc) sym_feat = nx.get_node_attributes(sym_g, 's') rb_auc, rb_acc = RB(sym_embedding_train, sym_feat, 'sym', kfold=5) RBs.append(rb_auc) RB_ACCs.append(rb_acc) sym_di = DI(sym_best_result, examples_train, sym_g, sym_embedding_train) DIs.append(sym_di) print(f'sym_DI: {sym_di}') print('Edge RB') xor_train_label, xor_val_label = get_xor_label(examples_train, graph_train), get_xor_label(examples_model_selection, graph_train) print('sym') best_ERB_result = edge_pred(examples_train, examples_model_selection, xor_train_label, xor_val_label, sym_embedding_train, num_iter=3000) erb_auc, erb_acc = best_ERB_result['score'], best_ERB_result['acc'] ERBs.append(erb_auc) ERB_ACCs.append(erb_acc) mydict = {'AUCs': np.array(AUCs), 'ACCs': np.array(ACCs), 'RBs': np.array(RBs), 'RB_ACCs': np.array(RB_ACCs), 'DIs': np.array(DIs), 'ERBs': np.array(ERBs), 'ERB_ACCs': np.array(ERB_ACCs) } for name in mydict.keys(): print(f'{name}: {mydict[name].mean()}, {np.sqrt(mydict[name].var())} \n') # sym_di = DI(sym_best_result, examples_train, sym_g, sym_embedding_train) # DIs.append(sym_di) # print(f'sym_DI: {sym_di}') # print('Edge RB') # xor_train_label, xor_val_label = get_xor_label(examples_train, graph_train), get_xor_label(examples_model_selection, graph_train) # print('sym') # best_ERB_result = edge_pred(examples_train, examples_model_selection, xor_train_label, xor_val_label, sym_embedding_train) # erb_auc, erb_acc = best_ERB_result['score'], best_ERB_result['acc'] # ERBs.append(erb_auc) # ERB_ACCs.append(erb_acc) # sym_di = DI(sym_best_result, examples_test, graph_test, sym_embedding_test) # print(f'sym_DI: {sym_di}') # print('Edge RB') # xor_train_label, xor_val_label = get_xor_label(examples_train, graph_train), get_xor_label(examples_model_selection, graph_train) # print('sym') # edge_pred(examples_train, examples_model_selection, xor_train_label, xor_val_label, sym_embedding_train) # # dill.dump_session(f'./cora/new_{reg}.pkl')
import sys import stellargraph as sg import matplotlib.pyplot as plt from math import isclose import sklearn from sklearn.decomposition import PCA import os import networkx as nx import numpy as np import pandas as pd from stellargraph import StellarGraph, datasets from stellargraph.data import EdgeSplitter from collections import Counter import multiprocessing from IPython.display import display, HTML from sklearn.model_selection import train_test_split from src.main import * from sklearn.pipeline import Pipeline from sklearn.linear_model import LogisticRegressionCV from sklearn.metrics import roc_auc_score from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LogisticRegression from sklearn import model_selection from sklearn.multiclass import OneVsRestClassifier from sklearn import preprocessing from sklearn.model_selection import GridSearchCV from sklearn.metrics import accuracy_score import dill # is_dill = True # if is_dill: # dill.load_session('./cora/beforeRB.pkl') p = 1.0 q = 1.0 dimensions = 128 num_walks = 10 walk_length = 80 window_size = 10 num_iter = 1 import argparse parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('--reg1', type=float, help='sym reg') parser.add_argument('--reg2', type=float, help='sym reg') args = parser.parse_args() reg1 = args.reg1 reg2 = args.reg2 workers = multiprocessing.cpu_count() from stellargraph.data import BiasedRandomWalk from gensim.models import Word2Vec dill.load_session(f'./cora/node_adj_{reg1}_{reg2}.pkl') drop_weight = 0.45 emd_weight = 0.19 def RB(get_embedding, feat, name, kfold=5): embeddings = [] s = [] for i in range(len(feat.values())): embeddings.append(get_embedding(i)) s.append(str(feat[i])) X = embeddings y = s X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.3, random_state=1121218 ) from sklearn.svm import SVC clf = OneVsRestClassifier(SVC(probability=True)) # clf = LogisticRegression(solver='lbfgs') clf.fit(X_train, y_train) y_pred_probs = clf.predict_proba(X_test) # Calculate ROC_AUC results_lap = roc_auc_score( y_test, y_pred_probs, multi_class="ovr", average="weighted" ) predict_lables = clf.predict(X_test) print(f"RB on the {name} graph is: {results_lap.mean()}") acc = accuracy_score(y_test, predict_lables) return results_lap, acc def ERB(get_embedding, feat, name, kfold=5): embeddings = [] s = [] for i in range(len(feat.values())): embeddings.append(get_embedding(i)) s.append(str(feat[i])) X = embeddings y = s X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=1121218 ) from sklearn.svm import SVC clf = OneVsRestClassifier(SVC(probability=True)) # clf = LogisticRegression(solver='lbfgs') clf.fit(X_train, y_train) y_pred_probs = clf.predict_proba(X_test) # Calculate ROC_AUC results_lap = roc_auc_score( y_test, y_pred_probs, multi_class="ovr", average="weighted" ) y_predict = clf.predict(X_test) acc = accuracy_score(y_test, y_predict) print(f"RB on the {name} graph is: {results_lap.mean()}") return results_lap, acc def vis_pca(name, best_result, examples_test, embedding_test): link_features = link_examples_to_features( examples_test, embedding_test, best_result["binary_operator"] ) # Learn a projection from 128 dimensions to 2 pca = PCA(n_components=2) X_transformed = pca.fit_transform(link_features) # plot the 2-dimensional points plt.figure(figsize=(16, 12)) plt.scatter( X_transformed[:, 0], X_transformed[:, 1], c=np.where(labels_test == 1, "b", "r"), alpha=0.5, ) plt.tight_layout() plt.savefig(f'figs/dblp/{name}-pca.jpg') def vis_nx(name, g): # Visualisation of the generated graph #Retrieve indexes of node in each group s = nx.get_node_attributes(g, 's') idx_ps = [] labels = list(set(s.values())) for val in labels: idx_ps.append(get_keys_from_value(s, val)) # Draw the graph pos = nx.spring_layout(g) i = 0 colors = ['steelblue', 'gold', 'green', 'red', 'orange'] for idx_p in idx_ps: nx.draw_networkx_nodes(g, pos=pos, node_size=0.1, nodelist=idx_p, node_color=colors[i], label=f'S = {labels[i]}') nx.draw_networkx_edges(g, pos=pos) plt.legend(loc="upper left", scatterpoints=1, prop={'size': 15}) plt.tight_layout() plt.savefig(f'figs/dblp/{name}-nx.jpg') def node2vec_embedding(graph, name): rw = BiasedRandomWalk(graph) walks = rw.run(graph.nodes(), n=num_walks, length=walk_length, p=p, q=q) print(f"Number of random walks for '{name}': {len(walks)}") model = Word2Vec( walks, vector_size=dimensions, window=window_size, min_count=0, sg=1, workers=workers, # iter=num_iter, ) def get_embedding(u): return model.wv[u] return get_embedding # 1. link embeddings def link_examples_to_features(link_examples, transform_node, binary_operator): return [ binary_operator(transform_node(src), transform_node(dst)) for src, dst in link_examples ] # 2. training classifier def train_link_prediction_model( link_examples, link_labels, get_embedding, binary_operator, num_iter ): clf = link_prediction_classifier(max_iter=num_iter) link_features = link_examples_to_features( link_examples, get_embedding, binary_operator ) clf.fit(link_features, link_labels) return clf def link_prediction_classifier(max_iter=3000): lr_clf = LogisticRegressionCV(Cs=10, cv=10, scoring="roc_auc", max_iter=max_iter) return Pipeline(steps=[("sc", StandardScaler()), ("clf", lr_clf)]) # 3. and 4. evaluate classifier def evaluate_link_prediction_model( clf, link_examples_test, link_labels_test, get_embedding, binary_operator ): link_features_test = link_examples_to_features( link_examples_test, get_embedding, binary_operator ) score, acc = evaluate_roc_auc(clf, link_features_test, link_labels_test) return score, acc def evaluate_roc_auc(clf, link_features, link_labels): predicted = clf.predict_proba(link_features) # check which class corresponds to positive links positive_column = list(clf.classes_).index(1) predicted_labels = clf.predict(link_features) return roc_auc_score(link_labels, predicted[:, positive_column]), accuracy_score(link_labels, predicted_labels) def operator_hadamard(u, v): return u * v def operator_l1(u, v): return np.abs(u - v) def operator_l2(u, v): return (u - v) ** 2 def operator_avg(u, v): return (u + v) / 2.0 def run_link_prediction(embedding_train, binary_operator, examples_train, labels_train, examples_model_selection, labels_model_selection, num_iter): clf = train_link_prediction_model( examples_train, labels_train, embedding_train, binary_operator, num_iter=num_iter ) score, acc = evaluate_link_prediction_model( clf, examples_model_selection, labels_model_selection, embedding_train, binary_operator, ) return { "classifier": clf, "binary_operator": binary_operator, "score": score, 'acc': acc } def AUC_print(results): print(pd.DataFrame( [(result["binary_operator"].__name__, result["score"]) for result in results], columns=("name", "ROC AUC score"), ).set_index("name")) def DI(best_result, examples_test, g, embedding_test): link_features_test = link_examples_to_features( examples_test, embedding_test, best_result["binary_operator"] ) xor0, xor1 = [], [] feat = nx.get_node_attributes(g, 's') for i in range(len(examples_test)): if feat[examples_test[i][0]] == feat[examples_test[i][1]]: xor0.append(link_features_test[i]) else: xor1.append(link_features_test[i]) y0 = best_result["classifier"].predict(xor0) score0 = sklearn.metrics.accuracy_score(y0, np.ones_like(y0)) y1 = best_result["classifier"].predict(xor1) score1 = sklearn.metrics.accuracy_score(y1, np.ones_like(y1)) return score1/score0 binary_operators = [operator_hadamard, operator_l1, operator_l2, operator_avg] def parse_cora(plot=False): path = "./data/cora/" id2index = {} label2index = { 'Case_Based': 0, 'Genetic_Algorithms': 1, 'Neural_Networks': 2, 'Probabilistic_Methods': 3, 'Reinforcement_Learning': 4, 'Rule_Learning': 5, 'Theory': 6 } features = [] labels = [] with open(path + 'cora.content', 'r') as f: i = 0 for line in f.readlines(): items = line.strip().split('\t') id = items[0] # 1-hot encode labels label = np.zeros(len(label2index)) label[label2index[items[-1]]] = 1 labels.append(items[-1]) # parse features features.append([int(x) for x in items[1:-1]]) id2index[id] = i i += 1 features = np.asarray(features, dtype='float32') labels = np.array(labels) # labels = np.asarray(labels, dtype='int32') n_papers = len(id2index) adj = np.zeros((n_papers, n_papers), dtype='float32') with open(path + 'cora.cites', 'r') as f: for line in f.readlines(): items = line.strip().split('\t') adj[ id2index[items[0]], id2index[items[1]] ] = 1.0 # undirected adj[ id2index[items[1]], id2index[items[0]] ] = 1.0 G = nx.from_numpy_matrix(adj, nx.Graph()) feat_dict, label_dict = {}, {} for i in range(features.shape[0]): feat_dict[i] = features[i] label_dict[i] = labels[i] nx.set_node_attributes(G, feat_dict, name='feat') nx.set_node_attributes(G, label_dict, name='s') return G def load_data(): G = parse_cora() # G = nx.relabel.convert_node_labels_to_integers(G, first_label=0, ordering='default') return G def emd_repair(graph_train, num_iter=1e6, edge_weight=0.2): emd_adj, s_emd, gamma, M = multi_total_repair(graph_train, num_iter=num_iter, metric='euclidean', log=False) print('emd edges', np.sum(np.array(emd_adj) >= edge_weight)) emd_g = nx.from_numpy_matrix(emd_adj) # Filter out the smallest weights to keep a reasonable density list_edge = [(u, v) for (u, v, d) in emd_g.edges(data=True) if d['weight'] < edge_weight] emd_g.remove_edges_from(list_edge) nx.set_node_attributes(emd_g, nx.get_node_attributes(graph_train, 's'), name='s') print('Assortativity coeffcient on the emd graph: %0.3f' % nx.attribute_assortativity_coefficient(emd_g, 's')) return emd_g def drop_repair(graph_train, edge_weight=0.2): sens = nx.get_node_attributes(graph_train, 's') sens_ls = [] for i in range(len(sens)): sens_ls.append(sens[i]) sens_ls = np.array(sens_ls) mij = np.random.rand(len(sens_ls)*len(sens_ls)).reshape(len(sens_ls), len(sens_ls)) for i in range(0, len(sens_ls)): # import pdb; pdb.set_trace() mij[i][sens_ls == sens_ls[i]] = 0 mij[i][sens_ls != sens_ls[i]] = 1 myrand = np.random.rand(len(sens_ls)) mij[i][myrand < 0.5 - edge_weight] = 1- mij[i][myrand < 0.5 - edge_weight] drop_adj = nx.adjacency_matrix(graph_train) * mij drop_g = nx.from_numpy_matrix(drop_adj) # Filter out the smallest weights to keep a reasonable density nx.set_node_attributes(drop_g, nx.get_node_attributes(graph_train, 's'), name='s') print('Assortativity coeffcient on the drop graph: %0.3f' % nx.attribute_assortativity_coefficient(drop_g, 's')) return drop_g def sym_repair_adj(graph_train, num_iter=1e6, reg=1e-9): emd_adj, emd_nodes, s_emd, gamma, M = multi_node_sym_total_repair(graph_train, num_iter=num_iter, metric='euclidean', log=False, reg=reg, reg1=reg1, reg2=reg2) return emd_adj, emd_nodes def node_repair_adj(graph_train, num_iter=1e6, reg=1e-9): emd_adj, emd_nodes, s_emd, gamma, M = multi_node_total_repair(graph_train, num_iter=num_iter, metric='euclidean', log=False, reg=reg, reg1=reg1, reg2=reg2) return emd_adj, emd_nodes def node_repair(graph_train, emd_adj, emd_nodes, edge_weight=0.2): print('emd edges', np.sum(np.array(emd_adj) >= edge_weight)) emd_g = nx.from_numpy_matrix(emd_adj) # Filter out the smallest weights to keep a reasonable density list_edge = [(u, v) for (u, v, d) in emd_g.edges(data=True) if d['weight'] < edge_weight] emd_g.remove_edges_from(list_edge) emd_nodes_dict = {} for i in range(emd_nodes.shape[0]): emd_nodes_dict[i] = emd_nodes[i] nx.set_node_attributes(emd_g, emd_nodes_dict, name='feat') # import pdb; pdb.set_trace() nx.set_node_attributes(emd_g, nx.get_node_attributes(graph_train, 's'),name='s') print('Assortativity coeffcient on the node repair graph: %0.3f' % nx.attribute_assortativity_coefficient(emd_g, 's')) return emd_g def sym_repair(graph_train, emd_adj, emd_nodes, edge_weight=0.2): print('emd edges', np.sum(np.array(emd_adj) >= edge_weight)) emd_g = nx.from_numpy_matrix(emd_adj) # Filter out the smallest weights to keep a reasonable density list_edge = [(u, v) for (u, v, d) in emd_g.edges(data=True) if d['weight'] < edge_weight] emd_g.remove_edges_from(list_edge) emd_nodes_dict = {} for i in range(emd_nodes.shape[0]): emd_nodes_dict[i] = emd_nodes[i] nx.set_node_attributes(emd_g, emd_nodes_dict, name='feat') # import pdb; pdb.set_trace() nx.set_node_attributes(emd_g, nx.get_node_attributes(graph_train, 's'),name='s') print('Assortativity coeffcient on the emd graph: %0.3f' % nx.attribute_assortativity_coefficient(emd_g, 's')) return emd_g def AUC_test(best_result, examples_test,labels_test, embedding_test): test_score = evaluate_link_prediction_model( best_result["classifier"], examples_test, labels_test, embedding_test, best_result["binary_operator"], ) print( f"ROC AUC score on test set using '{best_result['binary_operator'].__name__}': {test_score}" ) def edge_pred(examples_train, examples_model_selection, labels_train, labels_model_selection, embedding_train, num_iter=2000): results = [run_link_prediction(embedding_train, op, examples_train, labels_train, examples_model_selection, labels_model_selection, num_iter = num_iter) for op in binary_operators] best_result = max(results, key=lambda result: result["score"]) AUC_print(results) return best_result def get_xor_label(examples_train, graph_train): feat = nx.get_node_attributes(graph_train, 's') xor_labels = [] for example in examples_train: if feat[example[0]] == feat[example[1]]: xor_labels.append(0) else: xor_labels.append(1) return xor_labels is_dill = True if not is_dill: G = load_data() # nx.set_node_attributes(G, node_feat, 's') print('Assortativity coeffcient on the origin graph: %0.3f' % nx.attribute_assortativity_coefficient(G, 's')) print("Correcting the graph with EMD") edge_splitter_test = EdgeSplitter(G) # Randomly sample a fraction p=0.1 of all positive links, and same number of negative links, from graph, and obtain the # reduced graph graph_test with the sampled links removed: graph_test, examples_test, labels_test = edge_splitter_test.train_test_split( p=0.1, method="global" ) # Do the same process to compute a training subset from within the test graph edge_splitter_train = EdgeSplitter(graph_test, G) graph_train, examples, labels = edge_splitter_train.train_test_split( p=0.1, method="global" ) # REPAIRG drop_g = drop_repair(graph_train, edge_weight=drop_weight) emd_g = emd_repair(graph_train, num_iter=1e6, edge_weight=0.12) # EMBEDDING with node2vec embedding_train = node2vec_embedding(StellarGraph.from_networkx(graph_train, node_features='feat'), "Train Graph") emd_embedding_train = node2vec_embedding(StellarGraph.from_networkx(emd_g, node_features='feat'), "EMD Train Graph") drop_embedding_train = node2vec_embedding(StellarGraph.from_networkx(drop_g), "Drop Train Graph") # TRAIN and VAL ( examples_train, examples_model_selection, labels_train, labels_model_selection, ) = train_test_split(examples, labels, train_size=0.75, test_size=0.25) print('origin') ori_best_result = edge_pred(examples_train, examples_model_selection, labels_train, labels_model_selection, embedding_train) print('drop') drop_best_result = edge_pred(examples_train, examples_model_selection, labels_train, labels_model_selection, drop_embedding_train) print('emd') emd_best_result = edge_pred(examples_train, examples_model_selection, labels_train, labels_model_selection, emd_embedding_train) embedding_test = node2vec_embedding(StellarGraph.from_networkx(graph_test), "Test Graph") print('origin graph') AUC_test(ori_best_result, examples_test,labels_test, embedding_test) print('drop graph') drop_graph_test = drop_repair(graph_test, edge_weight=drop_weight) drop_embedding_test = node2vec_embedding(StellarGraph.from_networkx(drop_graph_test), "Drop Test Graph") AUC_test(drop_best_result, examples_test,labels_test, drop_embedding_test) print('emd graph') emd_graph_test = emd_repair(graph_test, num_iter=1e6, edge_weight=emd_weight) emd_embedding_test = node2vec_embedding(StellarGraph.from_networkx(emd_graph_test), "EMD Test Graph") AUC_test(emd_best_result, examples_test,labels_test, emd_embedding_test) # RB ori_feat = nx.get_node_attributes(graph_train, 's') RB(embedding_train, ori_feat, 'origin', kfold=5) drop_feat = nx.get_node_attributes(drop_g, 's') RB(drop_embedding_train, drop_feat, 'emd', kfold=5) emd_feat = nx.get_node_attributes(emd_g, 's') RB(emd_embedding_train, emd_feat, 'emd', kfold=5) # DI ori_di = DI(ori_best_result, examples_test, graph_test, embedding_test) drop_di = DI(drop_best_result, examples_test, graph_test, drop_embedding_test) emd_di = DI(emd_best_result, examples_test, graph_test, emd_embedding_test) print(f'ori_DI: {ori_di}, drop_DI: {drop_di}, emd_DI: {emd_di}') dill.dump_session('./cora/beforeERB.pkl') # ERB print('Edge RB') xor_train_label, xor_val_label = get_xor_label(examples_train, graph_train), get_xor_label(examples_model_selection, graph_train) print('ori') edge_pred(examples_train, examples_model_selection, xor_train_label, xor_val_label, embedding_train) print('drop') edge_pred(examples_train, examples_model_selection, xor_train_label, xor_val_label, drop_embedding_train) print('emd') edge_pred(examples_train, examples_model_selection, xor_train_label, xor_val_label, emd_embedding_train) # VISUALIZATION # Calculate edge features for test data vis_pca('origin', ori_best_result, examples_test, embedding_test) vis_pca('drop', drop_best_result, examples_test, drop_embedding_test) vis_pca('emd', emd_best_result, examples_test, emd_embedding_test) vis_nx('origin', graph_train) vis_nx('drop', drop_g) vis_nx('emd', emd_g) dill.dump_session('./cora/beforeSym.pkl') exit() # else: # dill.load_session(f'./cora/sym_adj_{reg}.pkl') # reg = 1e-3 # sym_g = sym_repair_adj(graph_train, num_iter=1e4, reg=reg) # sym_testg = sym_repair_adj(graph_test, num_iter=1e4, reg=reg) # results = [run_link_prediction(embedding_train, op, examples_train, labels_train, examples_model_selection, # labels_model_selection,) for op in binary_operators] # best_result = max(results, key=lambda result: result["score"]) # AUC_print(results) # emd_results = [run_link_prediction(emd_embedding_train, op, examples_train, labels_train, examples_model_selection, # labels_model_selection,) for op in binary_operators] # emd_best_result = max(emd_results, key=lambda result: result["score"]) # print('emd repair') # AUC_print(emd_results) # # TEST AUC # embedding_test = node2vec_embedding(StellarGraph.from_networkx(graph_test, node_features='feat'), "Test Graph") # print('origin graph') # AUC_test(best_result, examples_test,labels_test, embedding_test) # print('emd graph') # emd_graph_test = emd_repair(graph_test) # emd_embedding_test = node2vec_embedding(StellarGraph.from_networkx(emd_graph_test, node_features='feat'), "EMD Test Graph") # AUC_test(emd_best_result, examples_test,labels_test, emd_embedding_test) # ori_feat = nx.get_node_attributes(graph_test, 's') # RB(embedding_test, ori_feat, 'origin', kfold=5) # emd_feat = nx.get_node_attributes(emd_graph_test, 's') # RB(emd_embedding_test, emd_feat, 'emd', kfold=5) # # DI # ori_di = DI(best_result, examples_test, graph_test, embedding_test) # emd_di = DI(emd_best_result, examples_test, graph_test, emd_embedding_test) # print(f'ori_DI: {ori_di}, emd_DI: {emd_di}') # # VISUALIZATION # # Calculate edge features for test data # vis_pca('origin', best_result, examples_test, embedding_test) # vis_pca('emd', emd_best_result, examples_test, embedding_test) # vis_nx('origin', graph_train) # vis_nx('emd', emd_g) # dill.dump_session('./cora/beforeRB.pkl') # reg = 1e-3 # sym_g = sym_repair_adj(graph_train, num_iter=1e4, reg=reg) # sym_testg = sym_repair_adj(graph_test, num_iter=1e4, reg=reg) # multi_adj, multi_nodes = node_repair_adj(graph_train, num_iter=1e4, reg=0) # sym_test_adj, sym_test_nodes = node_repair_adj(graph_test, num_iter=1e4, reg=0) # dill.dump_session(f'./cora/node_adj_{reg1}_{reg2}.pkl') edge_weight = 0.15872583472031107 AUCs = [] ACCs = [] RBs = [] RB_ACCs = [] DIs = [] ERBs = [] ERB_ACCs = [] sym_g = node_repair(graph_train, multi_adj, multi_nodes, edge_weight=edge_weight) for i in range(5): sym_embedding_train = node2vec_embedding(StellarGraph.from_networkx(sym_g, node_features='feat'), "Train Sym Graph") sym_best_result = edge_pred(examples_train, examples_model_selection, labels_train, labels_model_selection, sym_embedding_train, num_iter=5000) test_auc = sym_best_result['score'] test_acc = sym_best_result['acc'] AUCs.append(test_auc) ACCs.append(test_acc) sym_feat = nx.get_node_attributes(sym_g, 's') rb_auc, rb_acc = RB(sym_embedding_train, sym_feat, 'sym', kfold=5) RBs.append(rb_auc) RB_ACCs.append(rb_acc) sym_di = DI(sym_best_result, examples_train, sym_g, sym_embedding_train) DIs.append(sym_di) print(f'sym_DI: {sym_di}') print('Edge RB') xor_train_label, xor_val_label = get_xor_label(examples_train, graph_train), get_xor_label(examples_model_selection, graph_train) print('sym') best_ERB_result = edge_pred(examples_train, examples_model_selection, xor_train_label, xor_val_label, sym_embedding_train, num_iter=3000) erb_auc, erb_acc = best_ERB_result['score'], best_ERB_result['acc'] ERBs.append(erb_auc) ERB_ACCs.append(erb_acc) mydict = {'AUCs': np.array(AUCs), 'ACCs': np.array(ACCs), 'RBs': np.array(RBs), 'RB_ACCs': np.array(RB_ACCs), 'DIs': np.array(DIs), 'ERBs': np.array(ERBs), 'ERB_ACCs': np.array(ERB_ACCs) } for name in mydict.keys(): print(f'{name}: {mydict[name].mean()}, {np.sqrt(mydict[name].var())} \n') # sym_di = DI(sym_best_result, examples_train, sym_g, sym_embedding_train) # DIs.append(sym_di) # print(f'sym_DI: {sym_di}') # print('Edge RB') # xor_train_label, xor_val_label = get_xor_label(examples_train, graph_train), get_xor_label(examples_model_selection, graph_train) # print('sym') # best_ERB_result = edge_pred(examples_train, examples_model_selection, xor_train_label, xor_val_label, sym_embedding_train) # erb_auc, erb_acc = best_ERB_result['score'], best_ERB_result['acc'] # ERBs.append(erb_auc) # ERB_ACCs.append(erb_acc) # sym_di = DI(sym_best_result, examples_test, graph_test, sym_embedding_test) # print(f'sym_DI: {sym_di}') # print('Edge RB') # xor_train_label, xor_val_label = get_xor_label(examples_train, graph_train), get_xor_label(examples_model_selection, graph_train) # print('sym') # edge_pred(examples_train, examples_model_selection, xor_train_label, xor_val_label, sym_embedding_train) # # dill.dump_session(f'./cora/new_{reg}.pkl')
# vim: sw=4:ts=4:et:cc=120 import datetime import hashlib import json import logging import os import requests import saq from saq.analysis import Analysis from saq.constants import * from saq.modules.sandbox import * from wildfirelib import parse class WildfireAnalysis(Analysis): def initialize_details(self): self.details = { 'sha256': None, 'verdict': None, 'submit_date': None, 'report': None } def init(self, path): self.report = None self.sha256 = hashlib.sha256(open(path, 'rb').read()).hexdigest() def fail(self, message, error): self.verdict = '-101' try: error = error.split('<error-message>')[1].split('</error-message>')[0].strip().strip("'") except: error.replace('\n','').replace('\r','') self.report = f'{message}: {error}' logging.debug(f'{message}: {error}') @property def sha256(self): return self.details['sha256'] @sha256.setter def sha256(self, value): self.details['sha256'] = value self.set_modified() @property def verdict(self): return self.details['verdict'] @verdict.setter def verdict(self, value): self.details['verdict'] = value self.set_modified() @property def submit_date(self): return self.details['submit_date'] @submit_date.setter def submit_date(self, value): self.details['submit_date'] = value self.set_modified() @property def report(self): return self.details_property('report') @report.setter def report(self, value): self.details['report'] = value self.set_modified() def generate_summary(self): if self.verdict is None: return None elif self.verdict == '-100': return 'Wildfire Analysis - Incomplete' elif self.verdict == '-101': if not hasattr(self, 'report') or self.report is None: return 'Wildfire Analysis - Missing Report' if self.report.endswith('Unsupported File type'): return 'Wildfire Analysis - Unsupported File Type' return 'Wildfire Analysis - Failed' elif self.verdict == '-102': return 'Wildfire Analysis - Not Submitted' elif self.verdict == '0': return 'Wildfire Analysis - Benign' elif self.verdict == '1': return 'Wildfire Analysis - Malware' elif self.verdict == '2': return 'Wildfire Analysis - Grayware' else: return f'Wildfire Analysis - Verdict Not Recognized {self.verdict}' class WildfireAnalyzer(SandboxAnalysisModule): @property def api_key(self): return self.config['api_key'] @property def timeout(self): return self.config.getint('timeout') @property def frequency(self): return self.config.getint('frequency') @property def query_only(self): return self.config.getboolean('query_only') @property def generated_analysis_type(self): return WildfireAnalysis def verify_environment(self): self.verify_config_exists('frequency') self.verify_config_exists('api_key') self.verify_config_exists('use_proxy') self.verify_config_exists('timeout') self.verify_config_exists('supported_extensions') def execute_analysis(self, _file): def walk_tree(process_json=None, processes=None, previous_pid=0): if not processes: processes = ProcessList() if isinstance(process_json, dict): process_json = [process_json] if process_json: for process in process_json: new_process = Process() new_process.command = process['@text'] new_process.pid = process['@pid'] new_process.parent_pid = previous_pid processes.append(new_process) try: processes = walk_tree(process['child']['process'], processes, process['@pid']) except: pass return processes # we want to sandbox the root file which this file originated from while _file.redirection: _file = _file.redirection path = os.path.join(self.root.storage_dir, _file.value) # create new wildfire analysis if none exists analysis = _file.get_analysis(WildfireAnalysis) if analysis is None: analysis = self.create_analysis(_file) analysis.init(path) # does this file even exist? if not os.path.exists(os.path.join(self.root.storage_dir, _file.value)): logging.debug(f'{_file} does not exist') return # does this file have a supported file extension? is_supported = False file_extension = None try: file_extension = _file.value.rsplit('.', 1)[-1] except IndexError: pass if not self.is_sandboxable_file(os.path.join(self.root.storage_dir, _file.value)): logging.debug(f'{_file} is not a supported file type for WildFire analysis') return # request verdict from wildfire job = {'apikey': self.api_key, 'hash': analysis.sha256} url = 'https://wildfire.paloaltonetworks.com/publicapi/get/verdict' try: r = requests.post(url, data=job, verify=False, proxies=self.proxies) except Exception as e: message = f'error while getting wildfire verdict: {e.__class__} - {e}' logging.error(message) raise ValueError(message) if r.status_code != 200: analysis.fail(f'failed to get verdict {r.status_code}', r.text) return try: analysis.verdict = r.text.split('<verdict>')[1].split('</verdict>')[0].strip() except: analysis.fail('failed to get verdict 200', 'format not recognized') return # if wildfire failed to analyze file if analysis.verdict == '-101': analysis.fail(r.text) return # if wildfire has never analyzed this file before then submit it and check back later elif analysis.verdict == '-102': if self.query_only: # Do not upload files, so exit if Wildfire doesn't know about this file return False logging.debug(f'submitting {path} to wildfire for analysis') file = {'file': (os.path.basename(path), open(path, 'rb').read())} url = 'https://wildfire.paloaltonetworks.com/publicapi/submit/file' try: r = requests.post(url, data=job, files=file, verify=False, proxies=self.proxies) except Exception as e: message = f'error while submitting file for wildfire analysis: {e.__class__} - {e}' logging.error(message) raise ValueError(message) if r.status_code != 200: analysis.fail(f'failed to submit file {r.status_code}', r.text) return self.delay_analysis(_file, analysis, seconds=self.frequency) analysis.submit_date = datetime.datetime.now() return # if wildfire is currently analyzing the file then check back later elif analysis.verdict == '-100': # XXX refactor this out -- should already be a datetime object to begin with # I think that in some cases wildfire may already be processing a given file # in that case we may not receive a -102 message and thus not have a submit_date if not analysis.submit_date: logging.warning(f'{path} got -100 result from wildfire without a submit date set (already processing?)') analysis.submit_date = datetime.datetime.now() else: submit_date = analysis.submit_date if isinstance(submit_date, str): submit_date = datetime.datetime.strptime(submit_date, '%Y-%m-%dT%H:%M:%S.%f') if datetime.datetime.now() > (submit_date + datetime.timedelta(minutes=self.timeout)): logging.error(f'submission for {_file.value} sha256 {analysis.sha256} has timed out') return logging.debug('waiting on wildfire analysis...') self.delay_analysis(_file, analysis, seconds=self.frequency) return # tag appropriately if verdict is malware or grayware if analysis.verdict == '1': _file.add_tag('malicious') elif analysis.verdict == '2': _file.add_tag('grayware') # download the report logging.debug('downloading wildfire report') url = 'https://wildfire.paloaltonetworks.com/publicapi/get/report' try: r = requests.post(url, data=job, verify=False, proxies=self.proxies) except Exception as e: message = f'error while getting wildfire report: {e.__class__} - {e}' logging.error(message) raise ValueError(message) if r.status_code != 200: analysis.fail(f'failed to get report {r.status_code}', r.text) return report_json = parse(r.text) # store the report wildfire_dir = f'{path}.wildfire' if not os.path.isdir(wildfire_dir): os.mkdir(wildfire_dir) report_path = os.path.join(wildfire_dir, 'report.json') with open(report_path, 'w') as report: json.dump(report_json, report) analysis.add_observable(F_FILE, os.path.relpath(report_path, start=self.root.storage_dir)) sandbox_report = GenericSandboxReport() sandbox_report.filename = os.path.basename(os.path.normpath(path)) # MD5 try: sandbox_report.md5 = report_json['wildfire']['file_info']['md5'] md5 = analysis.add_observable(F_MD5, sandbox_report.md5) if md5: md5.add_tag('wildfire_sandbox_sample') analysis.add_ioc(I_MD5, sandbox_report.md5, tags=['wildfire_sandbox_sample']) except: logging.error('Unable to parse WildFire Sandbox md5') # SHA1 try: sandbox_report.sha1 = report_json['wildfire']['file_info']['sha1'] sha1 = analysis.add_observable(F_SHA1, sandbox_report.sha1) if sha1: sha1.add_tag('wildfire_sandbox_sample') analysis.add_ioc(I_SHA1, sandbox_report.sha1, tags=['wildfire_sandbox_sample']) except: logging.error('Unable to parse WildFire Sandbox sha1') # SHA256 try: sandbox_report.sha256 = report_json['wildfire']['file_info']['sha256'] sha256 = analysis.add_observable(F_SHA256, sandbox_report.sha256) if sha256: sha256.add_tag('wildfire_sandbox_sample') analysis.add_ioc(I_SHA256, sandbox_report.sha256, tags=['wildfire_sandbox_sample']) sandbox_report.sandbox_urls.add(f'https://wildfire.paloaltonetworks.com/wildfire/reportlist?search={sandbox_report.sha256}') except: logging.error('Unable to parse WildFire Sandbox sha256') try: reports = report_json['wildfire']['task_info']['report'] except KeyError: reports = [] # Pick one of the process trees to use instead of all of them process_tree_to_use = None process_tree_to_use_size = 0 for report in reports: # Process Tree try: process_tree = report['process_tree']['process'] process_tree_size = len(str(process_tree)) if process_tree_size > process_tree_to_use_size: process_tree_to_use = process_tree process_tree_to_use_size = process_tree_size except: pass # Contacted Hosts try: contacted_hosts_json = report['network']['TCP'] except: contacted_hosts_json = [] if isinstance(contacted_hosts_json, dict): contacted_hosts_json = [contacted_hosts_json] for host in contacted_hosts_json: h = ContactedHost() try: h.ip = host['@ip'] ipv4 = analysis.add_observable(F_IPV4, h.ip) if ipv4: ipv4.add_tag('contacted_host') analysis.add_ioc(I_IP_DEST, h.ip, tags=['contacted_host']) except: pass try: h.port = host['@port'] except: pass try: h.protocol = 'TCP' except: pass try: h.location = host['@country'] except: pass sandbox_report.contacted_hosts.append(h) try: contacted_hosts_json = report['network']['UDP'] except: contacted_hosts_json = [] if isinstance(contacted_hosts_json, dict): contacted_hosts_json = [contacted_hosts_json] for host in contacted_hosts_json: h = ContactedHost() try: h.ip = host['@ip'] ipv4 = analysis.add_observable(F_IPV4, h.ip) if ipv4: ipv4.add_tag('contacted_host') analysis.add_ioc(I_IP_DEST, h.ip, tags=['contacted_host']) except: pass try: h.port = host['@port'] except: pass try: h.protocol = 'UDP' except: pass try: h.location = host['@country'] except: pass sandbox_report.contacted_hosts.append(h) # DNS Requests try: dns_requests_json = report['network']['dns'] except: dns_requests_json = [] if isinstance(dns_requests_json, dict): dns_requests_json = [dns_requests_json] for dns_request in dns_requests_json: r = DnsRequest() try: r.request = dns_request['@query'] dns = analysis.add_observable(F_FQDN, r.request) if dns: dns.add_tag('dns_request') analysis.add_ioc(I_DOMAIN, r.request, tags=['dns_request']) except: pass try: r.type = dns_request['@type'] except: pass try: r.answer = dns_request['@response'] dns_answer = analysis.add_observable(F_IPV4, r.answer) if dns_answer: dns_answer.add_tag('dns_answer') analysis.add_ioc(I_IP_DEST, r.answer, tags=['dns_answer']) except: pass sandbox_report.dns_requests.append(r) # Processes try: processes_json = report['process_list']['process'] except: processes_json = [] if isinstance(processes_json, dict): processes_json = [processes_json] # Dropped Files for process in processes_json: try: dropped_files_json = process['file']['Create'] except: dropped_files_json = [] if isinstance(dropped_files_json, dict): dropped_files_json = [dropped_files_json] for file in dropped_files_json: f = DroppedFile() try: f.filename = file['@name'].split('\\')[-1] except: pass try: f.path = file['@name'] except: pass try: f.size = file['@size'] except: pass try: f.type = file['@type'] except: pass try: if file['@md5'] != 'N/A': f.md5 = file['@md5'] md5 = analysis.add_observable(F_MD5, f.md5) if md5: md5.add_tag('dropped_file') analysis.add_ioc(I_MD5, f.md5, tags=['dropped_file']) except: pass try: f.sha1 = file['@sha1'] analysis.add_ioc(I_SHA1, f.sha1, tags=['dropped_file']) except: pass try: f.sha256 = file['@sha256'] analysis.add_ioc(I_SHA256, f.sha256, tags=['dropped_file']) except: pass # Attempt to download any dropped files from WildFire and add them to the analysis if f.filename and f.md5 != 'N/A': job = {'apikey': self.api_key, 'hash': f.md5} url = 'https://wildfire.paloaltonetworks.com/publicapi/get/sample' try: r = requests.post(url, data=job, verify=False, proxies=self.proxies) except Exception as e: message = f'Error getting WildFire dropped file: {e.__class__} - {e}' logging.exception(message) raise ValueError(message) if r.status_code == 200: outpath = os.path.join(wildfire_dir, f.filename) with open(outpath, 'wb') as fp: fp.write(r.content) sample = analysis.add_observable(F_FILE, os.path.relpath(outpath, start=self.root.storage_dir)) if sample: sample.add_tag('dropped_file') sandbox_report.dropped_files.append(f) # Mutexes for process in processes_json: try: mutexes_json = process['mutex']['CreateMutex'] except: mutexes_json = [] for mutex_json in mutexes_json: if isinstance(mutex_json, dict): mutex_json = [mutex_json] for mutex in mutex_json: try: if mutex['@name'] != '<NULL>': sandbox_report.mutexes.add(mutex['@name']) except: logging.error(f'Error parsing WildFire mutex: {mutex}') # Registry for process in processes_json: try: registry_json = process['registry'] if process['registry'] else [] except: registry_json = [] for registry_action in registry_json: if isinstance(registry_json[registry_action], dict): registry_json[registry_action] = [registry_json[registry_action]] for registry_key in registry_json[registry_action]: try: sandbox_report.registry_keys.add(f'{registry_key['@key']}\\{registry_key['@subkey']}') except: logging.error(f'Error parsing WildFire registry key: {registry_key}') # Process tree URLs for process_url in sandbox_report.process_tree_urls: url = analysis.add_observable(F_URL, process_url) if url: url.add_tag('process_tree_url') analysis.iocs.add_url_iocs(process_url, tags=['process_tree_url']) # Walk the process tree that was chosen and add the processes to the parsed sandbox report sandbox_report.processes = walk_tree(process_json=process_tree_to_use) # Add the parsed report as a file observable parsed_report_path = os.path.join(wildfire_dir, 'parsed_report.json') with open(parsed_report_path, 'w') as f: json.dump(sandbox_report.json, f) analysis.add_observable(F_FILE, os.path.relpath(parsed_report_path, start=self.root.storage_dir)) # Add the dropped file paths as a file observable if sandbox_report.dropped_files: file_file_path = os.path.join(wildfire_dir, 'report.windows_filepath') with open(file_file_path, 'w') as file_file: file_file.writelines(sorted([f'{f.path}\n' for f in sandbox_report.dropped_files])) analysis.add_observable(F_FILE, os.path.relpath(file_file_path, start=self.root.storage_dir)) # Add the mutexes as a file observable if sandbox_report.mutexes: mutex_file_path = os.path.join(wildfire_dir, 'report.windows_mutex') with open(mutex_file_path, 'w') as mutex_file: mutex_file.writelines(sorted([f'{mutex}\n' for mutex in sandbox_report.mutexes])) analysis.add_observable(F_FILE, os.path.relpath(mutex_file_path, start=self.root.storage_dir)) # Add the registry keys as a file observable if sandbox_report.registry_keys: reg_file_path = os.path.join(wildfire_dir, 'report.windows_registry') with open(reg_file_path, 'w') as reg_file: reg_file.writelines(sorted([f'{reg}\n' for reg in sandbox_report.registry_keys])) analysis.add_observable(F_FILE, os.path.relpath(reg_file_path, start=self.root.storage_dir)) # Save the parsed report to the analysis details analysis.report = sandbox_report.json
# vim: sw=4:ts=4:et:cc=120 import datetime import hashlib import json import logging import os import requests import saq from saq.analysis import Analysis from saq.constants import * from saq.modules.sandbox import * from wildfirelib import parse class WildfireAnalysis(Analysis): def initialize_details(self): self.details = { 'sha256': None, 'verdict': None, 'submit_date': None, 'report': None } def init(self, path): self.report = None self.sha256 = hashlib.sha256(open(path, 'rb').read()).hexdigest() def fail(self, message, error): self.verdict = '-101' try: error = error.split('<error-message>')[1].split('</error-message>')[0].strip().strip("'") except: error.replace('\n','').replace('\r','') self.report = f'{message}: {error}' logging.debug(f'{message}: {error}') @property def sha256(self): return self.details['sha256'] @sha256.setter def sha256(self, value): self.details['sha256'] = value self.set_modified() @property def verdict(self): return self.details['verdict'] @verdict.setter def verdict(self, value): self.details['verdict'] = value self.set_modified() @property def submit_date(self): return self.details['submit_date'] @submit_date.setter def submit_date(self, value): self.details['submit_date'] = value self.set_modified() @property def report(self): return self.details_property('report') @report.setter def report(self, value): self.details['report'] = value self.set_modified() def generate_summary(self): if self.verdict is None: return None elif self.verdict == '-100': return 'Wildfire Analysis - Incomplete' elif self.verdict == '-101': if not hasattr(self, 'report') or self.report is None: return 'Wildfire Analysis - Missing Report' if self.report.endswith('Unsupported File type'): return 'Wildfire Analysis - Unsupported File Type' return 'Wildfire Analysis - Failed' elif self.verdict == '-102': return 'Wildfire Analysis - Not Submitted' elif self.verdict == '0': return 'Wildfire Analysis - Benign' elif self.verdict == '1': return 'Wildfire Analysis - Malware' elif self.verdict == '2': return 'Wildfire Analysis - Grayware' else: return f'Wildfire Analysis - Verdict Not Recognized {self.verdict}' class WildfireAnalyzer(SandboxAnalysisModule): @property def api_key(self): return self.config['api_key'] @property def timeout(self): return self.config.getint('timeout') @property def frequency(self): return self.config.getint('frequency') @property def query_only(self): return self.config.getboolean('query_only') @property def generated_analysis_type(self): return WildfireAnalysis def verify_environment(self): self.verify_config_exists('frequency') self.verify_config_exists('api_key') self.verify_config_exists('use_proxy') self.verify_config_exists('timeout') self.verify_config_exists('supported_extensions') def execute_analysis(self, _file): def walk_tree(process_json=None, processes=None, previous_pid=0): if not processes: processes = ProcessList() if isinstance(process_json, dict): process_json = [process_json] if process_json: for process in process_json: new_process = Process() new_process.command = process['@text'] new_process.pid = process['@pid'] new_process.parent_pid = previous_pid processes.append(new_process) try: processes = walk_tree(process['child']['process'], processes, process['@pid']) except: pass return processes # we want to sandbox the root file which this file originated from while _file.redirection: _file = _file.redirection path = os.path.join(self.root.storage_dir, _file.value) # create new wildfire analysis if none exists analysis = _file.get_analysis(WildfireAnalysis) if analysis is None: analysis = self.create_analysis(_file) analysis.init(path) # does this file even exist? if not os.path.exists(os.path.join(self.root.storage_dir, _file.value)): logging.debug(f'{_file} does not exist') return # does this file have a supported file extension? is_supported = False file_extension = None try: file_extension = _file.value.rsplit('.', 1)[-1] except IndexError: pass if not self.is_sandboxable_file(os.path.join(self.root.storage_dir, _file.value)): logging.debug(f'{_file} is not a supported file type for WildFire analysis') return # request verdict from wildfire job = {'apikey': self.api_key, 'hash': analysis.sha256} url = 'https://wildfire.paloaltonetworks.com/publicapi/get/verdict' try: r = requests.post(url, data=job, verify=False, proxies=self.proxies) except Exception as e: message = f'error while getting wildfire verdict: {e.__class__} - {e}' logging.error(message) raise ValueError(message) if r.status_code != 200: analysis.fail(f'failed to get verdict {r.status_code}', r.text) return try: analysis.verdict = r.text.split('<verdict>')[1].split('</verdict>')[0].strip() except: analysis.fail('failed to get verdict 200', 'format not recognized') return # if wildfire failed to analyze file if analysis.verdict == '-101': analysis.fail(r.text) return # if wildfire has never analyzed this file before then submit it and check back later elif analysis.verdict == '-102': if self.query_only: # Do not upload files, so exit if Wildfire doesn't know about this file return False logging.debug(f'submitting {path} to wildfire for analysis') file = {'file': (os.path.basename(path), open(path, 'rb').read())} url = 'https://wildfire.paloaltonetworks.com/publicapi/submit/file' try: r = requests.post(url, data=job, files=file, verify=False, proxies=self.proxies) except Exception as e: message = f'error while submitting file for wildfire analysis: {e.__class__} - {e}' logging.error(message) raise ValueError(message) if r.status_code != 200: analysis.fail(f'failed to submit file {r.status_code}', r.text) return self.delay_analysis(_file, analysis, seconds=self.frequency) analysis.submit_date = datetime.datetime.now() return # if wildfire is currently analyzing the file then check back later elif analysis.verdict == '-100': # XXX refactor this out -- should already be a datetime object to begin with # I think that in some cases wildfire may already be processing a given file # in that case we may not receive a -102 message and thus not have a submit_date if not analysis.submit_date: logging.warning(f'{path} got -100 result from wildfire without a submit date set (already processing?)') analysis.submit_date = datetime.datetime.now() else: submit_date = analysis.submit_date if isinstance(submit_date, str): submit_date = datetime.datetime.strptime(submit_date, '%Y-%m-%dT%H:%M:%S.%f') if datetime.datetime.now() > (submit_date + datetime.timedelta(minutes=self.timeout)): logging.error(f'submission for {_file.value} sha256 {analysis.sha256} has timed out') return logging.debug('waiting on wildfire analysis...') self.delay_analysis(_file, analysis, seconds=self.frequency) return # tag appropriately if verdict is malware or grayware if analysis.verdict == '1': _file.add_tag('malicious') elif analysis.verdict == '2': _file.add_tag('grayware') # download the report logging.debug('downloading wildfire report') url = 'https://wildfire.paloaltonetworks.com/publicapi/get/report' try: r = requests.post(url, data=job, verify=False, proxies=self.proxies) except Exception as e: message = f'error while getting wildfire report: {e.__class__} - {e}' logging.error(message) raise ValueError(message) if r.status_code != 200: analysis.fail(f'failed to get report {r.status_code}', r.text) return report_json = parse(r.text) # store the report wildfire_dir = f'{path}.wildfire' if not os.path.isdir(wildfire_dir): os.mkdir(wildfire_dir) report_path = os.path.join(wildfire_dir, 'report.json') with open(report_path, 'w') as report: json.dump(report_json, report) analysis.add_observable(F_FILE, os.path.relpath(report_path, start=self.root.storage_dir)) sandbox_report = GenericSandboxReport() sandbox_report.filename = os.path.basename(os.path.normpath(path)) # MD5 try: sandbox_report.md5 = report_json['wildfire']['file_info']['md5'] md5 = analysis.add_observable(F_MD5, sandbox_report.md5) if md5: md5.add_tag('wildfire_sandbox_sample') analysis.add_ioc(I_MD5, sandbox_report.md5, tags=['wildfire_sandbox_sample']) except: logging.error('Unable to parse WildFire Sandbox md5') # SHA1 try: sandbox_report.sha1 = report_json['wildfire']['file_info']['sha1'] sha1 = analysis.add_observable(F_SHA1, sandbox_report.sha1) if sha1: sha1.add_tag('wildfire_sandbox_sample') analysis.add_ioc(I_SHA1, sandbox_report.sha1, tags=['wildfire_sandbox_sample']) except: logging.error('Unable to parse WildFire Sandbox sha1') # SHA256 try: sandbox_report.sha256 = report_json['wildfire']['file_info']['sha256'] sha256 = analysis.add_observable(F_SHA256, sandbox_report.sha256) if sha256: sha256.add_tag('wildfire_sandbox_sample') analysis.add_ioc(I_SHA256, sandbox_report.sha256, tags=['wildfire_sandbox_sample']) sandbox_report.sandbox_urls.add(f'https://wildfire.paloaltonetworks.com/wildfire/reportlist?search={sandbox_report.sha256}') except: logging.error('Unable to parse WildFire Sandbox sha256') try: reports = report_json['wildfire']['task_info']['report'] except KeyError: reports = [] # Pick one of the process trees to use instead of all of them process_tree_to_use = None process_tree_to_use_size = 0 for report in reports: # Process Tree try: process_tree = report['process_tree']['process'] process_tree_size = len(str(process_tree)) if process_tree_size > process_tree_to_use_size: process_tree_to_use = process_tree process_tree_to_use_size = process_tree_size except: pass # Contacted Hosts try: contacted_hosts_json = report['network']['TCP'] except: contacted_hosts_json = [] if isinstance(contacted_hosts_json, dict): contacted_hosts_json = [contacted_hosts_json] for host in contacted_hosts_json: h = ContactedHost() try: h.ip = host['@ip'] ipv4 = analysis.add_observable(F_IPV4, h.ip) if ipv4: ipv4.add_tag('contacted_host') analysis.add_ioc(I_IP_DEST, h.ip, tags=['contacted_host']) except: pass try: h.port = host['@port'] except: pass try: h.protocol = 'TCP' except: pass try: h.location = host['@country'] except: pass sandbox_report.contacted_hosts.append(h) try: contacted_hosts_json = report['network']['UDP'] except: contacted_hosts_json = [] if isinstance(contacted_hosts_json, dict): contacted_hosts_json = [contacted_hosts_json] for host in contacted_hosts_json: h = ContactedHost() try: h.ip = host['@ip'] ipv4 = analysis.add_observable(F_IPV4, h.ip) if ipv4: ipv4.add_tag('contacted_host') analysis.add_ioc(I_IP_DEST, h.ip, tags=['contacted_host']) except: pass try: h.port = host['@port'] except: pass try: h.protocol = 'UDP' except: pass try: h.location = host['@country'] except: pass sandbox_report.contacted_hosts.append(h) # DNS Requests try: dns_requests_json = report['network']['dns'] except: dns_requests_json = [] if isinstance(dns_requests_json, dict): dns_requests_json = [dns_requests_json] for dns_request in dns_requests_json: r = DnsRequest() try: r.request = dns_request['@query'] dns = analysis.add_observable(F_FQDN, r.request) if dns: dns.add_tag('dns_request') analysis.add_ioc(I_DOMAIN, r.request, tags=['dns_request']) except: pass try: r.type = dns_request['@type'] except: pass try: r.answer = dns_request['@response'] dns_answer = analysis.add_observable(F_IPV4, r.answer) if dns_answer: dns_answer.add_tag('dns_answer') analysis.add_ioc(I_IP_DEST, r.answer, tags=['dns_answer']) except: pass sandbox_report.dns_requests.append(r) # Processes try: processes_json = report['process_list']['process'] except: processes_json = [] if isinstance(processes_json, dict): processes_json = [processes_json] # Dropped Files for process in processes_json: try: dropped_files_json = process['file']['Create'] except: dropped_files_json = [] if isinstance(dropped_files_json, dict): dropped_files_json = [dropped_files_json] for file in dropped_files_json: f = DroppedFile() try: f.filename = file['@name'].split('\\')[-1] except: pass try: f.path = file['@name'] except: pass try: f.size = file['@size'] except: pass try: f.type = file['@type'] except: pass try: if file['@md5'] != 'N/A': f.md5 = file['@md5'] md5 = analysis.add_observable(F_MD5, f.md5) if md5: md5.add_tag('dropped_file') analysis.add_ioc(I_MD5, f.md5, tags=['dropped_file']) except: pass try: f.sha1 = file['@sha1'] analysis.add_ioc(I_SHA1, f.sha1, tags=['dropped_file']) except: pass try: f.sha256 = file['@sha256'] analysis.add_ioc(I_SHA256, f.sha256, tags=['dropped_file']) except: pass # Attempt to download any dropped files from WildFire and add them to the analysis if f.filename and f.md5 != 'N/A': job = {'apikey': self.api_key, 'hash': f.md5} url = 'https://wildfire.paloaltonetworks.com/publicapi/get/sample' try: r = requests.post(url, data=job, verify=False, proxies=self.proxies) except Exception as e: message = f'Error getting WildFire dropped file: {e.__class__} - {e}' logging.exception(message) raise ValueError(message) if r.status_code == 200: outpath = os.path.join(wildfire_dir, f.filename) with open(outpath, 'wb') as fp: fp.write(r.content) sample = analysis.add_observable(F_FILE, os.path.relpath(outpath, start=self.root.storage_dir)) if sample: sample.add_tag('dropped_file') sandbox_report.dropped_files.append(f) # Mutexes for process in processes_json: try: mutexes_json = process['mutex']['CreateMutex'] except: mutexes_json = [] for mutex_json in mutexes_json: if isinstance(mutex_json, dict): mutex_json = [mutex_json] for mutex in mutex_json: try: if mutex['@name'] != '<NULL>': sandbox_report.mutexes.add(mutex['@name']) except: logging.error(f'Error parsing WildFire mutex: {mutex}') # Registry for process in processes_json: try: registry_json = process['registry'] if process['registry'] else [] except: registry_json = [] for registry_action in registry_json: if isinstance(registry_json[registry_action], dict): registry_json[registry_action] = [registry_json[registry_action]] for registry_key in registry_json[registry_action]: try: sandbox_report.registry_keys.add(f'{registry_key["@key"]}\\{registry_key["@subkey"]}') except: logging.error(f'Error parsing WildFire registry key: {registry_key}') # Process tree URLs for process_url in sandbox_report.process_tree_urls: url = analysis.add_observable(F_URL, process_url) if url: url.add_tag('process_tree_url') analysis.iocs.add_url_iocs(process_url, tags=['process_tree_url']) # Walk the process tree that was chosen and add the processes to the parsed sandbox report sandbox_report.processes = walk_tree(process_json=process_tree_to_use) # Add the parsed report as a file observable parsed_report_path = os.path.join(wildfire_dir, 'parsed_report.json') with open(parsed_report_path, 'w') as f: json.dump(sandbox_report.json, f) analysis.add_observable(F_FILE, os.path.relpath(parsed_report_path, start=self.root.storage_dir)) # Add the dropped file paths as a file observable if sandbox_report.dropped_files: file_file_path = os.path.join(wildfire_dir, 'report.windows_filepath') with open(file_file_path, 'w') as file_file: file_file.writelines(sorted([f'{f.path}\n' for f in sandbox_report.dropped_files])) analysis.add_observable(F_FILE, os.path.relpath(file_file_path, start=self.root.storage_dir)) # Add the mutexes as a file observable if sandbox_report.mutexes: mutex_file_path = os.path.join(wildfire_dir, 'report.windows_mutex') with open(mutex_file_path, 'w') as mutex_file: mutex_file.writelines(sorted([f'{mutex}\n' for mutex in sandbox_report.mutexes])) analysis.add_observable(F_FILE, os.path.relpath(mutex_file_path, start=self.root.storage_dir)) # Add the registry keys as a file observable if sandbox_report.registry_keys: reg_file_path = os.path.join(wildfire_dir, 'report.windows_registry') with open(reg_file_path, 'w') as reg_file: reg_file.writelines(sorted([f'{reg}\n' for reg in sandbox_report.registry_keys])) analysis.add_observable(F_FILE, os.path.relpath(reg_file_path, start=self.root.storage_dir)) # Save the parsed report to the analysis details analysis.report = sandbox_report.json
import argparse import os import logging import sys import itertools from torchsummary import summary import torch from torch.utils.data import DataLoader, ConcatDataset from torch.optim.lr_scheduler import CosineAnnealingLR, MultiStepLR from vision.utils.misc import str2bool, Timer, freeze_net_layers, store_labels from vision.ssd.ssd import MatchPrior from vision.ssd.vgg_ssd import create_vgg_ssd from vision.ssd.mobilenetv1_ssd import create_mobilenetv1_ssd from vision.ssd.mobilenetv1_ssd_lite import create_mobilenetv1_ssd_lite from vision.ssd.mobilenet_v2_ssd_lite import create_mobilenetv2_ssd_lite from vision.ssd.mobilenetv3_ssd_lite import create_mobilenetv3_large_ssd_lite, create_mobilenetv3_small_ssd_lite from vision.ssd.squeezenet_ssd_lite import create_squeezenet_ssd_lite from vision.datasets.voc_dataset import VOCDataset from vision.datasets.open_images import OpenImagesDataset from vision.nn.multibox_loss import MultiboxLoss from vision.ssd.config import vgg_ssd_config from vision.ssd.config import mobilenetv1_ssd_config from vision.ssd.config import squeezenet_ssd_config from vision.ssd.data_preprocessing import TrainAugmentation, TestTransform parser = argparse.ArgumentParser( description='Single Shot MultiBox Detector Training With Pytorch') parser.add_argument("--dataset_type", default="voc", type=str, help='Specify dataset type. Currently support voc and open_images.') parser.add_argument('--datasets', nargs='+', help='Dataset directory path') parser.add_argument('--validation_dataset', help='Dataset directory path') parser.add_argument('--balance_data', action='store_true', help="Balance training data by down-sampling more frequent labels.") parser.add_argument('--net', default="vgg16-ssd", help="The network architecture, it can be mb1-ssd, mb1-ssd-lite, mb2-ssd-lite, mb3-large-ssd-lite, mb3-small-ssd-lite or vgg16-ssd.") parser.add_argument('--freeze_base_net', action='store_true', help="Freeze base net layers.") parser.add_argument('--freeze_net', action='store_true', help="Freeze all the layers except the prediction head.") parser.add_argument('--mb2_width_mult', default=1.0, type=float, help='Width Multiplifier for MobilenetV2') # Params for SGD parser.add_argument('--lr', '--learning-rate', default=1e-3, type=float, help='initial learning rate') parser.add_argument('--momentum', default=0.9, type=float, help='Momentum value for optim') parser.add_argument('--weight_decay', default=5e-4, type=float, help='Weight decay for SGD') parser.add_argument('--gamma', default=0.1, type=float, help='Gamma update for SGD') parser.add_argument('--base_net_lr', default=None, type=float, help='initial learning rate for base net.') parser.add_argument('--extra_layers_lr', default=None, type=float, help='initial learning rate for the layers not in base net and prediction heads.') # Params for loading pretrained basenet or checkpoints. parser.add_argument('--base_net', help='Pretrained base model') parser.add_argument('--pretrained_ssd', help='Pre-trained base model') parser.add_argument('--resume', default=None, type=str, help='Checkpoint state_dict file to resume training from') # Scheduler parser.add_argument('--scheduler', default="multi-step", type=str, help="Scheduler for SGD. It can one of multi-step and cosine") # Params for Multi-step Scheduler parser.add_argument('--milestones', default="80,100", type=str, help="milestones for MultiStepLR") # Params for Cosine Annealing parser.add_argument('--t_max', default=120, type=float, help='T_max value for Cosine Annealing Scheduler.') # Train params parser.add_argument('--batch_size', default=32, type=int, help='Batch size for training') parser.add_argument('--num_epochs', default=120, type=int, help='the number epochs') parser.add_argument('--num_workers', default=4, type=int, help='Number of workers used in dataloading') parser.add_argument('--validation_epochs', default=5, type=int, help='the number epochs') parser.add_argument('--debug_steps', default=100, type=int, help='Set the debug log output frequency.') parser.add_argument('--use_cuda', default=True, type=str2bool, help='Use CUDA to train model') parser.add_argument('--checkpoint_folder', default='models/', help='Directory for saving checkpoint models') logging.basicConfig(stream=sys.stdout, level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') args = parser.parse_args() DEVICE = torch.device("cuda:0" if torch.cuda.is_available() and args.use_cuda else "cpu") if args.use_cuda and torch.cuda.is_available(): torch.backends.cudnn.benchmark = True logging.info("Use Cuda.") def train(loader, net, criterion, optimizer, device, debug_steps=100, epoch=-1): net.train(True) running_loss = 0.0 running_regression_loss = 0.0 running_classification_loss = 0.0 for i, data in enumerate(loader): images, boxes, labels = data images = images.to(device) boxes = boxes.to(device) labels = labels.to(device) optimizer.zero_grad() confidence, locations = net(images) regression_loss, classification_loss = criterion(confidence, locations, labels, boxes) # TODO CHANGE BOXES loss = regression_loss + classification_loss loss.backward() optimizer.step() running_loss += loss.item() running_regression_loss += regression_loss.item() running_classification_loss += classification_loss.item() if i and i % debug_steps == 0: avg_loss = running_loss / debug_steps avg_reg_loss = running_regression_loss / debug_steps avg_clf_loss = running_classification_loss / debug_steps logging.info( f"Epoch: {epoch}, Step: {i}, " + f"Average Loss: {avg_loss:.4f}, " + f"Average Regression Loss {avg_reg_loss:.4f}, " + f"Average Classification Loss: {avg_clf_loss:.4f}" ) running_loss = 0.0 running_regression_loss = 0.0 running_classification_loss = 0.0 def test(loader, net, criterion, device): net.eval() running_loss = 0.0 running_regression_loss = 0.0 running_classification_loss = 0.0 num = 0 for _, data in enumerate(loader): images, boxes, labels = data images = images.to(device) boxes = boxes.to(device) labels = labels.to(device) num += 1 with torch.no_grad(): confidence, locations = net(images) regression_loss, classification_loss = criterion(confidence, locations, labels, boxes) loss = regression_loss + classification_loss running_loss += loss.item() running_regression_loss += regression_loss.item() running_classification_loss += classification_loss.item() return running_loss / num, running_regression_loss / num, running_classification_loss / num if __name__ == '__main__': timer = Timer() logging.info(args) if args.net == 'vgg16-ssd': create_net = create_vgg_ssd config = vgg_ssd_config elif args.net == 'mb1-ssd': create_net = create_mobilenetv1_ssd config = mobilenetv1_ssd_config elif args.net == 'mb1-ssd-lite': create_net = create_mobilenetv1_ssd_lite config = mobilenetv1_ssd_config elif args.net == 'sq-ssd-lite': create_net = create_squeezenet_ssd_lite config = squeezenet_ssd_config elif args.net == 'mb2-ssd-lite': create_net = lambda num: create_mobilenetv2_ssd_lite(num, width_mult=args.mb2_width_mult) config = mobilenetv1_ssd_config elif args.net == 'mb3-large-ssd-lite': create_net = lambda num: create_mobilenetv3_large_ssd_lite(num) config = mobilenetv1_ssd_config elif args.net == 'mb3-small-ssd-lite': create_net = lambda num: create_mobilenetv3_small_ssd_lite(num) config = mobilenetv1_ssd_config else: logging.fatal("The net type is wrong.") parser.print_help(sys.stderr) sys.exit(1) train_transform = TrainAugmentation(config.image_size, config.image_mean, config.image_std) target_transform = MatchPrior(config.priors, config.center_variance, config.size_variance, 0.5) test_transform = TestTransform(config.image_size, config.image_mean, config.image_std) logging.info("Prepare training datasets.") datasets = [] for dataset_path in args.datasets: if args.dataset_type == 'voc': dataset = VOCDataset(dataset_path, transform=train_transform, target_transform=target_transform) label_file = os.path.join(args.checkpoint_folder, "voc-model-labels.txt") store_labels(label_file, dataset.class_names) num_classes = len(dataset.class_names) elif args.dataset_type == 'open_images': dataset = OpenImagesDataset(dataset_path, transform=train_transform, target_transform=target_transform, dataset_type="train", balance_data=args.balance_data) label_file = os.path.join(args.checkpoint_folder, "open-images-model-labels.txt") store_labels(label_file, dataset.class_names) logging.info(dataset) num_classes = len(dataset.class_names) else: raise ValueError(f"Dataset type {args.dataset_type} is not supported.") datasets.append(dataset) logging.info(f"Stored labels into file {label_file}.") train_dataset = ConcatDataset(datasets) logging.info("Train dataset size: {}".format(len(train_dataset))) train_loader = DataLoader(train_dataset, args.batch_size, num_workers=args.num_workers, shuffle=True) logging.info("Prepare Validation datasets.") if args.dataset_type == "voc": val_dataset = VOCDataset(args.validation_dataset, transform=test_transform, target_transform=target_transform, is_test=True) elif args.dataset_type == 'open_images': val_dataset = OpenImagesDataset(dataset_path, transform=test_transform, target_transform=target_transform, dataset_type="test") logging.info(val_dataset) logging.info("validation dataset size: {}".format(len(val_dataset))) val_loader = DataLoader(val_dataset, args.batch_size, num_workers=args.num_workers, shuffle=False) logging.info("Build network.") net = create_net(num_classes) summary(net.to("cuda"),(3,config.image_size,config.image_size),device='cuda') min_loss = -10000.0 last_epoch = -1 base_net_lr = args.base_net_lr if args.base_net_lr is not None else args.lr extra_layers_lr = args.extra_layers_lr if args.extra_layers_lr is not None else args.lr if args.freeze_base_net: logging.info("Freeze base net.") freeze_net_layers(net.base_net) params = itertools.chain(net.source_layer_add_ons.parameters(), net.extras.parameters(), net.regression_headers.parameters(), net.classification_headers.parameters()) params = [ {'params': itertools.chain( net.source_layer_add_ons.parameters(), net.extras.parameters() ), 'lr': extra_layers_lr}, {'params': itertools.chain( net.regression_headers.parameters(), net.classification_headers.parameters() )} ] elif args.freeze_net: freeze_net_layers(net.base_net) freeze_net_layers(net.source_layer_add_ons) freeze_net_layers(net.extras) params = itertools.chain(net.regression_headers.parameters(), net.classification_headers.parameters()) logging.info("Freeze all the layers except prediction heads.") else: params = [ {'params': net.base_net.parameters(), 'lr': base_net_lr}, {'params': itertools.chain( net.source_layer_add_ons.parameters(), net.extras.parameters() ), 'lr': extra_layers_lr}, {'params': itertools.chain( net.regression_headers.parameters(), net.classification_headers.parameters() )} ] timer.start("Load Model") if args.resume: logging.info(f"Resume from the model {args.resume}") net.load(args.resume) elif args.base_net: logging.info(f"Init from base net {args.base_net}") net.init_from_base_net(args.base_net) elif args.pretrained_ssd: logging.info(f"Init from pretrained ssd {args.pretrained_ssd}") net.init_from_pretrained_ssd(args.pretrained_ssd) logging.info(f'Took {timer.end('Load Model'):.2f} seconds to load the model.') net.to(DEVICE) criterion = MultiboxLoss(config.priors, iou_threshold=0.5, neg_pos_ratio=3, center_variance=0.1, size_variance=0.2, device=DEVICE) optimizer = torch.optim.SGD(params, lr=args.lr, momentum=args.momentum, weight_decay=args.weight_decay) logging.info(f"Learning rate: {args.lr}, Base net learning rate: {base_net_lr}, " + f"Extra Layers learning rate: {extra_layers_lr}.") if args.scheduler == 'multi-step': logging.info("Uses MultiStepLR scheduler.") milestones = [int(v.strip()) for v in args.milestones.split(",")] scheduler = MultiStepLR(optimizer, milestones=milestones, gamma=0.1, last_epoch=last_epoch) elif args.scheduler == 'cosine': logging.info("Uses CosineAnnealingLR scheduler.") scheduler = CosineAnnealingLR(optimizer, args.t_max, last_epoch=last_epoch) else: logging.fatal(f"Unsupported Scheduler: {args.scheduler}.") parser.print_help(sys.stderr) sys.exit(1) logging.info(f"Start training from epoch {last_epoch + 1}.") for epoch in range(last_epoch + 1, args.num_epochs): scheduler.step() train(train_loader, net, criterion, optimizer, device=DEVICE, debug_steps=args.debug_steps, epoch=epoch) if epoch % args.validation_epochs == 0 or epoch == args.num_epochs - 1: val_loss, val_regression_loss, val_classification_loss = test(val_loader, net, criterion, DEVICE) logging.info( f"Epoch: {epoch}, " + f"Validation Loss: {val_loss:.4f}, " + f"Validation Regression Loss {val_regression_loss:.4f}, " + f"Validation Classification Loss: {val_classification_loss:.4f}" ) model_path = os.path.join(args.checkpoint_folder, f"{args.net}-Epoch-{epoch}-Loss-{val_loss}.pth") net.save(model_path) logging.info(f"Saved model {model_path}")
import argparse import os import logging import sys import itertools from torchsummary import summary import torch from torch.utils.data import DataLoader, ConcatDataset from torch.optim.lr_scheduler import CosineAnnealingLR, MultiStepLR from vision.utils.misc import str2bool, Timer, freeze_net_layers, store_labels from vision.ssd.ssd import MatchPrior from vision.ssd.vgg_ssd import create_vgg_ssd from vision.ssd.mobilenetv1_ssd import create_mobilenetv1_ssd from vision.ssd.mobilenetv1_ssd_lite import create_mobilenetv1_ssd_lite from vision.ssd.mobilenet_v2_ssd_lite import create_mobilenetv2_ssd_lite from vision.ssd.mobilenetv3_ssd_lite import create_mobilenetv3_large_ssd_lite, create_mobilenetv3_small_ssd_lite from vision.ssd.squeezenet_ssd_lite import create_squeezenet_ssd_lite from vision.datasets.voc_dataset import VOCDataset from vision.datasets.open_images import OpenImagesDataset from vision.nn.multibox_loss import MultiboxLoss from vision.ssd.config import vgg_ssd_config from vision.ssd.config import mobilenetv1_ssd_config from vision.ssd.config import squeezenet_ssd_config from vision.ssd.data_preprocessing import TrainAugmentation, TestTransform parser = argparse.ArgumentParser( description='Single Shot MultiBox Detector Training With Pytorch') parser.add_argument("--dataset_type", default="voc", type=str, help='Specify dataset type. Currently support voc and open_images.') parser.add_argument('--datasets', nargs='+', help='Dataset directory path') parser.add_argument('--validation_dataset', help='Dataset directory path') parser.add_argument('--balance_data', action='store_true', help="Balance training data by down-sampling more frequent labels.") parser.add_argument('--net', default="vgg16-ssd", help="The network architecture, it can be mb1-ssd, mb1-ssd-lite, mb2-ssd-lite, mb3-large-ssd-lite, mb3-small-ssd-lite or vgg16-ssd.") parser.add_argument('--freeze_base_net', action='store_true', help="Freeze base net layers.") parser.add_argument('--freeze_net', action='store_true', help="Freeze all the layers except the prediction head.") parser.add_argument('--mb2_width_mult', default=1.0, type=float, help='Width Multiplifier for MobilenetV2') # Params for SGD parser.add_argument('--lr', '--learning-rate', default=1e-3, type=float, help='initial learning rate') parser.add_argument('--momentum', default=0.9, type=float, help='Momentum value for optim') parser.add_argument('--weight_decay', default=5e-4, type=float, help='Weight decay for SGD') parser.add_argument('--gamma', default=0.1, type=float, help='Gamma update for SGD') parser.add_argument('--base_net_lr', default=None, type=float, help='initial learning rate for base net.') parser.add_argument('--extra_layers_lr', default=None, type=float, help='initial learning rate for the layers not in base net and prediction heads.') # Params for loading pretrained basenet or checkpoints. parser.add_argument('--base_net', help='Pretrained base model') parser.add_argument('--pretrained_ssd', help='Pre-trained base model') parser.add_argument('--resume', default=None, type=str, help='Checkpoint state_dict file to resume training from') # Scheduler parser.add_argument('--scheduler', default="multi-step", type=str, help="Scheduler for SGD. It can one of multi-step and cosine") # Params for Multi-step Scheduler parser.add_argument('--milestones', default="80,100", type=str, help="milestones for MultiStepLR") # Params for Cosine Annealing parser.add_argument('--t_max', default=120, type=float, help='T_max value for Cosine Annealing Scheduler.') # Train params parser.add_argument('--batch_size', default=32, type=int, help='Batch size for training') parser.add_argument('--num_epochs', default=120, type=int, help='the number epochs') parser.add_argument('--num_workers', default=4, type=int, help='Number of workers used in dataloading') parser.add_argument('--validation_epochs', default=5, type=int, help='the number epochs') parser.add_argument('--debug_steps', default=100, type=int, help='Set the debug log output frequency.') parser.add_argument('--use_cuda', default=True, type=str2bool, help='Use CUDA to train model') parser.add_argument('--checkpoint_folder', default='models/', help='Directory for saving checkpoint models') logging.basicConfig(stream=sys.stdout, level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') args = parser.parse_args() DEVICE = torch.device("cuda:0" if torch.cuda.is_available() and args.use_cuda else "cpu") if args.use_cuda and torch.cuda.is_available(): torch.backends.cudnn.benchmark = True logging.info("Use Cuda.") def train(loader, net, criterion, optimizer, device, debug_steps=100, epoch=-1): net.train(True) running_loss = 0.0 running_regression_loss = 0.0 running_classification_loss = 0.0 for i, data in enumerate(loader): images, boxes, labels = data images = images.to(device) boxes = boxes.to(device) labels = labels.to(device) optimizer.zero_grad() confidence, locations = net(images) regression_loss, classification_loss = criterion(confidence, locations, labels, boxes) # TODO CHANGE BOXES loss = regression_loss + classification_loss loss.backward() optimizer.step() running_loss += loss.item() running_regression_loss += regression_loss.item() running_classification_loss += classification_loss.item() if i and i % debug_steps == 0: avg_loss = running_loss / debug_steps avg_reg_loss = running_regression_loss / debug_steps avg_clf_loss = running_classification_loss / debug_steps logging.info( f"Epoch: {epoch}, Step: {i}, " + f"Average Loss: {avg_loss:.4f}, " + f"Average Regression Loss {avg_reg_loss:.4f}, " + f"Average Classification Loss: {avg_clf_loss:.4f}" ) running_loss = 0.0 running_regression_loss = 0.0 running_classification_loss = 0.0 def test(loader, net, criterion, device): net.eval() running_loss = 0.0 running_regression_loss = 0.0 running_classification_loss = 0.0 num = 0 for _, data in enumerate(loader): images, boxes, labels = data images = images.to(device) boxes = boxes.to(device) labels = labels.to(device) num += 1 with torch.no_grad(): confidence, locations = net(images) regression_loss, classification_loss = criterion(confidence, locations, labels, boxes) loss = regression_loss + classification_loss running_loss += loss.item() running_regression_loss += regression_loss.item() running_classification_loss += classification_loss.item() return running_loss / num, running_regression_loss / num, running_classification_loss / num if __name__ == '__main__': timer = Timer() logging.info(args) if args.net == 'vgg16-ssd': create_net = create_vgg_ssd config = vgg_ssd_config elif args.net == 'mb1-ssd': create_net = create_mobilenetv1_ssd config = mobilenetv1_ssd_config elif args.net == 'mb1-ssd-lite': create_net = create_mobilenetv1_ssd_lite config = mobilenetv1_ssd_config elif args.net == 'sq-ssd-lite': create_net = create_squeezenet_ssd_lite config = squeezenet_ssd_config elif args.net == 'mb2-ssd-lite': create_net = lambda num: create_mobilenetv2_ssd_lite(num, width_mult=args.mb2_width_mult) config = mobilenetv1_ssd_config elif args.net == 'mb3-large-ssd-lite': create_net = lambda num: create_mobilenetv3_large_ssd_lite(num) config = mobilenetv1_ssd_config elif args.net == 'mb3-small-ssd-lite': create_net = lambda num: create_mobilenetv3_small_ssd_lite(num) config = mobilenetv1_ssd_config else: logging.fatal("The net type is wrong.") parser.print_help(sys.stderr) sys.exit(1) train_transform = TrainAugmentation(config.image_size, config.image_mean, config.image_std) target_transform = MatchPrior(config.priors, config.center_variance, config.size_variance, 0.5) test_transform = TestTransform(config.image_size, config.image_mean, config.image_std) logging.info("Prepare training datasets.") datasets = [] for dataset_path in args.datasets: if args.dataset_type == 'voc': dataset = VOCDataset(dataset_path, transform=train_transform, target_transform=target_transform) label_file = os.path.join(args.checkpoint_folder, "voc-model-labels.txt") store_labels(label_file, dataset.class_names) num_classes = len(dataset.class_names) elif args.dataset_type == 'open_images': dataset = OpenImagesDataset(dataset_path, transform=train_transform, target_transform=target_transform, dataset_type="train", balance_data=args.balance_data) label_file = os.path.join(args.checkpoint_folder, "open-images-model-labels.txt") store_labels(label_file, dataset.class_names) logging.info(dataset) num_classes = len(dataset.class_names) else: raise ValueError(f"Dataset type {args.dataset_type} is not supported.") datasets.append(dataset) logging.info(f"Stored labels into file {label_file}.") train_dataset = ConcatDataset(datasets) logging.info("Train dataset size: {}".format(len(train_dataset))) train_loader = DataLoader(train_dataset, args.batch_size, num_workers=args.num_workers, shuffle=True) logging.info("Prepare Validation datasets.") if args.dataset_type == "voc": val_dataset = VOCDataset(args.validation_dataset, transform=test_transform, target_transform=target_transform, is_test=True) elif args.dataset_type == 'open_images': val_dataset = OpenImagesDataset(dataset_path, transform=test_transform, target_transform=target_transform, dataset_type="test") logging.info(val_dataset) logging.info("validation dataset size: {}".format(len(val_dataset))) val_loader = DataLoader(val_dataset, args.batch_size, num_workers=args.num_workers, shuffle=False) logging.info("Build network.") net = create_net(num_classes) summary(net.to("cuda"),(3,config.image_size,config.image_size),device='cuda') min_loss = -10000.0 last_epoch = -1 base_net_lr = args.base_net_lr if args.base_net_lr is not None else args.lr extra_layers_lr = args.extra_layers_lr if args.extra_layers_lr is not None else args.lr if args.freeze_base_net: logging.info("Freeze base net.") freeze_net_layers(net.base_net) params = itertools.chain(net.source_layer_add_ons.parameters(), net.extras.parameters(), net.regression_headers.parameters(), net.classification_headers.parameters()) params = [ {'params': itertools.chain( net.source_layer_add_ons.parameters(), net.extras.parameters() ), 'lr': extra_layers_lr}, {'params': itertools.chain( net.regression_headers.parameters(), net.classification_headers.parameters() )} ] elif args.freeze_net: freeze_net_layers(net.base_net) freeze_net_layers(net.source_layer_add_ons) freeze_net_layers(net.extras) params = itertools.chain(net.regression_headers.parameters(), net.classification_headers.parameters()) logging.info("Freeze all the layers except prediction heads.") else: params = [ {'params': net.base_net.parameters(), 'lr': base_net_lr}, {'params': itertools.chain( net.source_layer_add_ons.parameters(), net.extras.parameters() ), 'lr': extra_layers_lr}, {'params': itertools.chain( net.regression_headers.parameters(), net.classification_headers.parameters() )} ] timer.start("Load Model") if args.resume: logging.info(f"Resume from the model {args.resume}") net.load(args.resume) elif args.base_net: logging.info(f"Init from base net {args.base_net}") net.init_from_base_net(args.base_net) elif args.pretrained_ssd: logging.info(f"Init from pretrained ssd {args.pretrained_ssd}") net.init_from_pretrained_ssd(args.pretrained_ssd) logging.info(f'Took {timer.end("Load Model"):.2f} seconds to load the model.') net.to(DEVICE) criterion = MultiboxLoss(config.priors, iou_threshold=0.5, neg_pos_ratio=3, center_variance=0.1, size_variance=0.2, device=DEVICE) optimizer = torch.optim.SGD(params, lr=args.lr, momentum=args.momentum, weight_decay=args.weight_decay) logging.info(f"Learning rate: {args.lr}, Base net learning rate: {base_net_lr}, " + f"Extra Layers learning rate: {extra_layers_lr}.") if args.scheduler == 'multi-step': logging.info("Uses MultiStepLR scheduler.") milestones = [int(v.strip()) for v in args.milestones.split(",")] scheduler = MultiStepLR(optimizer, milestones=milestones, gamma=0.1, last_epoch=last_epoch) elif args.scheduler == 'cosine': logging.info("Uses CosineAnnealingLR scheduler.") scheduler = CosineAnnealingLR(optimizer, args.t_max, last_epoch=last_epoch) else: logging.fatal(f"Unsupported Scheduler: {args.scheduler}.") parser.print_help(sys.stderr) sys.exit(1) logging.info(f"Start training from epoch {last_epoch + 1}.") for epoch in range(last_epoch + 1, args.num_epochs): scheduler.step() train(train_loader, net, criterion, optimizer, device=DEVICE, debug_steps=args.debug_steps, epoch=epoch) if epoch % args.validation_epochs == 0 or epoch == args.num_epochs - 1: val_loss, val_regression_loss, val_classification_loss = test(val_loader, net, criterion, DEVICE) logging.info( f"Epoch: {epoch}, " + f"Validation Loss: {val_loss:.4f}, " + f"Validation Regression Loss {val_regression_loss:.4f}, " + f"Validation Classification Loss: {val_classification_loss:.4f}" ) model_path = os.path.join(args.checkpoint_folder, f"{args.net}-Epoch-{epoch}-Loss-{val_loss}.pth") net.save(model_path) logging.info(f"Saved model {model_path}")
import os import selenium import requests from selenium import webdriver from optparse import OptionParser from selenium.webdriver.common.keys import Keys from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.firefox.options import Options from selenium.webdriver import ActionChains import time import sys from html.parser import HTMLParser import json from SocialMedia.scrapefb import fb from SocialMedia.scrapetwitter import twit from SocialMedia.scrapelinkedin import linked from Info.Spamcalls import risk from Info.fouroneone import fouroneone from Info.google import trace from Info.googlemaps import maps from Style.banner import banner api_key = '86191f43c035c6da6744113acdf7f9ea' n = [] class colors: yellow = '\033[1;33m' green = '\033[1;32m' red = '\033[1;31m' magenta = '\033[1;35m' darkwhite = '\033[0;37m' class MyHTMLParser(HTMLParser): def __init__(self): HTMLParser.__init__(self) self.inLink = False self.dataArray = [] self.countLanguages = 0 self.lasttag = None self.lastname = None self.lastvalue = None def handle_starttag(self, tag, attrs): self.inLink = False if tag == 'h1': for name, value in attrs: if name == 'class' and value == 'flex-1 text-xl text-fontPrimaryColor leading-tight': self.countLanguages += 1 self.inLink = True self.lasttag = tag def handle_endtag(self, tag): if tag == "h1": self.inlink = False def handle_data(self, data): if self.lasttag == 'h1' and self.inLink and data.strip(): print(colors.green + "Name : " + data + colors.green) class HTML(HTMLParser): def __init__(self): HTMLParser.__init__(self) self.inLink = False self.dataArray = [] self.countLanguages = 0 self.lasttag = None self.lastname = None self.lastvalue = None def handle_starttag(self, tag, attrs): self.inLink = False if tag == 'div': for name, value in attrs: if name == 'class' and value == 'flex-1 h-16 leading-16 border-b border-borderColor truncate pr-4': self.countLanguages += 1 self.inLink = True self.lasttag = tag def handle_endtag(self, tag): if tag == "div": self.inlink = False def handle_data(self, data): if self.lasttag == 'div' and self.inLink and data.strip(): if "@" in data: print(colors.magenta + "Email : " + data + colors.magenta) else: pass banner() query = input(colors.green + "\n└──=>Enter the phone number (along with prefix) :") line_1 = "\nRunning Scan..." for x in line_1: print(x, end='') sys.stdout.flush() time.sleep(0.1) request = requests.get(f'http://apilayer.net/api/validate?access_key={api_key}&number={query}') answer = json.loads(request.text) optionss = webdriver.FirefoxOptions() optionss.headless = True optionss.add_argument("--disable-popup-blocking") optionss.add_argument("--disable-extensions") browser = webdriver.Firefox(options=optionss) browser.get(f"https://www.truecaller.com/search/{str(answer["country_code"]).lower()}/{query.replace("+91", "")}") parse = HTML() parser = MyHTMLParser() if browser.current_url != 'https://www.truecaller.com/auth/sign-in': print(colors.red+"\nInfo Scan\n"+colors.red) print(colors.red+"------------------------"+colors.red) parser.feed(browser.page_source) print(colors.green+f''' Valid : {str(answer['valid'])} Number: {str(answer['number'])} Local Format: {str(answer['local_format'])} International Format: {str(answer['international_format'])} Country Prefix: {str(answer['country_prefix'])} Country Code: {str(answer['country_code'])} Country Name: {str(answer['country_name'])} Location: {str(answer['location'])} Maps : {maps(str(answer['location']))} Carrier: {str(answer['carrier'])} Line Type: {str(answer['line_type'])}'''+colors.green) else: actionchains = ActionChains(browser) click = browser.find_element_by_xpath('/html/body/div/main/div/a[2]') actionchains.move_to_element(click).click().perform() time.sleep(20) email = browser.find_element_by_css_selector('#i0116') email.send_keys('anonsurf69@outlook.com', Keys.ENTER) time.sleep(20) password = browser.find_element_by_css_selector('#i0118') password.send_keys('Hsvmq2jvgz', Keys.ENTER) time.sleep(30) print(colors.red+"\nInfo Scan\n"+colors.red) print(colors.red+"------------------------"+colors.red) parser.feed(browser.page_source) print(colors.green+f''' Valid : {str(answer['valid'])} Number: {str(answer['number'])} Local Format: {str(answer['local_format'])} International Format: {str(answer['international_format'])} Country Prefix: {str(answer['country_prefix'])} Country Code: {str(answer['country_code'])} Country Name: {str(answer['country_name'])} Location: {str(answer['location'])} Maps : {maps(str(answer['location']))} Carrier: {str(answer['carrier'])} Line Type: {str(answer['line_type'])}'''+colors.green) print("") print(colors.magenta + "[*] Scanning Social Media Footprints" + colors.magenta) print("-------------------------------------") print("") print(fb(query)) print("") print(twit(query)) print("") print(linked(query)) print("") parse.feed(browser.page_source) print("") print(colors.darkwhite + "Spamcalls.net Search" + colors.darkwhite) print("------------") print("") print(risk(query)) print(colors.darkwhite + "\n411.com search" + colors.darkwhite) print("------------") print("") print(fouroneone(query)) print(colors.red + "\nGoogle Exception Results") print(colors.red + "-------------") print("") print(trace(query)) print("") browser.quit()
import os import selenium import requests from selenium import webdriver from optparse import OptionParser from selenium.webdriver.common.keys import Keys from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.firefox.options import Options from selenium.webdriver import ActionChains import time import sys from html.parser import HTMLParser import json from SocialMedia.scrapefb import fb from SocialMedia.scrapetwitter import twit from SocialMedia.scrapelinkedin import linked from Info.Spamcalls import risk from Info.fouroneone import fouroneone from Info.google import trace from Info.googlemaps import maps from Style.banner import banner api_key = '86191f43c035c6da6744113acdf7f9ea' n = [] class colors: yellow = '\033[1;33m' green = '\033[1;32m' red = '\033[1;31m' magenta = '\033[1;35m' darkwhite = '\033[0;37m' class MyHTMLParser(HTMLParser): def __init__(self): HTMLParser.__init__(self) self.inLink = False self.dataArray = [] self.countLanguages = 0 self.lasttag = None self.lastname = None self.lastvalue = None def handle_starttag(self, tag, attrs): self.inLink = False if tag == 'h1': for name, value in attrs: if name == 'class' and value == 'flex-1 text-xl text-fontPrimaryColor leading-tight': self.countLanguages += 1 self.inLink = True self.lasttag = tag def handle_endtag(self, tag): if tag == "h1": self.inlink = False def handle_data(self, data): if self.lasttag == 'h1' and self.inLink and data.strip(): print(colors.green + "Name : " + data + colors.green) class HTML(HTMLParser): def __init__(self): HTMLParser.__init__(self) self.inLink = False self.dataArray = [] self.countLanguages = 0 self.lasttag = None self.lastname = None self.lastvalue = None def handle_starttag(self, tag, attrs): self.inLink = False if tag == 'div': for name, value in attrs: if name == 'class' and value == 'flex-1 h-16 leading-16 border-b border-borderColor truncate pr-4': self.countLanguages += 1 self.inLink = True self.lasttag = tag def handle_endtag(self, tag): if tag == "div": self.inlink = False def handle_data(self, data): if self.lasttag == 'div' and self.inLink and data.strip(): if "@" in data: print(colors.magenta + "Email : " + data + colors.magenta) else: pass banner() query = input(colors.green + "\n└──=>Enter the phone number (along with prefix) :") line_1 = "\nRunning Scan..." for x in line_1: print(x, end='') sys.stdout.flush() time.sleep(0.1) request = requests.get(f'http://apilayer.net/api/validate?access_key={api_key}&number={query}') answer = json.loads(request.text) optionss = webdriver.FirefoxOptions() optionss.headless = True optionss.add_argument("--disable-popup-blocking") optionss.add_argument("--disable-extensions") browser = webdriver.Firefox(options=optionss) browser.get(f"https://www.truecaller.com/search/{str(answer['country_code']).lower()}/{query.replace('+91', '')}") parse = HTML() parser = MyHTMLParser() if browser.current_url != 'https://www.truecaller.com/auth/sign-in': print(colors.red+"\nInfo Scan\n"+colors.red) print(colors.red+"------------------------"+colors.red) parser.feed(browser.page_source) print(colors.green+f''' Valid : {str(answer['valid'])} Number: {str(answer['number'])} Local Format: {str(answer['local_format'])} International Format: {str(answer['international_format'])} Country Prefix: {str(answer['country_prefix'])} Country Code: {str(answer['country_code'])} Country Name: {str(answer['country_name'])} Location: {str(answer['location'])} Maps : {maps(str(answer['location']))} Carrier: {str(answer['carrier'])} Line Type: {str(answer['line_type'])}'''+colors.green) else: actionchains = ActionChains(browser) click = browser.find_element_by_xpath('/html/body/div/main/div/a[2]') actionchains.move_to_element(click).click().perform() time.sleep(20) email = browser.find_element_by_css_selector('#i0116') email.send_keys('anonsurf69@outlook.com', Keys.ENTER) time.sleep(20) password = browser.find_element_by_css_selector('#i0118') password.send_keys('Hsvmq2jvgz', Keys.ENTER) time.sleep(30) print(colors.red+"\nInfo Scan\n"+colors.red) print(colors.red+"------------------------"+colors.red) parser.feed(browser.page_source) print(colors.green+f''' Valid : {str(answer['valid'])} Number: {str(answer['number'])} Local Format: {str(answer['local_format'])} International Format: {str(answer['international_format'])} Country Prefix: {str(answer['country_prefix'])} Country Code: {str(answer['country_code'])} Country Name: {str(answer['country_name'])} Location: {str(answer['location'])} Maps : {maps(str(answer['location']))} Carrier: {str(answer['carrier'])} Line Type: {str(answer['line_type'])}'''+colors.green) print("") print(colors.magenta + "[*] Scanning Social Media Footprints" + colors.magenta) print("-------------------------------------") print("") print(fb(query)) print("") print(twit(query)) print("") print(linked(query)) print("") parse.feed(browser.page_source) print("") print(colors.darkwhite + "Spamcalls.net Search" + colors.darkwhite) print("------------") print("") print(risk(query)) print(colors.darkwhite + "\n411.com search" + colors.darkwhite) print("------------") print("") print(fouroneone(query)) print(colors.red + "\nGoogle Exception Results") print(colors.red + "-------------") print("") print(trace(query)) print("") browser.quit()
# This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from collections import namedtuple from io import BytesIO from operator import attrgetter, itemgetter from dateutil.relativedelta import relativedelta from flask import flash, jsonify, redirect, render_template, request, session from markupsafe import Markup, escape from marshmallow import fields from marshmallow_enum import EnumField from PIL import Image from sqlalchemy.orm import joinedload, load_only, subqueryload from sqlalchemy.orm.exc import StaleDataError from webargs import validate from werkzeug.exceptions import BadRequest, Forbidden, NotFound from indico.core import signals from indico.core.auth import multipass from indico.core.cache import make_scoped_cache from indico.core.db import db from indico.core.db.sqlalchemy.util.queries import get_n_matching from indico.core.errors import UserValueError from indico.core.marshmallow import mm from indico.core.notifications import make_email, send_email from indico.modules.admin import RHAdminBase from indico.modules.auth import Identity from indico.modules.auth.models.registration_requests import RegistrationRequest from indico.modules.auth.util import register_user from indico.modules.categories import Category from indico.modules.events import Event from indico.modules.events.util import serialize_event_for_ical from indico.modules.users import User, logger, user_management_settings from indico.modules.users.forms import (AdminAccountRegistrationForm, AdminsForm, AdminUserSettingsForm, MergeForm, SearchForm, UserDetailsForm, UserEmailsForm, UserPreferencesForm) from indico.modules.users.models.emails import UserEmail from indico.modules.users.models.users import ProfilePictureSource from indico.modules.users.operations import create_user from indico.modules.users.schemas import BasicCategorySchema from indico.modules.users.util import (get_avatar_url_from_name, get_gravatar_for_user, get_linked_events, get_related_categories, get_suggested_categories, merge_users, search_users, send_avatar, serialize_user, set_user_avatar) from indico.modules.users.views import WPUser, WPUserDashboard, WPUserFavorites, WPUserProfilePic, WPUsersAdmin from indico.util.date_time import now_utc from indico.util.i18n import _ from indico.util.images import square from indico.util.marshmallow import HumanizedDate, Principal, validate_with_message from indico.util.signals import values_from_signal from indico.util.string import make_unique_token from indico.web.args import use_kwargs from indico.web.flask.templating import get_template_module from indico.web.flask.util import send_file, url_for from indico.web.forms.base import FormDefaults from indico.web.http_api.metadata import Serializer from indico.web.rh import RH, RHProtected, allow_signed_url from indico.web.util import is_legacy_signed_url_valid, jsonify_data, jsonify_form, jsonify_template IDENTITY_ATTRIBUTES = {'first_name', 'last_name', 'email', 'affiliation', 'full_name'} UserEntry = namedtuple('UserEntry', IDENTITY_ATTRIBUTES | {'profile_url', 'avatar_url', 'user'}) def get_events_in_categories(category_ids, user, limit=10): """Get all the user-accessible events in a given set of categories.""" tz = session.tzinfo today = now_utc(False).astimezone(tz).date() query = (Event.query .filter(~Event.is_deleted, Event.category_chain_overlaps(category_ids), Event.start_dt.astimezone(session.tzinfo) >= today) .options(joinedload('category').load_only('id', 'title'), joinedload('series'), joinedload('label'), subqueryload('acl_entries'), load_only('id', 'category_id', 'start_dt', 'end_dt', 'title', 'access_key', 'protection_mode', 'series_id', 'series_pos', 'series_count', 'label_id', 'label_message')) .order_by(Event.start_dt, Event.id)) return get_n_matching(query, limit, lambda x: x.can_access(user)) class RHUserBase(RHProtected): flash_user_status = True allow_system_user = False def _process_args(self): if not session.user: return self.user = session.user if 'user_id' in request.view_args: self.user = User.get(request.view_args['user_id']) if self.user is None: raise NotFound('This user does not exist') elif request.method == 'GET' and not request.is_xhr and self.flash_user_status: # Show messages about the user's status if it's a simple GET request if self.user.is_deleted: if self.user.merged_into_id is not None: msg = _('This user has been merged into <a href="{url}">another user</a>.') flash(Markup(msg).format(url=url_for(request.endpoint, self.user.merged_into_user)), 'warning') else: flash(_('This user is marked as deleted.'), 'warning') if self.user.is_pending: flash(_('This user is marked as pending, i.e. it has been attached to something but never ' 'logged in.'), 'warning') if not self.allow_system_user and self.user.is_system: return redirect(url_for('users.user_profile')) def _check_access(self): RHProtected._check_access(self) if not self.user.can_be_modified(session.user): raise Forbidden('You cannot modify this user.') class RHUserDashboard(RHUserBase): management_roles = {'conference_creator', 'conference_chair', 'conference_manager', 'session_manager', 'session_coordinator', 'contribution_manager'} reviewer_roles = {'paper_manager', 'paper_judge', 'paper_content_reviewer', 'paper_layout_reviewer', 'contribution_referee', 'contribution_editor', 'contribution_reviewer', 'abstract_reviewer', 'track_convener'} attendance_roles = {'contributor', 'contribution_submission', 'abstract_submitter', 'abstract_person', 'registration_registrant', 'survey_submitter', 'lecture_speaker'} def _process(self): self.user.settings.set('suggest_categories', True) categories = get_related_categories(self.user) categories_events = [] if categories: category_ids = {c['categ'].id for c in categories.values()} categories_events = get_events_in_categories(category_ids, self.user) from_dt = now_utc(False) - relativedelta(weeks=1, hour=0, minute=0, second=0) linked_events = [(event, {'management': bool(roles & self.management_roles), 'reviewing': bool(roles & self.reviewer_roles), 'attendance': bool(roles & self.attendance_roles)}) for event, roles in get_linked_events(self.user, from_dt, 10).items()] return WPUserDashboard.render_template('dashboard.html', 'dashboard', user=self.user, categories=categories, categories_events=categories_events, suggested_categories=get_suggested_categories(self.user), linked_events=linked_events) @allow_signed_url class RHExportDashboardICS(RHProtected): def _get_user(self): return session.user @use_kwargs({ 'from_': HumanizedDate(data_key='from', missing=lambda: now_utc(False) - relativedelta(weeks=1)), 'include': fields.List(fields.Str(), missing={'linked', 'categories'}), 'limit': fields.Integer(missing=100, validate=lambda v: 0 < v <= 500) }, location='query') def _process(self, from_, include, limit): user = self._get_user() all_events = set() if 'linked' in include: all_events |= set(get_linked_events( user, from_, limit=limit, load_also=('description', 'own_room_id', 'own_venue_id', 'own_room_name', 'own_venue_name') )) if 'categories' in include and (categories := get_related_categories(user)): category_ids = {c['categ'].id for c in categories.values()} all_events |= set(get_events_in_categories(category_ids, user, limit=limit)) all_events = sorted(all_events, key=lambda e: (e.start_dt, e.id))[:limit] response = {'results': [serialize_event_for_ical(event, 'events') for event in all_events]} serializer = Serializer.create('ics') return send_file('event.ics', BytesIO(serializer(response)), 'text/calendar') class RHExportDashboardICSLegacy(RHExportDashboardICS): def _get_user(self): user = User.get_or_404(request.view_args['user_id'], is_deleted=False) if not is_legacy_signed_url_valid(user, request.full_path): raise BadRequest('Invalid signature') if user.is_blocked: raise BadRequest('User blocked') return user def _check_access(self): # disable the usual RHProtected access check; `_get_user` does it all pass class RHPersonalData(RHUserBase): allow_system_user = True def _process(self): form = UserDetailsForm(obj=FormDefaults(self.user, skip_attrs={'title'}, title=self.user._title), synced_fields=self.user.synced_fields, synced_values=self.user.synced_values) if form.validate_on_submit(): self.user.synced_fields = form.synced_fields form.populate_obj(self.user, skip=self.user.synced_fields) self.user.synchronize_data(refresh=True) flash(_('Your personal data was successfully updated.'), 'success') return redirect(url_for('.user_profile')) return WPUser.render_template('personal_data.html', 'personal_data', user=self.user, form=form) class RHProfilePicturePage(RHUserBase): """Page to manage the profile picture.""" def _process(self): return WPUserProfilePic.render_template('profile_picture.html', 'profile_picture', user=self.user, source=self.user.picture_source.name) class RHProfilePicturePreview(RHUserBase): """Preview the different profile pictures. This always uses a fresh picture without any caching. """ @use_kwargs({'source': EnumField(ProfilePictureSource)}, location='view_args') def _process(self, source): if source == ProfilePictureSource.standard: first_name = self.user.first_name[0].upper() if self.user.first_name else '' avatar = render_template('users/avatar.svg', bg_color=self.user.avatar_bg_color, text=first_name) return send_file('avatar.svg', BytesIO(avatar.encode()), mimetype='image/svg+xml', no_cache=True, inline=True, safe=False) elif source == ProfilePictureSource.custom: metadata = self.user.picture_metadata return send_file('avatar.png', BytesIO(self.user.picture), mimetype=metadata['content_type'], no_cache=True, inline=True) else: gravatar = get_gravatar_for_user(self.user, source == ProfilePictureSource.identicon, size=80)[0] return send_file('avatar.png', BytesIO(gravatar), mimetype='image/png') class RHProfilePictureDisplay(RH): """Display the user's profile picture.""" def _process_args(self): self.user = User.get_or_404(request.view_args['user_id'], is_deleted=False) def _process(self): return send_avatar(self.user) class RHSaveProfilePicture(RHUserBase): """Update the user's profile picture.""" @use_kwargs({ 'source': EnumField(ProfilePictureSource) }) def _process(self, source): self.user.picture_source = source if source == ProfilePictureSource.standard: self.user.picture = None self.user.picture_metadata = None logger.info('Profile picture of user %s removed by %s', self.user, session.user) return '', 204 if source == ProfilePictureSource.custom: f = request.files['picture'] try: pic = Image.open(f) except OSError: raise UserValueError(_('You cannot upload this file as profile picture.')) if pic.format.lower() not in {'jpeg', 'png', 'gif', 'webp'}: raise UserValueError(_('The file has an invalid format ({format}).').format(format=pic.format)) if pic.mode not in ('RGB', 'RGBA'): pic = pic.convert('RGB') pic = square(pic) if pic.height > 256: pic = pic.resize((256, 256), resample=Image.BICUBIC) image_bytes = BytesIO() pic.save(image_bytes, 'PNG') image_bytes.seek(0) set_user_avatar(self.user, image_bytes.read(), f.filename) else: content, lastmod = get_gravatar_for_user(self.user, source == ProfilePictureSource.identicon, 256) set_user_avatar(self.user, content, source.name, lastmod) logger.info('Profile picture of user %s updated by %s', self.user, session.user) return '', 204 class RHUserPreferences(RHUserBase): def _process(self): extra_preferences = [pref(self.user) for pref in values_from_signal(signals.users.preferences.send(self.user)) if pref.is_active(self.user)] form_class = UserPreferencesForm defaults = FormDefaults(**self.user.settings.get_all(self.user)) for pref in extra_preferences: form_class = pref.extend_form(form_class) pref.extend_defaults(defaults) form = form_class(obj=defaults) if form.validate_on_submit(): data = form.data for pref in extra_preferences: pref.process_form_data(data) self.user.settings.set_multi(data) session.lang = self.user.settings.get('lang') session.timezone = (self.user.settings.get('timezone') if self.user.settings.get('force_timezone') else 'LOCAL') flash(_('Preferences saved'), 'success') return redirect(url_for('.user_preferences')) return WPUser.render_template('preferences.html', 'preferences', user=self.user, form=form) class RHUserFavorites(RHUserBase): def _process(self): return WPUserFavorites.render_template('favorites.html', 'favorites', user=self.user) class RHUserFavoritesAPI(RHUserBase): def _process_args(self): RHUserBase._process_args(self) self.fav_user = ( User.get_or_404(request.view_args['fav_user_id']) if 'fav_user_id' in request.view_args else None ) def _process_GET(self): return jsonify(sorted(u.id for u in self.user.favorite_users)) def _process_PUT(self): self.user.favorite_users.add(self.fav_user) return jsonify(self.user.id), 201 def _process_DELETE(self): self.user.favorite_users.discard(self.fav_user) return '', 204 class RHUserFavoritesCategoryAPI(RHUserBase): def _process_args(self): RHUserBase._process_args(self) self.category = ( Category.get_or_404(request.view_args['category_id']) if 'category_id' in request.view_args else None ) self.suggestion = ( self.user.suggested_categories.filter_by(category=self.category).first() if 'category_id' in request.view_args else None ) def _process_GET(self): return jsonify({d.id: BasicCategorySchema().dump(d) for d in self.user.favorite_categories}) def _process_PUT(self): if self.category not in self.user.favorite_categories: if not self.category.can_access(self.user): raise Forbidden() self.user.favorite_categories.add(self.category) if self.suggestion: self.user.suggested_categories.remove(self.suggestion) return jsonify(success=True) def _process_DELETE(self): if self.category in self.user.favorite_categories: self.user.favorite_categories.discard(self.category) try: db.session.flush() except StaleDataError: # Deleted in another transaction db.session.rollback() suggestion = self.user.suggested_categories.filter_by(category=self.category).first() if suggestion: self.user.suggested_categories.remove(suggestion) return jsonify(success=True) class RHUserSuggestionsRemove(RHUserBase): def _process(self): suggestion = self.user.suggested_categories.filter_by(category_id=request.view_args['category_id']).first() if suggestion: suggestion.is_ignored = True return jsonify(success=True) class RHUserEmails(RHUserBase): def _send_confirmation(self, email): token_storage = make_scoped_cache('confirm-email') data = {'email': email, 'user_id': self.user.id} token = make_unique_token(lambda t: not token_storage.get(t)) token_storage.set(token, data, timeout=86400) send_email(make_email(email, template=get_template_module('users/emails/verify_email.txt', user=self.user, email=email, token=token))) def _process(self): form = UserEmailsForm() if form.validate_on_submit(): self._send_confirmation(form.email.data) flash(_('We have sent an email to {email}. Please click the link in that email within 24 hours to ' 'confirm your new email address.').format(email=form.email.data), 'success') return redirect(url_for('.user_emails')) return WPUser.render_template('emails.html', 'emails', user=self.user, form=form) class RHUserEmailsVerify(RHUserBase): flash_user_status = False token_storage = make_scoped_cache('confirm-email') def _validate(self, data): if not data: flash(_('The verification token is invalid or expired.'), 'error') return False, None user = User.get(data['user_id']) if not user or user != self.user: flash(_('This token is for a different Indico user. Please login with the correct account'), 'error') return False, None existing = UserEmail.query.filter_by(is_user_deleted=False, email=data['email']).first() if existing and not existing.user.is_pending: if existing.user == self.user: flash(_('This email address is already attached to your account.')) else: flash(_('This email address is already in use by another account.'), 'error') return False, existing.user return True, existing.user if existing else None def _process(self): token = request.view_args['token'] data = self.token_storage.get(token) valid, existing = self._validate(data) if valid: self.token_storage.delete(token) if existing and existing.is_pending: logger.info('Found pending user %s to be merged into %s', existing, self.user) # If the pending user has missing names, copy them from the active one # to allow it to be marked as not pending and deleted during the merge. existing.first_name = existing.first_name or self.user.first_name existing.last_name = existing.last_name or self.user.last_name merge_users(existing, self.user) flash(_("Merged data from existing '{}' identity").format(existing.email)) existing.is_pending = False self.user.secondary_emails.add(data['email']) signals.users.email_added.send(self.user, email=data['email']) flash(_('The email address {email} has been added to your account.').format(email=data['email']), 'success') return redirect(url_for('.user_emails')) class RHUserEmailsDelete(RHUserBase): def _process(self): email = request.view_args['email'] if email in self.user.secondary_emails: self.user.secondary_emails.remove(email) return jsonify(success=True) class RHUserEmailsSetPrimary(RHUserBase): def _process(self): from .tasks import update_gravatars email = request.form['email'] if email in self.user.secondary_emails: self.user.make_email_primary(email) db.session.commit() if self.user.picture_source in (ProfilePictureSource.gravatar, ProfilePictureSource.identicon): update_gravatars.delay(self.user) flash(_('Your primary email was updated successfully.'), 'success') return redirect(url_for('.user_emails')) class RHAdmins(RHAdminBase): """Show Indico administrators.""" def _process(self): admins = set(User.query .filter_by(is_admin=True, is_deleted=False) .order_by(db.func.lower(User.first_name), db.func.lower(User.last_name))) form = AdminsForm(admins=admins) if form.validate_on_submit(): added = form.admins.data - admins removed = admins - form.admins.data for user in added: user.is_admin = True logger.warning('Admin rights granted to %r by %r [%s]', user, session.user, request.remote_addr) flash(_('Admin added: {name} ({email})').format(name=user.name, email=user.email), 'success') for user in removed: user.is_admin = False logger.warning('Admin rights revoked from %r by %r [%s]', user, session.user, request.remote_addr) flash(_('Admin removed: {name} ({email})').format(name=user.name, email=user.email), 'success') return redirect(url_for('.admins')) return WPUsersAdmin.render_template('admins.html', 'admins', form=form) class RHUsersAdmin(RHAdminBase): """Admin users overview.""" def _process(self): form = SearchForm(obj=FormDefaults(exact=True)) form_data = form.data search_results = None num_of_users = User.query.count() num_deleted_users = User.query.filter_by(is_deleted=True).count() if form.validate_on_submit(): search_results = [] exact = form_data.pop('exact') include_deleted = form_data.pop('include_deleted') include_pending = form_data.pop('include_pending') external = form_data.pop('external') form_data = {k: v for (k, v) in form_data.items() if v and v.strip()} matches = search_users(exact=exact, include_deleted=include_deleted, include_pending=include_pending, include_blocked=True, external=external, allow_system_user=True, **form_data) for entry in matches: if isinstance(entry, User): search_results.append(UserEntry( avatar_url=entry.avatar_url, profile_url=url_for('.user_profile', entry), user=entry, **{k: getattr(entry, k) for k in IDENTITY_ATTRIBUTES} )) else: if not entry.data['first_name'] and not entry.data['last_name']: full_name = '<no name>' initial = '?' else: full_name = f'{entry.data['first_name']} {entry.data['last_name']}'.strip() initial = full_name[0] search_results.append(UserEntry( avatar_url=url_for('assets.avatar', name=initial), profile_url=None, user=None, full_name=full_name, **{k: entry.data.get(k) for k in (IDENTITY_ATTRIBUTES - {'full_name'})} )) search_results.sort(key=attrgetter('full_name')) num_reg_requests = RegistrationRequest.query.count() return WPUsersAdmin.render_template('users_admin.html', 'users', form=form, search_results=search_results, num_of_users=num_of_users, num_deleted_users=num_deleted_users, num_reg_requests=num_reg_requests) class RHUsersAdminSettings(RHAdminBase): """Manage global user-related settings.""" def _process(self): form = AdminUserSettingsForm(obj=FormDefaults(**user_management_settings.get_all())) if form.validate_on_submit(): user_management_settings.set_multi(form.data) return jsonify_data(flash=False) return jsonify_form(form) class RHUsersAdminCreate(RHAdminBase): """Create user (admin).""" def _process(self): form = AdminAccountRegistrationForm() if form.validate_on_submit(): data = form.data if data.pop('create_identity', False): identity = Identity(provider='indico', identifier=data.pop('username'), password=data.pop('password')) else: identity = None data.pop('username', None) data.pop('password', None) user = create_user(data.pop('email'), data, identity, from_moderation=True) msg = Markup('{} <a href="{}">{}</a>').format( escape(_('The account has been created.')), url_for('users.user_profile', user), escape(_('Show details')) ) flash(msg, 'success') return jsonify_data() return jsonify_template('users/users_admin_create.html', form=form) def _get_merge_problems(source, target): errors = [] warnings = [] if source == target: errors.append(_('Users are the same!')) if (source.first_name.strip().lower() != target.first_name.strip().lower() or source.last_name.strip().lower() != target.last_name.strip().lower()): warnings.append(_("Users' names seem to be different!")) if source.is_pending: warnings.append(_('Source user has never logged in to Indico!')) if target.is_pending: warnings.append(_('Target user has never logged in to Indico!')) if source.is_blocked: warnings.append(_('Source user is blocked!')) if target.is_blocked: warnings.append(_('Target user is blocked!')) if source.is_deleted: errors.append(_('Source user has been deleted!')) if target.is_deleted: errors.append(_('Target user has been deleted!')) if source.is_admin: warnings.append(_('Source user is an administrator!')) if target.is_admin: warnings.append(_('Target user is an administrator!')) if source.is_admin and not target.is_admin: errors.append(_("Source user is an administrator but target user isn't!")) return errors, warnings class RHUsersAdminMerge(RHAdminBase): """Merge users (admin).""" def _process(self): form = MergeForm() if form.validate_on_submit(): source = form.source_user.data target = form.target_user.data errors, warnings = _get_merge_problems(source, target) if errors: raise BadRequest(_('Merge aborted due to failed sanity check')) if warnings: logger.info('User %s initiated merge of %s into %s (with %d warnings)', session.user, source, target, len(warnings)) else: logger.info('User %s initiated merge of %s into %s', session.user, source, target) merge_users(source, target) flash(_('The users have been successfully merged.'), 'success') return redirect(url_for('.user_profile', user_id=target.id)) return WPUsersAdmin.render_template('users_merge.html', 'users', form=form) class RHUsersAdminMergeCheck(RHAdminBase): @use_kwargs({ 'source': Principal(allow_external_users=True, required=True), 'target': Principal(allow_external_users=True, required=True), }, location='query') def _process(self, source, target): errors, warnings = _get_merge_problems(source, target) return jsonify(errors=errors, warnings=warnings, source=serialize_user(source), target=serialize_user(target)) class RHRegistrationRequestList(RHAdminBase): """List all registration requests.""" def _process(self): requests = RegistrationRequest.query.order_by(RegistrationRequest.email).all() return WPUsersAdmin.render_template('registration_requests.html', 'users', pending_requests=requests) class RHRegistrationRequestBase(RHAdminBase): """Base class to process a registration request.""" def _process_args(self): RHAdminBase._process_args(self) self.request = RegistrationRequest.get_or_404(request.view_args['request_id']) class RHAcceptRegistrationRequest(RHRegistrationRequestBase): """Accept a registration request.""" def _process(self): user, identity = register_user(self.request.email, self.request.extra_emails, self.request.user_data, self.request.identity_data, self.request.settings) tpl = get_template_module('users/emails/registration_request_accepted.txt', user=user) send_email(make_email(self.request.email, template=tpl)) flash(_('The request has been approved.'), 'success') return jsonify_data() class RHRejectRegistrationRequest(RHRegistrationRequestBase): """Reject a registration request.""" def _process(self): db.session.delete(self.request) tpl = get_template_module('users/emails/registration_request_rejected.txt', req=self.request) send_email(make_email(self.request.email, template=tpl)) flash(_('The request has been rejected.'), 'success') return jsonify_data() class UserSearchResultSchema(mm.SQLAlchemyAutoSchema): class Meta: model = User fields = ('id', 'identifier', 'email', 'affiliation', 'full_name', 'first_name', 'last_name', 'avatar_url') search_result_schema = UserSearchResultSchema() class RHUserSearch(RHProtected): """Search for users based on given criteria.""" def _serialize_pending_user(self, entry): first_name = entry.data.get('first_name') or '' last_name = entry.data.get('last_name') or '' full_name = f'{first_name} {last_name}'.strip() or 'Unknown' affiliation = entry.data.get('affiliation') or '' email = entry.data['email'].lower() ext_id = f'{entry.provider.name}:{entry.identifier}' # IdentityInfo from flask-multipass does not have `avatar_url` avatar_url = get_avatar_url_from_name(first_name) # detailed data to put in redis to create a pending user if needed self.externals[ext_id] = { 'first_name': first_name, 'last_name': last_name, 'email': email, 'affiliation': affiliation, 'phone': entry.data.get('phone') or '', 'address': entry.data.get('address') or '', } # simple data for the search results return { '_ext_id': ext_id, 'id': None, 'identifier': f'ExternalUser:{ext_id}', 'email': email, 'affiliation': affiliation, 'full_name': full_name, 'first_name': first_name, 'last_name': last_name, 'avatar_url': avatar_url } def _serialize_entry(self, entry): if isinstance(entry, User): return search_result_schema.dump(entry) else: return self._serialize_pending_user(entry) def _process_pending_users(self, results): cache = make_scoped_cache('external-user') for entry in results: ext_id = entry.pop('_ext_id', None) if ext_id is not None: cache.set(ext_id, self.externals[ext_id], timeout=86400) @use_kwargs({ 'first_name': fields.Str(validate=validate.Length(min=1)), 'last_name': fields.Str(validate=validate.Length(min=1)), 'email': fields.Str(validate=lambda s: len(s) > 3), 'affiliation': fields.Str(validate=validate.Length(min=1)), 'exact': fields.Bool(missing=False), 'external': fields.Bool(missing=False), 'favorites_first': fields.Bool(missing=False) }, validate=validate_with_message( lambda args: args.keys() & {'first_name', 'last_name', 'email', 'affiliation'}, 'No criteria provided' ), location='query') def _process(self, exact, external, favorites_first, **criteria): matches = search_users(exact=exact, include_pending=True, external=external, **criteria) self.externals = {} results = sorted((self._serialize_entry(entry) for entry in matches), key=itemgetter('full_name', 'email')) if favorites_first: favorites = {u.id for u in session.user.favorite_users} results.sort(key=lambda x: x['id'] not in favorites) total = len(results) results = results[:10] self._process_pending_users(results) return jsonify(users=results, total=total) class RHUserSearchInfo(RHProtected): def _process(self): external_users_available = any(auth.supports_search for auth in multipass.identity_providers.values()) return jsonify(external_users_available=external_users_available) class RHUserBlock(RHUserBase): def _check_access(self): RHUserBase._check_access(self) if not session.user.is_admin: raise Forbidden def _process_PUT(self): if self.user == session.user: raise Forbidden(_('You cannot block yourself')) self.user.is_blocked = True logger.info('User %s blocked %s', session.user, self.user) flash(_('{name} has been blocked.').format(name=self.user.name), 'success') return jsonify(success=True) def _process_DELETE(self): self.user.is_blocked = False logger.info('User %s unblocked %s', session.user, self.user) flash(_('{name} has been unblocked.').format(name=self.user.name), 'success') return jsonify(success=True)
# This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from collections import namedtuple from io import BytesIO from operator import attrgetter, itemgetter from dateutil.relativedelta import relativedelta from flask import flash, jsonify, redirect, render_template, request, session from markupsafe import Markup, escape from marshmallow import fields from marshmallow_enum import EnumField from PIL import Image from sqlalchemy.orm import joinedload, load_only, subqueryload from sqlalchemy.orm.exc import StaleDataError from webargs import validate from werkzeug.exceptions import BadRequest, Forbidden, NotFound from indico.core import signals from indico.core.auth import multipass from indico.core.cache import make_scoped_cache from indico.core.db import db from indico.core.db.sqlalchemy.util.queries import get_n_matching from indico.core.errors import UserValueError from indico.core.marshmallow import mm from indico.core.notifications import make_email, send_email from indico.modules.admin import RHAdminBase from indico.modules.auth import Identity from indico.modules.auth.models.registration_requests import RegistrationRequest from indico.modules.auth.util import register_user from indico.modules.categories import Category from indico.modules.events import Event from indico.modules.events.util import serialize_event_for_ical from indico.modules.users import User, logger, user_management_settings from indico.modules.users.forms import (AdminAccountRegistrationForm, AdminsForm, AdminUserSettingsForm, MergeForm, SearchForm, UserDetailsForm, UserEmailsForm, UserPreferencesForm) from indico.modules.users.models.emails import UserEmail from indico.modules.users.models.users import ProfilePictureSource from indico.modules.users.operations import create_user from indico.modules.users.schemas import BasicCategorySchema from indico.modules.users.util import (get_avatar_url_from_name, get_gravatar_for_user, get_linked_events, get_related_categories, get_suggested_categories, merge_users, search_users, send_avatar, serialize_user, set_user_avatar) from indico.modules.users.views import WPUser, WPUserDashboard, WPUserFavorites, WPUserProfilePic, WPUsersAdmin from indico.util.date_time import now_utc from indico.util.i18n import _ from indico.util.images import square from indico.util.marshmallow import HumanizedDate, Principal, validate_with_message from indico.util.signals import values_from_signal from indico.util.string import make_unique_token from indico.web.args import use_kwargs from indico.web.flask.templating import get_template_module from indico.web.flask.util import send_file, url_for from indico.web.forms.base import FormDefaults from indico.web.http_api.metadata import Serializer from indico.web.rh import RH, RHProtected, allow_signed_url from indico.web.util import is_legacy_signed_url_valid, jsonify_data, jsonify_form, jsonify_template IDENTITY_ATTRIBUTES = {'first_name', 'last_name', 'email', 'affiliation', 'full_name'} UserEntry = namedtuple('UserEntry', IDENTITY_ATTRIBUTES | {'profile_url', 'avatar_url', 'user'}) def get_events_in_categories(category_ids, user, limit=10): """Get all the user-accessible events in a given set of categories.""" tz = session.tzinfo today = now_utc(False).astimezone(tz).date() query = (Event.query .filter(~Event.is_deleted, Event.category_chain_overlaps(category_ids), Event.start_dt.astimezone(session.tzinfo) >= today) .options(joinedload('category').load_only('id', 'title'), joinedload('series'), joinedload('label'), subqueryload('acl_entries'), load_only('id', 'category_id', 'start_dt', 'end_dt', 'title', 'access_key', 'protection_mode', 'series_id', 'series_pos', 'series_count', 'label_id', 'label_message')) .order_by(Event.start_dt, Event.id)) return get_n_matching(query, limit, lambda x: x.can_access(user)) class RHUserBase(RHProtected): flash_user_status = True allow_system_user = False def _process_args(self): if not session.user: return self.user = session.user if 'user_id' in request.view_args: self.user = User.get(request.view_args['user_id']) if self.user is None: raise NotFound('This user does not exist') elif request.method == 'GET' and not request.is_xhr and self.flash_user_status: # Show messages about the user's status if it's a simple GET request if self.user.is_deleted: if self.user.merged_into_id is not None: msg = _('This user has been merged into <a href="{url}">another user</a>.') flash(Markup(msg).format(url=url_for(request.endpoint, self.user.merged_into_user)), 'warning') else: flash(_('This user is marked as deleted.'), 'warning') if self.user.is_pending: flash(_('This user is marked as pending, i.e. it has been attached to something but never ' 'logged in.'), 'warning') if not self.allow_system_user and self.user.is_system: return redirect(url_for('users.user_profile')) def _check_access(self): RHProtected._check_access(self) if not self.user.can_be_modified(session.user): raise Forbidden('You cannot modify this user.') class RHUserDashboard(RHUserBase): management_roles = {'conference_creator', 'conference_chair', 'conference_manager', 'session_manager', 'session_coordinator', 'contribution_manager'} reviewer_roles = {'paper_manager', 'paper_judge', 'paper_content_reviewer', 'paper_layout_reviewer', 'contribution_referee', 'contribution_editor', 'contribution_reviewer', 'abstract_reviewer', 'track_convener'} attendance_roles = {'contributor', 'contribution_submission', 'abstract_submitter', 'abstract_person', 'registration_registrant', 'survey_submitter', 'lecture_speaker'} def _process(self): self.user.settings.set('suggest_categories', True) categories = get_related_categories(self.user) categories_events = [] if categories: category_ids = {c['categ'].id for c in categories.values()} categories_events = get_events_in_categories(category_ids, self.user) from_dt = now_utc(False) - relativedelta(weeks=1, hour=0, minute=0, second=0) linked_events = [(event, {'management': bool(roles & self.management_roles), 'reviewing': bool(roles & self.reviewer_roles), 'attendance': bool(roles & self.attendance_roles)}) for event, roles in get_linked_events(self.user, from_dt, 10).items()] return WPUserDashboard.render_template('dashboard.html', 'dashboard', user=self.user, categories=categories, categories_events=categories_events, suggested_categories=get_suggested_categories(self.user), linked_events=linked_events) @allow_signed_url class RHExportDashboardICS(RHProtected): def _get_user(self): return session.user @use_kwargs({ 'from_': HumanizedDate(data_key='from', missing=lambda: now_utc(False) - relativedelta(weeks=1)), 'include': fields.List(fields.Str(), missing={'linked', 'categories'}), 'limit': fields.Integer(missing=100, validate=lambda v: 0 < v <= 500) }, location='query') def _process(self, from_, include, limit): user = self._get_user() all_events = set() if 'linked' in include: all_events |= set(get_linked_events( user, from_, limit=limit, load_also=('description', 'own_room_id', 'own_venue_id', 'own_room_name', 'own_venue_name') )) if 'categories' in include and (categories := get_related_categories(user)): category_ids = {c['categ'].id for c in categories.values()} all_events |= set(get_events_in_categories(category_ids, user, limit=limit)) all_events = sorted(all_events, key=lambda e: (e.start_dt, e.id))[:limit] response = {'results': [serialize_event_for_ical(event, 'events') for event in all_events]} serializer = Serializer.create('ics') return send_file('event.ics', BytesIO(serializer(response)), 'text/calendar') class RHExportDashboardICSLegacy(RHExportDashboardICS): def _get_user(self): user = User.get_or_404(request.view_args['user_id'], is_deleted=False) if not is_legacy_signed_url_valid(user, request.full_path): raise BadRequest('Invalid signature') if user.is_blocked: raise BadRequest('User blocked') return user def _check_access(self): # disable the usual RHProtected access check; `_get_user` does it all pass class RHPersonalData(RHUserBase): allow_system_user = True def _process(self): form = UserDetailsForm(obj=FormDefaults(self.user, skip_attrs={'title'}, title=self.user._title), synced_fields=self.user.synced_fields, synced_values=self.user.synced_values) if form.validate_on_submit(): self.user.synced_fields = form.synced_fields form.populate_obj(self.user, skip=self.user.synced_fields) self.user.synchronize_data(refresh=True) flash(_('Your personal data was successfully updated.'), 'success') return redirect(url_for('.user_profile')) return WPUser.render_template('personal_data.html', 'personal_data', user=self.user, form=form) class RHProfilePicturePage(RHUserBase): """Page to manage the profile picture.""" def _process(self): return WPUserProfilePic.render_template('profile_picture.html', 'profile_picture', user=self.user, source=self.user.picture_source.name) class RHProfilePicturePreview(RHUserBase): """Preview the different profile pictures. This always uses a fresh picture without any caching. """ @use_kwargs({'source': EnumField(ProfilePictureSource)}, location='view_args') def _process(self, source): if source == ProfilePictureSource.standard: first_name = self.user.first_name[0].upper() if self.user.first_name else '' avatar = render_template('users/avatar.svg', bg_color=self.user.avatar_bg_color, text=first_name) return send_file('avatar.svg', BytesIO(avatar.encode()), mimetype='image/svg+xml', no_cache=True, inline=True, safe=False) elif source == ProfilePictureSource.custom: metadata = self.user.picture_metadata return send_file('avatar.png', BytesIO(self.user.picture), mimetype=metadata['content_type'], no_cache=True, inline=True) else: gravatar = get_gravatar_for_user(self.user, source == ProfilePictureSource.identicon, size=80)[0] return send_file('avatar.png', BytesIO(gravatar), mimetype='image/png') class RHProfilePictureDisplay(RH): """Display the user's profile picture.""" def _process_args(self): self.user = User.get_or_404(request.view_args['user_id'], is_deleted=False) def _process(self): return send_avatar(self.user) class RHSaveProfilePicture(RHUserBase): """Update the user's profile picture.""" @use_kwargs({ 'source': EnumField(ProfilePictureSource) }) def _process(self, source): self.user.picture_source = source if source == ProfilePictureSource.standard: self.user.picture = None self.user.picture_metadata = None logger.info('Profile picture of user %s removed by %s', self.user, session.user) return '', 204 if source == ProfilePictureSource.custom: f = request.files['picture'] try: pic = Image.open(f) except OSError: raise UserValueError(_('You cannot upload this file as profile picture.')) if pic.format.lower() not in {'jpeg', 'png', 'gif', 'webp'}: raise UserValueError(_('The file has an invalid format ({format}).').format(format=pic.format)) if pic.mode not in ('RGB', 'RGBA'): pic = pic.convert('RGB') pic = square(pic) if pic.height > 256: pic = pic.resize((256, 256), resample=Image.BICUBIC) image_bytes = BytesIO() pic.save(image_bytes, 'PNG') image_bytes.seek(0) set_user_avatar(self.user, image_bytes.read(), f.filename) else: content, lastmod = get_gravatar_for_user(self.user, source == ProfilePictureSource.identicon, 256) set_user_avatar(self.user, content, source.name, lastmod) logger.info('Profile picture of user %s updated by %s', self.user, session.user) return '', 204 class RHUserPreferences(RHUserBase): def _process(self): extra_preferences = [pref(self.user) for pref in values_from_signal(signals.users.preferences.send(self.user)) if pref.is_active(self.user)] form_class = UserPreferencesForm defaults = FormDefaults(**self.user.settings.get_all(self.user)) for pref in extra_preferences: form_class = pref.extend_form(form_class) pref.extend_defaults(defaults) form = form_class(obj=defaults) if form.validate_on_submit(): data = form.data for pref in extra_preferences: pref.process_form_data(data) self.user.settings.set_multi(data) session.lang = self.user.settings.get('lang') session.timezone = (self.user.settings.get('timezone') if self.user.settings.get('force_timezone') else 'LOCAL') flash(_('Preferences saved'), 'success') return redirect(url_for('.user_preferences')) return WPUser.render_template('preferences.html', 'preferences', user=self.user, form=form) class RHUserFavorites(RHUserBase): def _process(self): return WPUserFavorites.render_template('favorites.html', 'favorites', user=self.user) class RHUserFavoritesAPI(RHUserBase): def _process_args(self): RHUserBase._process_args(self) self.fav_user = ( User.get_or_404(request.view_args['fav_user_id']) if 'fav_user_id' in request.view_args else None ) def _process_GET(self): return jsonify(sorted(u.id for u in self.user.favorite_users)) def _process_PUT(self): self.user.favorite_users.add(self.fav_user) return jsonify(self.user.id), 201 def _process_DELETE(self): self.user.favorite_users.discard(self.fav_user) return '', 204 class RHUserFavoritesCategoryAPI(RHUserBase): def _process_args(self): RHUserBase._process_args(self) self.category = ( Category.get_or_404(request.view_args['category_id']) if 'category_id' in request.view_args else None ) self.suggestion = ( self.user.suggested_categories.filter_by(category=self.category).first() if 'category_id' in request.view_args else None ) def _process_GET(self): return jsonify({d.id: BasicCategorySchema().dump(d) for d in self.user.favorite_categories}) def _process_PUT(self): if self.category not in self.user.favorite_categories: if not self.category.can_access(self.user): raise Forbidden() self.user.favorite_categories.add(self.category) if self.suggestion: self.user.suggested_categories.remove(self.suggestion) return jsonify(success=True) def _process_DELETE(self): if self.category in self.user.favorite_categories: self.user.favorite_categories.discard(self.category) try: db.session.flush() except StaleDataError: # Deleted in another transaction db.session.rollback() suggestion = self.user.suggested_categories.filter_by(category=self.category).first() if suggestion: self.user.suggested_categories.remove(suggestion) return jsonify(success=True) class RHUserSuggestionsRemove(RHUserBase): def _process(self): suggestion = self.user.suggested_categories.filter_by(category_id=request.view_args['category_id']).first() if suggestion: suggestion.is_ignored = True return jsonify(success=True) class RHUserEmails(RHUserBase): def _send_confirmation(self, email): token_storage = make_scoped_cache('confirm-email') data = {'email': email, 'user_id': self.user.id} token = make_unique_token(lambda t: not token_storage.get(t)) token_storage.set(token, data, timeout=86400) send_email(make_email(email, template=get_template_module('users/emails/verify_email.txt', user=self.user, email=email, token=token))) def _process(self): form = UserEmailsForm() if form.validate_on_submit(): self._send_confirmation(form.email.data) flash(_('We have sent an email to {email}. Please click the link in that email within 24 hours to ' 'confirm your new email address.').format(email=form.email.data), 'success') return redirect(url_for('.user_emails')) return WPUser.render_template('emails.html', 'emails', user=self.user, form=form) class RHUserEmailsVerify(RHUserBase): flash_user_status = False token_storage = make_scoped_cache('confirm-email') def _validate(self, data): if not data: flash(_('The verification token is invalid or expired.'), 'error') return False, None user = User.get(data['user_id']) if not user or user != self.user: flash(_('This token is for a different Indico user. Please login with the correct account'), 'error') return False, None existing = UserEmail.query.filter_by(is_user_deleted=False, email=data['email']).first() if existing and not existing.user.is_pending: if existing.user == self.user: flash(_('This email address is already attached to your account.')) else: flash(_('This email address is already in use by another account.'), 'error') return False, existing.user return True, existing.user if existing else None def _process(self): token = request.view_args['token'] data = self.token_storage.get(token) valid, existing = self._validate(data) if valid: self.token_storage.delete(token) if existing and existing.is_pending: logger.info('Found pending user %s to be merged into %s', existing, self.user) # If the pending user has missing names, copy them from the active one # to allow it to be marked as not pending and deleted during the merge. existing.first_name = existing.first_name or self.user.first_name existing.last_name = existing.last_name or self.user.last_name merge_users(existing, self.user) flash(_("Merged data from existing '{}' identity").format(existing.email)) existing.is_pending = False self.user.secondary_emails.add(data['email']) signals.users.email_added.send(self.user, email=data['email']) flash(_('The email address {email} has been added to your account.').format(email=data['email']), 'success') return redirect(url_for('.user_emails')) class RHUserEmailsDelete(RHUserBase): def _process(self): email = request.view_args['email'] if email in self.user.secondary_emails: self.user.secondary_emails.remove(email) return jsonify(success=True) class RHUserEmailsSetPrimary(RHUserBase): def _process(self): from .tasks import update_gravatars email = request.form['email'] if email in self.user.secondary_emails: self.user.make_email_primary(email) db.session.commit() if self.user.picture_source in (ProfilePictureSource.gravatar, ProfilePictureSource.identicon): update_gravatars.delay(self.user) flash(_('Your primary email was updated successfully.'), 'success') return redirect(url_for('.user_emails')) class RHAdmins(RHAdminBase): """Show Indico administrators.""" def _process(self): admins = set(User.query .filter_by(is_admin=True, is_deleted=False) .order_by(db.func.lower(User.first_name), db.func.lower(User.last_name))) form = AdminsForm(admins=admins) if form.validate_on_submit(): added = form.admins.data - admins removed = admins - form.admins.data for user in added: user.is_admin = True logger.warning('Admin rights granted to %r by %r [%s]', user, session.user, request.remote_addr) flash(_('Admin added: {name} ({email})').format(name=user.name, email=user.email), 'success') for user in removed: user.is_admin = False logger.warning('Admin rights revoked from %r by %r [%s]', user, session.user, request.remote_addr) flash(_('Admin removed: {name} ({email})').format(name=user.name, email=user.email), 'success') return redirect(url_for('.admins')) return WPUsersAdmin.render_template('admins.html', 'admins', form=form) class RHUsersAdmin(RHAdminBase): """Admin users overview.""" def _process(self): form = SearchForm(obj=FormDefaults(exact=True)) form_data = form.data search_results = None num_of_users = User.query.count() num_deleted_users = User.query.filter_by(is_deleted=True).count() if form.validate_on_submit(): search_results = [] exact = form_data.pop('exact') include_deleted = form_data.pop('include_deleted') include_pending = form_data.pop('include_pending') external = form_data.pop('external') form_data = {k: v for (k, v) in form_data.items() if v and v.strip()} matches = search_users(exact=exact, include_deleted=include_deleted, include_pending=include_pending, include_blocked=True, external=external, allow_system_user=True, **form_data) for entry in matches: if isinstance(entry, User): search_results.append(UserEntry( avatar_url=entry.avatar_url, profile_url=url_for('.user_profile', entry), user=entry, **{k: getattr(entry, k) for k in IDENTITY_ATTRIBUTES} )) else: if not entry.data['first_name'] and not entry.data['last_name']: full_name = '<no name>' initial = '?' else: full_name = f'{entry.data["first_name"]} {entry.data["last_name"]}'.strip() initial = full_name[0] search_results.append(UserEntry( avatar_url=url_for('assets.avatar', name=initial), profile_url=None, user=None, full_name=full_name, **{k: entry.data.get(k) for k in (IDENTITY_ATTRIBUTES - {'full_name'})} )) search_results.sort(key=attrgetter('full_name')) num_reg_requests = RegistrationRequest.query.count() return WPUsersAdmin.render_template('users_admin.html', 'users', form=form, search_results=search_results, num_of_users=num_of_users, num_deleted_users=num_deleted_users, num_reg_requests=num_reg_requests) class RHUsersAdminSettings(RHAdminBase): """Manage global user-related settings.""" def _process(self): form = AdminUserSettingsForm(obj=FormDefaults(**user_management_settings.get_all())) if form.validate_on_submit(): user_management_settings.set_multi(form.data) return jsonify_data(flash=False) return jsonify_form(form) class RHUsersAdminCreate(RHAdminBase): """Create user (admin).""" def _process(self): form = AdminAccountRegistrationForm() if form.validate_on_submit(): data = form.data if data.pop('create_identity', False): identity = Identity(provider='indico', identifier=data.pop('username'), password=data.pop('password')) else: identity = None data.pop('username', None) data.pop('password', None) user = create_user(data.pop('email'), data, identity, from_moderation=True) msg = Markup('{} <a href="{}">{}</a>').format( escape(_('The account has been created.')), url_for('users.user_profile', user), escape(_('Show details')) ) flash(msg, 'success') return jsonify_data() return jsonify_template('users/users_admin_create.html', form=form) def _get_merge_problems(source, target): errors = [] warnings = [] if source == target: errors.append(_('Users are the same!')) if (source.first_name.strip().lower() != target.first_name.strip().lower() or source.last_name.strip().lower() != target.last_name.strip().lower()): warnings.append(_("Users' names seem to be different!")) if source.is_pending: warnings.append(_('Source user has never logged in to Indico!')) if target.is_pending: warnings.append(_('Target user has never logged in to Indico!')) if source.is_blocked: warnings.append(_('Source user is blocked!')) if target.is_blocked: warnings.append(_('Target user is blocked!')) if source.is_deleted: errors.append(_('Source user has been deleted!')) if target.is_deleted: errors.append(_('Target user has been deleted!')) if source.is_admin: warnings.append(_('Source user is an administrator!')) if target.is_admin: warnings.append(_('Target user is an administrator!')) if source.is_admin and not target.is_admin: errors.append(_("Source user is an administrator but target user isn't!")) return errors, warnings class RHUsersAdminMerge(RHAdminBase): """Merge users (admin).""" def _process(self): form = MergeForm() if form.validate_on_submit(): source = form.source_user.data target = form.target_user.data errors, warnings = _get_merge_problems(source, target) if errors: raise BadRequest(_('Merge aborted due to failed sanity check')) if warnings: logger.info('User %s initiated merge of %s into %s (with %d warnings)', session.user, source, target, len(warnings)) else: logger.info('User %s initiated merge of %s into %s', session.user, source, target) merge_users(source, target) flash(_('The users have been successfully merged.'), 'success') return redirect(url_for('.user_profile', user_id=target.id)) return WPUsersAdmin.render_template('users_merge.html', 'users', form=form) class RHUsersAdminMergeCheck(RHAdminBase): @use_kwargs({ 'source': Principal(allow_external_users=True, required=True), 'target': Principal(allow_external_users=True, required=True), }, location='query') def _process(self, source, target): errors, warnings = _get_merge_problems(source, target) return jsonify(errors=errors, warnings=warnings, source=serialize_user(source), target=serialize_user(target)) class RHRegistrationRequestList(RHAdminBase): """List all registration requests.""" def _process(self): requests = RegistrationRequest.query.order_by(RegistrationRequest.email).all() return WPUsersAdmin.render_template('registration_requests.html', 'users', pending_requests=requests) class RHRegistrationRequestBase(RHAdminBase): """Base class to process a registration request.""" def _process_args(self): RHAdminBase._process_args(self) self.request = RegistrationRequest.get_or_404(request.view_args['request_id']) class RHAcceptRegistrationRequest(RHRegistrationRequestBase): """Accept a registration request.""" def _process(self): user, identity = register_user(self.request.email, self.request.extra_emails, self.request.user_data, self.request.identity_data, self.request.settings) tpl = get_template_module('users/emails/registration_request_accepted.txt', user=user) send_email(make_email(self.request.email, template=tpl)) flash(_('The request has been approved.'), 'success') return jsonify_data() class RHRejectRegistrationRequest(RHRegistrationRequestBase): """Reject a registration request.""" def _process(self): db.session.delete(self.request) tpl = get_template_module('users/emails/registration_request_rejected.txt', req=self.request) send_email(make_email(self.request.email, template=tpl)) flash(_('The request has been rejected.'), 'success') return jsonify_data() class UserSearchResultSchema(mm.SQLAlchemyAutoSchema): class Meta: model = User fields = ('id', 'identifier', 'email', 'affiliation', 'full_name', 'first_name', 'last_name', 'avatar_url') search_result_schema = UserSearchResultSchema() class RHUserSearch(RHProtected): """Search for users based on given criteria.""" def _serialize_pending_user(self, entry): first_name = entry.data.get('first_name') or '' last_name = entry.data.get('last_name') or '' full_name = f'{first_name} {last_name}'.strip() or 'Unknown' affiliation = entry.data.get('affiliation') or '' email = entry.data['email'].lower() ext_id = f'{entry.provider.name}:{entry.identifier}' # IdentityInfo from flask-multipass does not have `avatar_url` avatar_url = get_avatar_url_from_name(first_name) # detailed data to put in redis to create a pending user if needed self.externals[ext_id] = { 'first_name': first_name, 'last_name': last_name, 'email': email, 'affiliation': affiliation, 'phone': entry.data.get('phone') or '', 'address': entry.data.get('address') or '', } # simple data for the search results return { '_ext_id': ext_id, 'id': None, 'identifier': f'ExternalUser:{ext_id}', 'email': email, 'affiliation': affiliation, 'full_name': full_name, 'first_name': first_name, 'last_name': last_name, 'avatar_url': avatar_url } def _serialize_entry(self, entry): if isinstance(entry, User): return search_result_schema.dump(entry) else: return self._serialize_pending_user(entry) def _process_pending_users(self, results): cache = make_scoped_cache('external-user') for entry in results: ext_id = entry.pop('_ext_id', None) if ext_id is not None: cache.set(ext_id, self.externals[ext_id], timeout=86400) @use_kwargs({ 'first_name': fields.Str(validate=validate.Length(min=1)), 'last_name': fields.Str(validate=validate.Length(min=1)), 'email': fields.Str(validate=lambda s: len(s) > 3), 'affiliation': fields.Str(validate=validate.Length(min=1)), 'exact': fields.Bool(missing=False), 'external': fields.Bool(missing=False), 'favorites_first': fields.Bool(missing=False) }, validate=validate_with_message( lambda args: args.keys() & {'first_name', 'last_name', 'email', 'affiliation'}, 'No criteria provided' ), location='query') def _process(self, exact, external, favorites_first, **criteria): matches = search_users(exact=exact, include_pending=True, external=external, **criteria) self.externals = {} results = sorted((self._serialize_entry(entry) for entry in matches), key=itemgetter('full_name', 'email')) if favorites_first: favorites = {u.id for u in session.user.favorite_users} results.sort(key=lambda x: x['id'] not in favorites) total = len(results) results = results[:10] self._process_pending_users(results) return jsonify(users=results, total=total) class RHUserSearchInfo(RHProtected): def _process(self): external_users_available = any(auth.supports_search for auth in multipass.identity_providers.values()) return jsonify(external_users_available=external_users_available) class RHUserBlock(RHUserBase): def _check_access(self): RHUserBase._check_access(self) if not session.user.is_admin: raise Forbidden def _process_PUT(self): if self.user == session.user: raise Forbidden(_('You cannot block yourself')) self.user.is_blocked = True logger.info('User %s blocked %s', session.user, self.user) flash(_('{name} has been blocked.').format(name=self.user.name), 'success') return jsonify(success=True) def _process_DELETE(self): self.user.is_blocked = False logger.info('User %s unblocked %s', session.user, self.user) flash(_('{name} has been unblocked.').format(name=self.user.name), 'success') return jsonify(success=True)
import cv2 import numpy as np from . import ref_input class Stimulus: def __init__(self, param): self.param = param self.image = create_image(param['image']) self.motion = self.get_motion_model(param['motion']) self.vel = np.array([0.0, 0.0]) self.pos = np.array([0.0, 0.0]) @property def done(self): return self.motion.done def update(self, t, dt): self.vel = self.motion.velocity(t) self.pos += dt*self.vel def display_image(self, input_pos): rel_pos = self.pos - input_pos image = np.roll(self.image, int(rel_pos[1]), axis=0) image = np.roll(image, int(rel_pos[0]), axis=1) if self.param['image']['type'] == 'ball': width = self.param['image']['width'] height = self.param['image']['height'] radius = int(1.5*self.param['image']['radius']) pos = (width//2, height//2) image = cv2.circle(image, pos, radius, (0,0,255), 5) return image @staticmethod def get_motion_model(motion_param): if motion_param['type'] == 'none': model = ref_input.NoMotion(motion_param) elif motion_param['type'] == 'sin': model = ref_input.Sin(motion_param) elif motion_param['type'] == 'sin_series': model = ref_input.SinSeries(motion_param) elif motion_param['type'] == 'sin_period_series': model = ref_input.SinPeriodSeries(motion_param) elif motion_param['type'] == 'step': model = ref_input.Step(motion_param) elif motion_param['type'] == 'step_series': model = ref_input.StepSeries(motion_param) elif motion_param['type'] == 'step_zero_step': model = ref_input.StepZeroStep(motion_param) elif motion_param['type'] == 'random_step': model = ref_input.RandomStep(motion_param) elif motion_param['type'] == 'cyclic_chirp': model = ref_input.CyclicChirp(motion_param) else: raise RuntimeError(f'unknown motion type {motion_param['type']}') return model def create_image(param): image = None if param['type'] == 'vstripe': # Extract image parameters width = param['width'] height = param['height'] number = param['number'] color0 = param['color0'] color1 = param['color1'] # Create empty image image = np.zeros((height, width, 3), dtype=np.uint8) bndry = np.linspace(0, width, 2*number+1, dtype=np.int) bndry_pairs = zip(bndry[:-1], bndry[1:]) for i, pair in enumerate(bndry_pairs): n,m = pair if i%2 == 0: image[:,n:m] = color0 else: image[:,n:m] = color1 elif param['type'] == 'ball': width = param['width'] height = param['height'] color = param['color'] radius = param['radius'] image = np.zeros((height, width, 3), dtype=np.uint8) pos = ( width // 2, height // 2 ) image = cv2.circle(image, pos, radius, color, -1) else: raise RuntimeError(f'unknown image type {param['type']}') return image
import cv2 import numpy as np from . import ref_input class Stimulus: def __init__(self, param): self.param = param self.image = create_image(param['image']) self.motion = self.get_motion_model(param['motion']) self.vel = np.array([0.0, 0.0]) self.pos = np.array([0.0, 0.0]) @property def done(self): return self.motion.done def update(self, t, dt): self.vel = self.motion.velocity(t) self.pos += dt*self.vel def display_image(self, input_pos): rel_pos = self.pos - input_pos image = np.roll(self.image, int(rel_pos[1]), axis=0) image = np.roll(image, int(rel_pos[0]), axis=1) if self.param['image']['type'] == 'ball': width = self.param['image']['width'] height = self.param['image']['height'] radius = int(1.5*self.param['image']['radius']) pos = (width//2, height//2) image = cv2.circle(image, pos, radius, (0,0,255), 5) return image @staticmethod def get_motion_model(motion_param): if motion_param['type'] == 'none': model = ref_input.NoMotion(motion_param) elif motion_param['type'] == 'sin': model = ref_input.Sin(motion_param) elif motion_param['type'] == 'sin_series': model = ref_input.SinSeries(motion_param) elif motion_param['type'] == 'sin_period_series': model = ref_input.SinPeriodSeries(motion_param) elif motion_param['type'] == 'step': model = ref_input.Step(motion_param) elif motion_param['type'] == 'step_series': model = ref_input.StepSeries(motion_param) elif motion_param['type'] == 'step_zero_step': model = ref_input.StepZeroStep(motion_param) elif motion_param['type'] == 'random_step': model = ref_input.RandomStep(motion_param) elif motion_param['type'] == 'cyclic_chirp': model = ref_input.CyclicChirp(motion_param) else: raise RuntimeError(f'unknown motion type {motion_param["type"]}') return model def create_image(param): image = None if param['type'] == 'vstripe': # Extract image parameters width = param['width'] height = param['height'] number = param['number'] color0 = param['color0'] color1 = param['color1'] # Create empty image image = np.zeros((height, width, 3), dtype=np.uint8) bndry = np.linspace(0, width, 2*number+1, dtype=np.int) bndry_pairs = zip(bndry[:-1], bndry[1:]) for i, pair in enumerate(bndry_pairs): n,m = pair if i%2 == 0: image[:,n:m] = color0 else: image[:,n:m] = color1 elif param['type'] == 'ball': width = param['width'] height = param['height'] color = param['color'] radius = param['radius'] image = np.zeros((height, width, 3), dtype=np.uint8) pos = ( width // 2, height // 2 ) image = cv2.circle(image, pos, radius, color, -1) else: raise RuntimeError(f'unknown image type {param["type"]}') return image
from django.shortcuts import render from django.http import HttpResponse from catalog.models import Book, Author, BookInstance, Genre from django.views import generic from django.contrib.auth.decorators import login_required @login_required def index(request): """View function for home page of site.""" # Generate counts of some of the main objects num_books = Book.objects.all().count() num_instances = BookInstance.objects.all().count() # Available books (status = 'a') num_instances_available = BookInstance.objects.filter(status__exact='a').count() # The 'all()' is implied by default. num_authors = Author.objects.count() request.session.setdefault('page_hits', 0) request.session['page_hits'] += 1 print(f'This is request number: {request.session['page_hits']}') from pprint import pprint as pp pp(dict(request.session)) context = { 'num_books': num_books, 'num_instances': num_instances, 'num_instances_available': num_instances_available, 'num_authors': num_authors, 'num_visits': request.session["page_hits"], } # Render the HTML template index.html with the data in the context variable return render(request, 'index.html', context=context) class BookListView(generic.ListView): model = Book paginate_by = 2 # /catalog/books/?page=2. template_name = 'catalog/book_list.html' # '<app_name>/<model>_list.html # context_object_name = 'book_list' # your own name for the list as a template variable # # queryset = Book.objects.filter(title__icontains='war')[:5] # Get 5 books containing the title war # def get_queryset(self): # return Book.objects.filter(title__icontains='war')[:5] # Get 5 books containing the title war # def get_context_data(self, **kwargs): # # Call the base implementation first to get the context # context = super(BookListView, self).get_context_data(**kwargs) # # Create any data and add it to the context # context['some_data'] = 'This is just some data' # return context # def book_detail_view(request, primary_key): # try: # book = Book.objects.get(pk=primary_key) # except Book.DoesNotExist: # raise Http404('Book does not exist') # return render(request, 'catalog/book_detail.html', context={'book': book}) # from django.shortcuts import get_object_or_404 # def book_detail_view(request, primary_key): # book = get_object_or_404(Book, pk=primary_key) # return render(request, 'catalog/book_detail.html', context={'book': book}) class BookDetailView(generic.DetailView): model = Book
from django.shortcuts import render from django.http import HttpResponse from catalog.models import Book, Author, BookInstance, Genre from django.views import generic from django.contrib.auth.decorators import login_required @login_required def index(request): """View function for home page of site.""" # Generate counts of some of the main objects num_books = Book.objects.all().count() num_instances = BookInstance.objects.all().count() # Available books (status = 'a') num_instances_available = BookInstance.objects.filter(status__exact='a').count() # The 'all()' is implied by default. num_authors = Author.objects.count() request.session.setdefault('page_hits', 0) request.session['page_hits'] += 1 print(f'This is request number: {request.session["page_hits"]}') from pprint import pprint as pp pp(dict(request.session)) context = { 'num_books': num_books, 'num_instances': num_instances, 'num_instances_available': num_instances_available, 'num_authors': num_authors, 'num_visits': request.session["page_hits"], } # Render the HTML template index.html with the data in the context variable return render(request, 'index.html', context=context) class BookListView(generic.ListView): model = Book paginate_by = 2 # /catalog/books/?page=2. template_name = 'catalog/book_list.html' # '<app_name>/<model>_list.html # context_object_name = 'book_list' # your own name for the list as a template variable # # queryset = Book.objects.filter(title__icontains='war')[:5] # Get 5 books containing the title war # def get_queryset(self): # return Book.objects.filter(title__icontains='war')[:5] # Get 5 books containing the title war # def get_context_data(self, **kwargs): # # Call the base implementation first to get the context # context = super(BookListView, self).get_context_data(**kwargs) # # Create any data and add it to the context # context['some_data'] = 'This is just some data' # return context # def book_detail_view(request, primary_key): # try: # book = Book.objects.get(pk=primary_key) # except Book.DoesNotExist: # raise Http404('Book does not exist') # return render(request, 'catalog/book_detail.html', context={'book': book}) # from django.shortcuts import get_object_or_404 # def book_detail_view(request, primary_key): # book = get_object_or_404(Book, pk=primary_key) # return render(request, 'catalog/book_detail.html', context={'book': book}) class BookDetailView(generic.DetailView): model = Book
import os import torch import numpy as np import math import scipy from htvlearn.lattice import Lattice from htvlearn.delaunay import Delaunay from htvlearn.grid import Grid class Hex(): """Hexagonal lattice vectors""" v1 = Lattice.hexagonal_matrix[:, 0].numpy() v2 = Lattice.hexagonal_matrix[:, 1].numpy() class BoxSpline(): """Three-directional hexagonal box spline""" center_points = np.array([0., 0.]) border_points = np.array([Hex.v1, Hex.v2, -Hex.v1 + Hex.v2, -Hex.v1, -Hex.v2, -Hex.v2 + Hex.v1]) points = np.vstack((center_points, border_points, 2 * border_points)) values = np.array([math.sqrt(3) / 2, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]) htv = 12 class SimplicialSpline(): """Simplicial spline with randomly positioned vertices""" np.random.seed(3) center_points = np.array([0., 0.]) + np.random.uniform(-0.2, 0.2, (2, )) border_points = np.array([Hex.v1, Hex.v2, -Hex.v1 + Hex.v2, -Hex.v1, -Hex.v2, -Hex.v2 + Hex.v1]) + \ np.random.uniform(-0.2, 0.2, (6, 2)) points = np.vstack((center_points, border_points, 2 * border_points)) values = np.array([math.sqrt(3) / 2, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]) class CutPyramid(): """Pyramid with flat top""" points = np.vstack((BoxSpline.center_points, BoxSpline.border_points, 2 * BoxSpline.border_points, 3 * BoxSpline.border_points)) values = np.array([1., 1., 1., 1., 1., 1., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., ]) htv = 16 * math.sqrt(3) class SimpleJunction(): """A simple two-polytope junction""" points = np.array([[0., 0.], [1., 0.], [0., 1.], [1., 1.], [0., 3. / 4], [1., 1. / 4]]) values = np.array([0., 2. / 3, 2. / 3, 0., 1., 1.]) # gradients of each polytope a1_affine_coeff = np.array([2. / 3, 4. / 3., 0.]) a2_affine_coeff = np.array([-2. / 3, -4. / 3., 2.]) htv = 10. / 3 def init_distorted_grid(size_=(3, 3), range_=(-1, 1)): """ Initialize a distorted grid. Args: size (2-tuple): grid size. range (2-tuple): range of points in each dimension before distortion. Returns: points (np.array): distorted grid points. size: (size_[0]*size_[1]) x 2. """ assert isinstance(size_, tuple) assert len(size_) == 2 # initialize undistorted grid points (u, v) vec1 = np.linspace(*range_, size_[0]) * 1. vec2 = np.linspace(*range_, size_[1]) * 1. u, v = np.meshgrid(vec1, vec2) u = u.flatten() v = v.flatten() # add noise to the interior vertices of the grid mask = np.ma.mask_or(np.abs(u) == u.max(), np.abs(v) == v.max()) points = np.hstack((u[:, np.newaxis], v[:, np.newaxis])).copy() # the noise is scaled according to the grid spacing noise = (np.random.rand(*points.shape) - 0.5) * (u[1] - u[0]) # don't add noise to boundary vertices points[~mask] = points[~mask] + noise[~mask] return points class DistortedGrid: """Dataset with random values in a distorted random grid""" points = init_distorted_grid(size_=(3, 3)) values = (np.random.rand(points.shape[0], ) - 0.5) class Data(): """Data class for algorithms""" def __init__(self, data_from_ckpt=None, dataset_name=None, num_train=None, data_dir='./data', valid_fraction=0.2, test_as_valid=False, non_uniform=False, noise_ratio=0., seed=-1, verbose=False, **kwargs): """ Args: data_from_ckpt (dict): dictionary with 'train', 'valid' and 'test' data loaded from a checkpoint. dataset_name (str) num_train (int): number of training+valid samples. The effective number of training samples is a multiple of 1000. Further, if the dataset has gaps the data inside the gaps will also removed. data_dir (int): data directory (for face dataset) valid_fraction (float [0,1]): fraction of num_train samples that is used for validation test_as_valid (bool): if True, use test set in validation. non_uniform (bool): if True, perform non-uniform data sampling (face dataset only). noise_ratio (float >= 0): noise that should be applied to the samples as a fraction of the data range. seed (int): seed for random generation. If negative, no seed is set. verbose (bool): print more info. """ self.data_from_ckpt = data_from_ckpt self.dataset_name = dataset_name self.num_train = num_train if self.data_from_ckpt is None: assert self.dataset_name is not None if not self.dataset_name.startswith('pyramid'): assert self.num_train is not None self.data_dir = data_dir self.valid_fraction = valid_fraction self.test_as_valid = test_as_valid self.non_uniform = non_uniform self.noise_ratio = noise_ratio self.seed = seed self.verbose = verbose # if not overwritten, computed in add_noise_to_values() # from self.noise_ratio and dataset height range self.noise_std = None if self.seed >= 0: # set seed torch.manual_seed(self.seed) torch.cuda.manual_seed_all(self.seed) np.random.seed(self.seed) self.train, self.valid, self.test = {}, {}, {} self.delaunay = {} # points and values for delaunay triangulation if self.data_from_ckpt is not None: # load data from self.data_from_ckpt assert 'train' in self.data_from_ckpt assert 'valid' in self.data_from_ckpt self.train = self.data_from_ckpt['train'] self.valid = self.data_from_ckpt['valid'] if 'delaunay' in self.data_from_ckpt: assert 'points' in self.data_from_ckpt['delaunay'] assert 'values' in self.data_from_ckpt['delaunay'] self.delaunay['points'] = \ self.data_from_ckpt['delaunay']['points'] self.delaunay['values'] = \ self.data_from_ckpt['delaunay']['values'] self.init_data() def init_data(self): """Initialize cpwl dataset, and train/test/valid sets""" if not bool(self.delaunay): if self.dataset_name.startswith('pyramid'): self.delaunay['points'], self.delaunay['values'] = \ self.init_pyramid() # training is made of all pyramid's points except apex self.train['input'] = \ torch.from_numpy(self.delaunay['points'][:-1]).clone() self.train['values'] = \ torch.from_numpy(self.delaunay['values'][:-1]).clone() # force validation set to be equal to test set self.test_as_valid = True elif self.dataset_name.endswith('planes'): self.delaunay['points'], self.delaunay['values'] = \ self.init_planes() elif 'face' in self.dataset_name: self.delaunay['points'], self.delaunay['values'] = \ self.init_face(self.data_dir, cut=True if 'cut' in self.dataset_name else False) self.cpwl = Delaunay(points=self.delaunay['points'], values=self.delaunay['values']) if not self.cpwl.has_rectangular_range: if self.dataset_name.endswith('planes'): h = (self.cpwl.tri.points[:, 0].max() - self.cpwl.tri.points[:, 0].min()) / 400 self.test['input'] = \ Grid(x1_min=self.cpwl.tri.points[:, 0].min(), x1_max=self.cpwl.tri.points[:, 0].max(), x2_min=self.cpwl.tri.points[:, 1].min(), x2_max=self.cpwl.tri.points[:, 1].max(), h=h, to_numpy=False, to_float32=True).x # discard samples outside convex set idx = self.cpwl.tri.find_simplex(self.test['input']) self.test['input'] = self.test['input'][idx >= 0] else: # generate uniformly distributed samples in cpwl convex set # the final number of test samples will be smaller because # samples outside lattice are discarded nb_samples = 160000 # 400*400 self.test['input'] = \ self.generate_random_samples(nb_samples) else: # test set is sampled on a grid inside the convex hull of cpwl # this gives a test grid 500 x 500 samples self.test['input'] = self.cpwl.get_grid(h=0.0025, to_numpy=False, to_float32=True).x self.test['values'] = self.cpwl.evaluate(self.test['input']) print(f'\nnb. of test data points : {self.test['input'].size(0)}') if (not bool(self.valid)) and (self.test_as_valid is True): self.valid['input'] = self.test['input'].clone() self.valid['values'] = self.test['values'].clone() if not bool(self.train): num_train_valid_samples = int(self.num_train) if self.dataset_name.endswith('planes'): # generate grid in lattice reference x_lat = torch.empty((num_train_valid_samples, 2)) x_lat.uniform_(-0.5, 0.5) # convert to standard coordinates x = (Lattice.hexagonal_matrix @ x_lat.t()).t() elif self.non_uniform is True: hull_points = \ self.cpwl.tri.points[self.cpwl.convex_hull_points_idx] # compute largest distance max_dist = np.amax(np.sqrt(np.sum(hull_points ** 2, axis=1))) # radius r = (torch.empty((num_train_valid_samples, 1)) .uniform_(0., max_dist * 0.8)) # angle theta = (torch.empty((num_train_valid_samples, 1)) .uniform_(0., 2 * np.pi)) # points x = torch.cat((r * theta.cos(), r * theta.sin()), dim=1) # Only keep points inside cpwl convex hull x_simplices_idx = self.cpwl.tri.find_simplex(x) x = x[x_simplices_idx >= 0] else: # generate num_train_valid_samples uniformly distributed # in cpwl convex set x = self.generate_random_samples(num_train_valid_samples) # training / validation split indices if not self.test_as_valid: split_idx = int((1 - self.valid_fraction) * x.size(0)) else: # full training set, validation set = test set split_idx = x.size(0) self.train['input'] = x[0:split_idx] self.train['values'] = self.cpwl.evaluate(self.train['input']) if self.dataset_name.endswith('gaps'): # [(gap_x_min, gap_x_max)...] gap_x_range = [[0.108, 0.234], [-0.07, 0.226], [-0.234, -0.108]] # [(gap_y_min, gap_y_max)...] gap_y_range = [[-0.21, 0.07], [0.19, 0.311], [-0.21, 0.063]] # remove data inside gaps for i in range(len(gap_x_range)): gap_mask = ( (self.train['input'][:, 0] >= gap_x_range[i][0]) * (self.train['input'][:, 0] <= gap_x_range[i][1]) * (self.train['input'][:, 1] >= gap_y_range[i][0]) * (self.train['input'][:, 1] <= gap_y_range[i][1])) self.train['input'] = self.train['input'][~gap_mask] self.train['values'] = self.train['values'][~gap_mask] if not np.allclose(self.noise_ratio, 0.): # add noise to training data self.train['values'] = \ self.add_noise_to_values(self.train['values']) if self.train['input'].size(0) >= 3000: # effective number of samples (rounded to 1000) num = int(np.floor(self.train['input'].size(0) / 1000.) * 1000) idx = torch.randperm(self.train['input'].size(0))[:num] self.train['input'] = self.train['input'][idx] self.train['values'] = self.train['values'][idx] print('nb. of training data points : ' f'{self.train['input'].size(0)}') if not bool(self.valid): self.valid['input'] = x[(split_idx + 1)::] self.valid['values'] = \ self.cpwl.evaluate(self.valid['input']) @staticmethod def add_lattice_vertices(points, values, eps=0.): """Add lattice vertices (up to eps distance away) Args: points (torch.Tensor or np.ndarray): size (m, 2) values (torch.Tensor or np.ndarray): size (m,) eps (float): buffer distance from boundaries of lattice. """ nparray = False if isinstance(points, np.ndarray): nparray = True # convert to torch points = torch.from_numpy(points) values = torch.from_numpy(values) # add lattice corners br = Lattice.bottom_right_std ur = Lattice.upper_right_std a, b = eps * np.sqrt(3) / 2., eps * .5 lat_points = \ torch.tensor([[-ur[0] + a, -ur[1] + b], [br[0] - b, br[1] + a], [-br[0] + b, -br[1] - a], [ur[0] - a, ur[1] - b]]) points = torch.cat((points, lat_points), dim=0) values = torch.cat((values, torch.zeros(4))) if nparray is True: # convert to numpy points = points.numpy() values = values.numpy() return points, values def generate_random_samples(self, num_samples): """ Generate uniformly distributed data inside convex set. Works by generating num_samples points and then rejecting the ones outside the convex set. Args: num_samples (int) (before possible rejection) Returns: x (torch.tensor) """ x = torch.empty((num_samples, 2)) x[:, 0].uniform_(self.cpwl.tri.points[:, 0].min(), self.cpwl.tri.points[:, 0].max()) x[:, 1].uniform_(self.cpwl.tri.points[:, 1].min(), self.cpwl.tri.points[:, 1].max()) # reject samples outside convex set idx = self.cpwl.tri.find_simplex(x) x = x[idx >= 0] return x def add_noise_to_values(self, values): """ Add gaussian noise to values. if self.noise_std exists, it is used as the noise standard deviation, otherwise noise_std is computed from self.noise_ratio and the data height range. Args: values (torch.tensor): values to add noise to. Returns the noisy values. """ noise_std = self.noise_std if noise_std is None: noise_std = self.noise_ratio * (values.max() - values.min()) if self.verbose: print('Adding noise of standard deviation ' 'sigma = {:.2E}'.format(noise_std)) noise = torch.empty_like(values).normal_(std=noise_std) return values + noise @staticmethod def init_pyramid(): """ Initialize the pyramid dataset. Returns: points (np.array): size (M, 2). values (np.array): size (M,) """ # points in lattice coordinates h = 0.1 points = torch.tensor([[2 * h, 0.], [0., 2 * h], [2 * h, -2 * h], [0., -2 * h], [-2 * h, 0.], [-2 * h, 2 * h], [h, 0.], [0., h], [h, -h], [0., -h], [-h, 0.], [-h, h], [0., 0.]]) # last element -> apex values = torch.tensor([.0, .0, .0, .0, .0, .0, .1, .1, .1, .1, .1, .1, .2]) # convert to standard coordinates points = (Lattice.hexagonal_matrix @ points.t()).t() return points.numpy(), values.numpy() @classmethod def init_zero_boundary_planes(cls): """ Initialize the planes dataset with zero boundaries. Returns: points (torch.tensor): size (M, 2). values (torch.tensor): size (M,) """ # fit planes function in the lattice pad = 0.08 x_min, _, x_max, _ = cls.get_data_boundaries(hw_ratio=0.01, pad=pad) _, y_min, _, y_max = cls.get_data_boundaries(hw_ratio=100, pad=pad) dx = (x_max - x_min) / 100 # delta x step dy = (y_max - y_min) / 100 # delta y step # control points with values - (x1, x2, val) vert = \ torch.tensor([[x_min + 30 * dx, y_min + 35 * dy, dx * 20], # 0 [x_max - 40 * dx, y_min + 30 * dy, dx * 20], # 1 [x_max - 35 * dx, y_max - 30 * dy, dx * 20], # 2 [x_min + 40 * dx, y_max - 30 * dy, dx * 20], # 3 [x_max - 25 * dx, y_min + 5 * dy, 0.], # 4 [x_min + 25 * dx, y_max - 5 * dy, 0.]]) # 5 # auxiliary triangulation of the function # size (num_simplices, vertices) simplices = torch.tensor([[0, 1, 3], [1, 2, 3], [4, 1, 0], [0, 3, 5], [4, 2, 1], [3, 2, 5]]) # check values of vertices so that there is a seamless plane junction x_v6 = cls.get_zero_loc(vert, simplices, 2, 3) x_v7 = cls.get_zero_loc(vert, simplices, 4, 5) br = Lattice.bottom_right_std ur = Lattice.upper_right_std # add x_v6, x_v7, and lattice corners new_vert = torch.tensor([[x_v6[0], x_v6[1], 0.], # 6 [x_v7[0], x_v7[1], 0.], # 7 [-ur[0], -ur[1], 0.], # 8 [br[0], br[1], 0.], # 9 [-br[0], -br[1], 0.], # 10 [ur[0], ur[1], 0.]]) # 11 vert = torch.cat((vert, new_vert), dim=0) points, values = vert[:, 0:2], vert[:, 2] return points, values @staticmethod def add_linear_func(points, values): """ Add a linear term to the dataset. Args: points (torch.tensor): size (M, 2). values (torch.tensor): size (M,) Returns: values (torch.tensor): size (M,). """ # add linear term to vertices a = torch.tensor([0.1, 0.05]) b = torch.tensor([-0.05]) values += (points * a.unsqueeze(0)).sum(1) + b return values def init_planes(self): """ Initialize the planes dataset. Set self.noise_std. Returns: points (torch.tensor): size (M, 2). values (torch.tensor): size (M,) """ # initialize planes dataset with zero boundaries points, values = self.init_zero_boundary_planes() # overwrite noise standard deviation self.noise_std = (self.noise_ratio * values.max()) # add linear function to dataset values = self.add_linear_func(points, values) # convert to numpy points, values = points.numpy(), values.numpy() return points, values @staticmethod def get_zero_loc(vert, simplices, idx1, idx2): """ Get zero locations of vertices for a seamless junction of the planes. Args: vert (np.array): size: (M, 3) (points in the first two columns, values in the third) simplices (np.array): indexes of vertices for each simplex (row). size: (P, 3). idx1, idx2 (int>=0): indices of simplices to join. Returns: x (torch.tensor): size (2,) """ # size (2, 3, 3) idx_vec = [idx1, idx2] simplices_vert = \ torch.cat(tuple(vert[simplices[i]].unsqueeze(0) for i in idx_vec), dim=0) plane_coeff = Lattice.solve_method(simplices_vert) affine_coeff = Lattice.get_affine_coeff_from_plane_coeff(plane_coeff) assert affine_coeff.size() == (2, 3) B = -affine_coeff[:, -1:] A = affine_coeff[:, 0:2] x = torch.linalg.solve(A, B) return x.squeeze(-1) @staticmethod def read_face(data_dir, cut_eps=0.6): """ Read the 3D face dataset and construct a function from it by cutting and eliminating duplicates. Args: cut_eps (float in [0,1]): what height to cut face relative to its maximum height. Returns: cleaned_vert (np.array): with vertices below cut_eps and duplicates removed and zero mean. size: (M, 3) (points in the first two columns, values in the third) """ obj_file = os.path.join(data_dir, 'obj_free_male_head.obj') V = [] with open(obj_file, "r") as file1: for line in file1.readlines(): f_list = [i for i in line.split(" ") if i.strip()] if len(f_list) == 0: continue if f_list[0] != 'v': continue V += [float(i) for i in f_list[1::]] # vertices vert = np.array(V).reshape(-1, 3) # sort vertices by z coordinates in descending direction sort_vert = vert[vert[:, 2].argsort()][::-1] # get unique_idx of first occurences (largest height) _, unique_dx = np.unique(sort_vert[:, 0:2], return_index=True, axis=0) unique_sort_vert = sort_vert[unique_dx] # eliminate vertices whose height is below cutoff min_height = unique_sort_vert[:, 2].min() max_height = unique_sort_vert[:, 2].max() cutoff_val = min_height + (max_height - min_height) * cut_eps cutoff_mask = np.where(unique_sort_vert[:, 2] > cutoff_val)[0] cleaned_vert = unique_sort_vert[cutoff_mask] cleaned_vert[:, 2] = cleaned_vert[:, 2] - \ cutoff_val # shift z.min() to z = 0 x_mean = cleaned_vert[:, 0].min() / 2. + cleaned_vert[:, 0].max() / 2. y_mean = cleaned_vert[:, 1].min() / 2. + cleaned_vert[:, 1].max() / 2. cleaned_vert[:, 0] = cleaned_vert[:, 0] - x_mean # shift x around 0 cleaned_vert[:, 1] = cleaned_vert[:, 1] - y_mean # shift t around 0 return cleaned_vert @classmethod def init_face(cls, data_dir, cut=False): """ Initialize the face dataset. Args: cut (bool): if True, use only a smaller section of the face. Otherwise, use full face with zero boundaries. Returns: points (torch.tensor): size (M, 2). values (torch.tensor): size (M,) """ vert = cls.read_face(data_dir) # normalize face to fit in [-0.8, 0.8]^2 square max_ = max(np.abs(vert[:, 0]).max(), np.abs(vert[:, 1]).max()) vert = vert / max_ * 0.8 if cut is True: # cut a smaller portion of the face cpwl_aux = Delaunay(points=vert[:, 0:2].copy(), values=vert[:, 2].copy()) x_min, x_max = -0.324, 0.324 y_min, y_max = -0.45, 0.419 mask = (vert[:, 0] > x_min) * (vert[:, 0] < x_max) * \ (vert[:, 1] > y_min) * (vert[:, 1] < y_max) vert = vert[mask] # add extreme points of the convex hull to vertices hull_points = np.array([[x_min, y_min], [x_max, y_min], [x_max, y_max], [x_min, y_max]]) hull_values = cpwl_aux.evaluate(hull_points) new_vertices = np.concatenate( (hull_points, hull_values[:, np.newaxis]), axis=1) vert = np.concatenate((vert, new_vertices), axis=0) else: points = vert[:, 0:2] hull = scipy.spatial.ConvexHull(points) hull_points = points[hull.vertices] # add points along the convex hull for i in range(hull_points.shape[0]): frac = np.linspace(0.01, 0.99, num=99)[:, np.newaxis] next_vert = i + 1 if i != hull_points.shape[0] - 1 else 0 new_points = hull_points[next_vert][np.newaxis, :] * frac + \ hull_points[i][np.newaxis, :] * (1 - frac) if cut is True: # evaluate on convex hull of face new_values = cpwl_aux.evaluate(new_points) else: # add zeros around face (to its convex hull contour) new_values = np.zeros(new_points.shape[0]) new_vertices = np.concatenate( (new_points, new_values[:, np.newaxis]), axis=1) vert = np.concatenate((vert, new_vertices), axis=0) if cut is False: # create grid of points with zero value around face h = 0.01 x_r = vert[:, 0].max() * 10. / 8. y_r = vert[:, 1].max() * 9.5 / 8. fine_grid = Grid(x1_min=-x_r, x1_max=x_r + h, x2_min=-y_r, x2_max=y_r + h, h=h, to_float32=True).x # only retain points outside face convex hull aux_delaunay = scipy.spatial.Delaunay(points) fine_grid = fine_grid[aux_delaunay.find_simplex(fine_grid) < 0] # add zeros around face new_vertices = np.concatenate( (fine_grid, np.zeros((fine_grid.shape[0], 1))), axis=1) vert = np.concatenate((vert, new_vertices), axis=0) vert = cls.fit_in_lattice(vert) points, values = vert[:, 0:2], vert[:, 2] return points, values @classmethod def fit_in_lattice(cls, vert): """ Fit points in lattice. Args: vert (np.array): size: (M, 3) (points in the first two columns, values in the third) Returns: vert (np.array): scaled vertices that fit in lattice. """ # normalize face to fit in lattice hw_ratio = (vert[:, 1].max() - vert[:, 1].min()) / \ (vert[:, 0].max() - vert[:, 0].min()) _, _, x_max, y_max = cls.get_data_boundaries(hw_ratio=hw_ratio, pad=0.03) # recenter data x_mean = (vert[:, 0].max() + vert[:, 0].min()) / 2 y_mean = (vert[:, 1].max() + vert[:, 1].min()) / 2 vert[:, 0] = vert[:, 0] - x_mean vert[:, 1] = vert[:, 1] - y_mean # x,y scaling factors # vert[i,0] should be within (-x_max, x_max) # vert[i,1] should be within (-y_max, y_max) x_norm = x_max / vert[:, 0].max() y_norm = y_max / vert[:, 1].max() if x_norm < y_norm: vert = vert * x_norm else: vert = vert * y_norm return vert @staticmethod def get_data_boundaries(hw_ratio=math.sqrt(3), pad=0.1): """ Get the data boundaries that allow fitting the data in centered rectangular region of the lattice with a specified height/width ratio, so as to maximize occupied space within the interior lattice. Pad a given distance from the limits if pad > 0. Takes into account geometry of hexagonal lattice: if hw_ratio > math.sqrt(3), the data touches the upper and bottom interior border; otherwise, it touch the left and right borders. Args: hw_ratio (float>0): height/width ratio of rectangular region. pad (float>=0): distance to pad from the limits of the region. Returns: 4-tuple (x_min, x_max, y_min, y_max): data boundaries """ # requires that lattice is hexagonal and lsize*h = 1 (enforced) bottom_right_std = Lattice.bottom_right_std if hw_ratio > math.sqrt(3): # from geometry maximize space usage y_min = bottom_right_std[1] x_min = y_min * (1. / hw_ratio) else: a = (bottom_right_std[0] * 2) / (1 + hw_ratio * math.sqrt(3) / 3) x_min = -a y_min = x_min * hw_ratio x_min, y_min = x_min + pad, y_min + pad x_max, y_max = -x_min, -y_min return x_min.item(), y_min.item(), x_max.item(), y_max.item()
import os import torch import numpy as np import math import scipy from htvlearn.lattice import Lattice from htvlearn.delaunay import Delaunay from htvlearn.grid import Grid class Hex(): """Hexagonal lattice vectors""" v1 = Lattice.hexagonal_matrix[:, 0].numpy() v2 = Lattice.hexagonal_matrix[:, 1].numpy() class BoxSpline(): """Three-directional hexagonal box spline""" center_points = np.array([0., 0.]) border_points = np.array([Hex.v1, Hex.v2, -Hex.v1 + Hex.v2, -Hex.v1, -Hex.v2, -Hex.v2 + Hex.v1]) points = np.vstack((center_points, border_points, 2 * border_points)) values = np.array([math.sqrt(3) / 2, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]) htv = 12 class SimplicialSpline(): """Simplicial spline with randomly positioned vertices""" np.random.seed(3) center_points = np.array([0., 0.]) + np.random.uniform(-0.2, 0.2, (2, )) border_points = np.array([Hex.v1, Hex.v2, -Hex.v1 + Hex.v2, -Hex.v1, -Hex.v2, -Hex.v2 + Hex.v1]) + \ np.random.uniform(-0.2, 0.2, (6, 2)) points = np.vstack((center_points, border_points, 2 * border_points)) values = np.array([math.sqrt(3) / 2, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]) class CutPyramid(): """Pyramid with flat top""" points = np.vstack((BoxSpline.center_points, BoxSpline.border_points, 2 * BoxSpline.border_points, 3 * BoxSpline.border_points)) values = np.array([1., 1., 1., 1., 1., 1., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., ]) htv = 16 * math.sqrt(3) class SimpleJunction(): """A simple two-polytope junction""" points = np.array([[0., 0.], [1., 0.], [0., 1.], [1., 1.], [0., 3. / 4], [1., 1. / 4]]) values = np.array([0., 2. / 3, 2. / 3, 0., 1., 1.]) # gradients of each polytope a1_affine_coeff = np.array([2. / 3, 4. / 3., 0.]) a2_affine_coeff = np.array([-2. / 3, -4. / 3., 2.]) htv = 10. / 3 def init_distorted_grid(size_=(3, 3), range_=(-1, 1)): """ Initialize a distorted grid. Args: size (2-tuple): grid size. range (2-tuple): range of points in each dimension before distortion. Returns: points (np.array): distorted grid points. size: (size_[0]*size_[1]) x 2. """ assert isinstance(size_, tuple) assert len(size_) == 2 # initialize undistorted grid points (u, v) vec1 = np.linspace(*range_, size_[0]) * 1. vec2 = np.linspace(*range_, size_[1]) * 1. u, v = np.meshgrid(vec1, vec2) u = u.flatten() v = v.flatten() # add noise to the interior vertices of the grid mask = np.ma.mask_or(np.abs(u) == u.max(), np.abs(v) == v.max()) points = np.hstack((u[:, np.newaxis], v[:, np.newaxis])).copy() # the noise is scaled according to the grid spacing noise = (np.random.rand(*points.shape) - 0.5) * (u[1] - u[0]) # don't add noise to boundary vertices points[~mask] = points[~mask] + noise[~mask] return points class DistortedGrid: """Dataset with random values in a distorted random grid""" points = init_distorted_grid(size_=(3, 3)) values = (np.random.rand(points.shape[0], ) - 0.5) class Data(): """Data class for algorithms""" def __init__(self, data_from_ckpt=None, dataset_name=None, num_train=None, data_dir='./data', valid_fraction=0.2, test_as_valid=False, non_uniform=False, noise_ratio=0., seed=-1, verbose=False, **kwargs): """ Args: data_from_ckpt (dict): dictionary with 'train', 'valid' and 'test' data loaded from a checkpoint. dataset_name (str) num_train (int): number of training+valid samples. The effective number of training samples is a multiple of 1000. Further, if the dataset has gaps the data inside the gaps will also removed. data_dir (int): data directory (for face dataset) valid_fraction (float [0,1]): fraction of num_train samples that is used for validation test_as_valid (bool): if True, use test set in validation. non_uniform (bool): if True, perform non-uniform data sampling (face dataset only). noise_ratio (float >= 0): noise that should be applied to the samples as a fraction of the data range. seed (int): seed for random generation. If negative, no seed is set. verbose (bool): print more info. """ self.data_from_ckpt = data_from_ckpt self.dataset_name = dataset_name self.num_train = num_train if self.data_from_ckpt is None: assert self.dataset_name is not None if not self.dataset_name.startswith('pyramid'): assert self.num_train is not None self.data_dir = data_dir self.valid_fraction = valid_fraction self.test_as_valid = test_as_valid self.non_uniform = non_uniform self.noise_ratio = noise_ratio self.seed = seed self.verbose = verbose # if not overwritten, computed in add_noise_to_values() # from self.noise_ratio and dataset height range self.noise_std = None if self.seed >= 0: # set seed torch.manual_seed(self.seed) torch.cuda.manual_seed_all(self.seed) np.random.seed(self.seed) self.train, self.valid, self.test = {}, {}, {} self.delaunay = {} # points and values for delaunay triangulation if self.data_from_ckpt is not None: # load data from self.data_from_ckpt assert 'train' in self.data_from_ckpt assert 'valid' in self.data_from_ckpt self.train = self.data_from_ckpt['train'] self.valid = self.data_from_ckpt['valid'] if 'delaunay' in self.data_from_ckpt: assert 'points' in self.data_from_ckpt['delaunay'] assert 'values' in self.data_from_ckpt['delaunay'] self.delaunay['points'] = \ self.data_from_ckpt['delaunay']['points'] self.delaunay['values'] = \ self.data_from_ckpt['delaunay']['values'] self.init_data() def init_data(self): """Initialize cpwl dataset, and train/test/valid sets""" if not bool(self.delaunay): if self.dataset_name.startswith('pyramid'): self.delaunay['points'], self.delaunay['values'] = \ self.init_pyramid() # training is made of all pyramid's points except apex self.train['input'] = \ torch.from_numpy(self.delaunay['points'][:-1]).clone() self.train['values'] = \ torch.from_numpy(self.delaunay['values'][:-1]).clone() # force validation set to be equal to test set self.test_as_valid = True elif self.dataset_name.endswith('planes'): self.delaunay['points'], self.delaunay['values'] = \ self.init_planes() elif 'face' in self.dataset_name: self.delaunay['points'], self.delaunay['values'] = \ self.init_face(self.data_dir, cut=True if 'cut' in self.dataset_name else False) self.cpwl = Delaunay(points=self.delaunay['points'], values=self.delaunay['values']) if not self.cpwl.has_rectangular_range: if self.dataset_name.endswith('planes'): h = (self.cpwl.tri.points[:, 0].max() - self.cpwl.tri.points[:, 0].min()) / 400 self.test['input'] = \ Grid(x1_min=self.cpwl.tri.points[:, 0].min(), x1_max=self.cpwl.tri.points[:, 0].max(), x2_min=self.cpwl.tri.points[:, 1].min(), x2_max=self.cpwl.tri.points[:, 1].max(), h=h, to_numpy=False, to_float32=True).x # discard samples outside convex set idx = self.cpwl.tri.find_simplex(self.test['input']) self.test['input'] = self.test['input'][idx >= 0] else: # generate uniformly distributed samples in cpwl convex set # the final number of test samples will be smaller because # samples outside lattice are discarded nb_samples = 160000 # 400*400 self.test['input'] = \ self.generate_random_samples(nb_samples) else: # test set is sampled on a grid inside the convex hull of cpwl # this gives a test grid 500 x 500 samples self.test['input'] = self.cpwl.get_grid(h=0.0025, to_numpy=False, to_float32=True).x self.test['values'] = self.cpwl.evaluate(self.test['input']) print(f'\nnb. of test data points : {self.test["input"].size(0)}') if (not bool(self.valid)) and (self.test_as_valid is True): self.valid['input'] = self.test['input'].clone() self.valid['values'] = self.test['values'].clone() if not bool(self.train): num_train_valid_samples = int(self.num_train) if self.dataset_name.endswith('planes'): # generate grid in lattice reference x_lat = torch.empty((num_train_valid_samples, 2)) x_lat.uniform_(-0.5, 0.5) # convert to standard coordinates x = (Lattice.hexagonal_matrix @ x_lat.t()).t() elif self.non_uniform is True: hull_points = \ self.cpwl.tri.points[self.cpwl.convex_hull_points_idx] # compute largest distance max_dist = np.amax(np.sqrt(np.sum(hull_points ** 2, axis=1))) # radius r = (torch.empty((num_train_valid_samples, 1)) .uniform_(0., max_dist * 0.8)) # angle theta = (torch.empty((num_train_valid_samples, 1)) .uniform_(0., 2 * np.pi)) # points x = torch.cat((r * theta.cos(), r * theta.sin()), dim=1) # Only keep points inside cpwl convex hull x_simplices_idx = self.cpwl.tri.find_simplex(x) x = x[x_simplices_idx >= 0] else: # generate num_train_valid_samples uniformly distributed # in cpwl convex set x = self.generate_random_samples(num_train_valid_samples) # training / validation split indices if not self.test_as_valid: split_idx = int((1 - self.valid_fraction) * x.size(0)) else: # full training set, validation set = test set split_idx = x.size(0) self.train['input'] = x[0:split_idx] self.train['values'] = self.cpwl.evaluate(self.train['input']) if self.dataset_name.endswith('gaps'): # [(gap_x_min, gap_x_max)...] gap_x_range = [[0.108, 0.234], [-0.07, 0.226], [-0.234, -0.108]] # [(gap_y_min, gap_y_max)...] gap_y_range = [[-0.21, 0.07], [0.19, 0.311], [-0.21, 0.063]] # remove data inside gaps for i in range(len(gap_x_range)): gap_mask = ( (self.train['input'][:, 0] >= gap_x_range[i][0]) * (self.train['input'][:, 0] <= gap_x_range[i][1]) * (self.train['input'][:, 1] >= gap_y_range[i][0]) * (self.train['input'][:, 1] <= gap_y_range[i][1])) self.train['input'] = self.train['input'][~gap_mask] self.train['values'] = self.train['values'][~gap_mask] if not np.allclose(self.noise_ratio, 0.): # add noise to training data self.train['values'] = \ self.add_noise_to_values(self.train['values']) if self.train['input'].size(0) >= 3000: # effective number of samples (rounded to 1000) num = int(np.floor(self.train['input'].size(0) / 1000.) * 1000) idx = torch.randperm(self.train['input'].size(0))[:num] self.train['input'] = self.train['input'][idx] self.train['values'] = self.train['values'][idx] print('nb. of training data points : ' f'{self.train["input"].size(0)}') if not bool(self.valid): self.valid['input'] = x[(split_idx + 1)::] self.valid['values'] = \ self.cpwl.evaluate(self.valid['input']) @staticmethod def add_lattice_vertices(points, values, eps=0.): """Add lattice vertices (up to eps distance away) Args: points (torch.Tensor or np.ndarray): size (m, 2) values (torch.Tensor or np.ndarray): size (m,) eps (float): buffer distance from boundaries of lattice. """ nparray = False if isinstance(points, np.ndarray): nparray = True # convert to torch points = torch.from_numpy(points) values = torch.from_numpy(values) # add lattice corners br = Lattice.bottom_right_std ur = Lattice.upper_right_std a, b = eps * np.sqrt(3) / 2., eps * .5 lat_points = \ torch.tensor([[-ur[0] + a, -ur[1] + b], [br[0] - b, br[1] + a], [-br[0] + b, -br[1] - a], [ur[0] - a, ur[1] - b]]) points = torch.cat((points, lat_points), dim=0) values = torch.cat((values, torch.zeros(4))) if nparray is True: # convert to numpy points = points.numpy() values = values.numpy() return points, values def generate_random_samples(self, num_samples): """ Generate uniformly distributed data inside convex set. Works by generating num_samples points and then rejecting the ones outside the convex set. Args: num_samples (int) (before possible rejection) Returns: x (torch.tensor) """ x = torch.empty((num_samples, 2)) x[:, 0].uniform_(self.cpwl.tri.points[:, 0].min(), self.cpwl.tri.points[:, 0].max()) x[:, 1].uniform_(self.cpwl.tri.points[:, 1].min(), self.cpwl.tri.points[:, 1].max()) # reject samples outside convex set idx = self.cpwl.tri.find_simplex(x) x = x[idx >= 0] return x def add_noise_to_values(self, values): """ Add gaussian noise to values. if self.noise_std exists, it is used as the noise standard deviation, otherwise noise_std is computed from self.noise_ratio and the data height range. Args: values (torch.tensor): values to add noise to. Returns the noisy values. """ noise_std = self.noise_std if noise_std is None: noise_std = self.noise_ratio * (values.max() - values.min()) if self.verbose: print('Adding noise of standard deviation ' 'sigma = {:.2E}'.format(noise_std)) noise = torch.empty_like(values).normal_(std=noise_std) return values + noise @staticmethod def init_pyramid(): """ Initialize the pyramid dataset. Returns: points (np.array): size (M, 2). values (np.array): size (M,) """ # points in lattice coordinates h = 0.1 points = torch.tensor([[2 * h, 0.], [0., 2 * h], [2 * h, -2 * h], [0., -2 * h], [-2 * h, 0.], [-2 * h, 2 * h], [h, 0.], [0., h], [h, -h], [0., -h], [-h, 0.], [-h, h], [0., 0.]]) # last element -> apex values = torch.tensor([.0, .0, .0, .0, .0, .0, .1, .1, .1, .1, .1, .1, .2]) # convert to standard coordinates points = (Lattice.hexagonal_matrix @ points.t()).t() return points.numpy(), values.numpy() @classmethod def init_zero_boundary_planes(cls): """ Initialize the planes dataset with zero boundaries. Returns: points (torch.tensor): size (M, 2). values (torch.tensor): size (M,) """ # fit planes function in the lattice pad = 0.08 x_min, _, x_max, _ = cls.get_data_boundaries(hw_ratio=0.01, pad=pad) _, y_min, _, y_max = cls.get_data_boundaries(hw_ratio=100, pad=pad) dx = (x_max - x_min) / 100 # delta x step dy = (y_max - y_min) / 100 # delta y step # control points with values - (x1, x2, val) vert = \ torch.tensor([[x_min + 30 * dx, y_min + 35 * dy, dx * 20], # 0 [x_max - 40 * dx, y_min + 30 * dy, dx * 20], # 1 [x_max - 35 * dx, y_max - 30 * dy, dx * 20], # 2 [x_min + 40 * dx, y_max - 30 * dy, dx * 20], # 3 [x_max - 25 * dx, y_min + 5 * dy, 0.], # 4 [x_min + 25 * dx, y_max - 5 * dy, 0.]]) # 5 # auxiliary triangulation of the function # size (num_simplices, vertices) simplices = torch.tensor([[0, 1, 3], [1, 2, 3], [4, 1, 0], [0, 3, 5], [4, 2, 1], [3, 2, 5]]) # check values of vertices so that there is a seamless plane junction x_v6 = cls.get_zero_loc(vert, simplices, 2, 3) x_v7 = cls.get_zero_loc(vert, simplices, 4, 5) br = Lattice.bottom_right_std ur = Lattice.upper_right_std # add x_v6, x_v7, and lattice corners new_vert = torch.tensor([[x_v6[0], x_v6[1], 0.], # 6 [x_v7[0], x_v7[1], 0.], # 7 [-ur[0], -ur[1], 0.], # 8 [br[0], br[1], 0.], # 9 [-br[0], -br[1], 0.], # 10 [ur[0], ur[1], 0.]]) # 11 vert = torch.cat((vert, new_vert), dim=0) points, values = vert[:, 0:2], vert[:, 2] return points, values @staticmethod def add_linear_func(points, values): """ Add a linear term to the dataset. Args: points (torch.tensor): size (M, 2). values (torch.tensor): size (M,) Returns: values (torch.tensor): size (M,). """ # add linear term to vertices a = torch.tensor([0.1, 0.05]) b = torch.tensor([-0.05]) values += (points * a.unsqueeze(0)).sum(1) + b return values def init_planes(self): """ Initialize the planes dataset. Set self.noise_std. Returns: points (torch.tensor): size (M, 2). values (torch.tensor): size (M,) """ # initialize planes dataset with zero boundaries points, values = self.init_zero_boundary_planes() # overwrite noise standard deviation self.noise_std = (self.noise_ratio * values.max()) # add linear function to dataset values = self.add_linear_func(points, values) # convert to numpy points, values = points.numpy(), values.numpy() return points, values @staticmethod def get_zero_loc(vert, simplices, idx1, idx2): """ Get zero locations of vertices for a seamless junction of the planes. Args: vert (np.array): size: (M, 3) (points in the first two columns, values in the third) simplices (np.array): indexes of vertices for each simplex (row). size: (P, 3). idx1, idx2 (int>=0): indices of simplices to join. Returns: x (torch.tensor): size (2,) """ # size (2, 3, 3) idx_vec = [idx1, idx2] simplices_vert = \ torch.cat(tuple(vert[simplices[i]].unsqueeze(0) for i in idx_vec), dim=0) plane_coeff = Lattice.solve_method(simplices_vert) affine_coeff = Lattice.get_affine_coeff_from_plane_coeff(plane_coeff) assert affine_coeff.size() == (2, 3) B = -affine_coeff[:, -1:] A = affine_coeff[:, 0:2] x = torch.linalg.solve(A, B) return x.squeeze(-1) @staticmethod def read_face(data_dir, cut_eps=0.6): """ Read the 3D face dataset and construct a function from it by cutting and eliminating duplicates. Args: cut_eps (float in [0,1]): what height to cut face relative to its maximum height. Returns: cleaned_vert (np.array): with vertices below cut_eps and duplicates removed and zero mean. size: (M, 3) (points in the first two columns, values in the third) """ obj_file = os.path.join(data_dir, 'obj_free_male_head.obj') V = [] with open(obj_file, "r") as file1: for line in file1.readlines(): f_list = [i for i in line.split(" ") if i.strip()] if len(f_list) == 0: continue if f_list[0] != 'v': continue V += [float(i) for i in f_list[1::]] # vertices vert = np.array(V).reshape(-1, 3) # sort vertices by z coordinates in descending direction sort_vert = vert[vert[:, 2].argsort()][::-1] # get unique_idx of first occurences (largest height) _, unique_dx = np.unique(sort_vert[:, 0:2], return_index=True, axis=0) unique_sort_vert = sort_vert[unique_dx] # eliminate vertices whose height is below cutoff min_height = unique_sort_vert[:, 2].min() max_height = unique_sort_vert[:, 2].max() cutoff_val = min_height + (max_height - min_height) * cut_eps cutoff_mask = np.where(unique_sort_vert[:, 2] > cutoff_val)[0] cleaned_vert = unique_sort_vert[cutoff_mask] cleaned_vert[:, 2] = cleaned_vert[:, 2] - \ cutoff_val # shift z.min() to z = 0 x_mean = cleaned_vert[:, 0].min() / 2. + cleaned_vert[:, 0].max() / 2. y_mean = cleaned_vert[:, 1].min() / 2. + cleaned_vert[:, 1].max() / 2. cleaned_vert[:, 0] = cleaned_vert[:, 0] - x_mean # shift x around 0 cleaned_vert[:, 1] = cleaned_vert[:, 1] - y_mean # shift t around 0 return cleaned_vert @classmethod def init_face(cls, data_dir, cut=False): """ Initialize the face dataset. Args: cut (bool): if True, use only a smaller section of the face. Otherwise, use full face with zero boundaries. Returns: points (torch.tensor): size (M, 2). values (torch.tensor): size (M,) """ vert = cls.read_face(data_dir) # normalize face to fit in [-0.8, 0.8]^2 square max_ = max(np.abs(vert[:, 0]).max(), np.abs(vert[:, 1]).max()) vert = vert / max_ * 0.8 if cut is True: # cut a smaller portion of the face cpwl_aux = Delaunay(points=vert[:, 0:2].copy(), values=vert[:, 2].copy()) x_min, x_max = -0.324, 0.324 y_min, y_max = -0.45, 0.419 mask = (vert[:, 0] > x_min) * (vert[:, 0] < x_max) * \ (vert[:, 1] > y_min) * (vert[:, 1] < y_max) vert = vert[mask] # add extreme points of the convex hull to vertices hull_points = np.array([[x_min, y_min], [x_max, y_min], [x_max, y_max], [x_min, y_max]]) hull_values = cpwl_aux.evaluate(hull_points) new_vertices = np.concatenate( (hull_points, hull_values[:, np.newaxis]), axis=1) vert = np.concatenate((vert, new_vertices), axis=0) else: points = vert[:, 0:2] hull = scipy.spatial.ConvexHull(points) hull_points = points[hull.vertices] # add points along the convex hull for i in range(hull_points.shape[0]): frac = np.linspace(0.01, 0.99, num=99)[:, np.newaxis] next_vert = i + 1 if i != hull_points.shape[0] - 1 else 0 new_points = hull_points[next_vert][np.newaxis, :] * frac + \ hull_points[i][np.newaxis, :] * (1 - frac) if cut is True: # evaluate on convex hull of face new_values = cpwl_aux.evaluate(new_points) else: # add zeros around face (to its convex hull contour) new_values = np.zeros(new_points.shape[0]) new_vertices = np.concatenate( (new_points, new_values[:, np.newaxis]), axis=1) vert = np.concatenate((vert, new_vertices), axis=0) if cut is False: # create grid of points with zero value around face h = 0.01 x_r = vert[:, 0].max() * 10. / 8. y_r = vert[:, 1].max() * 9.5 / 8. fine_grid = Grid(x1_min=-x_r, x1_max=x_r + h, x2_min=-y_r, x2_max=y_r + h, h=h, to_float32=True).x # only retain points outside face convex hull aux_delaunay = scipy.spatial.Delaunay(points) fine_grid = fine_grid[aux_delaunay.find_simplex(fine_grid) < 0] # add zeros around face new_vertices = np.concatenate( (fine_grid, np.zeros((fine_grid.shape[0], 1))), axis=1) vert = np.concatenate((vert, new_vertices), axis=0) vert = cls.fit_in_lattice(vert) points, values = vert[:, 0:2], vert[:, 2] return points, values @classmethod def fit_in_lattice(cls, vert): """ Fit points in lattice. Args: vert (np.array): size: (M, 3) (points in the first two columns, values in the third) Returns: vert (np.array): scaled vertices that fit in lattice. """ # normalize face to fit in lattice hw_ratio = (vert[:, 1].max() - vert[:, 1].min()) / \ (vert[:, 0].max() - vert[:, 0].min()) _, _, x_max, y_max = cls.get_data_boundaries(hw_ratio=hw_ratio, pad=0.03) # recenter data x_mean = (vert[:, 0].max() + vert[:, 0].min()) / 2 y_mean = (vert[:, 1].max() + vert[:, 1].min()) / 2 vert[:, 0] = vert[:, 0] - x_mean vert[:, 1] = vert[:, 1] - y_mean # x,y scaling factors # vert[i,0] should be within (-x_max, x_max) # vert[i,1] should be within (-y_max, y_max) x_norm = x_max / vert[:, 0].max() y_norm = y_max / vert[:, 1].max() if x_norm < y_norm: vert = vert * x_norm else: vert = vert * y_norm return vert @staticmethod def get_data_boundaries(hw_ratio=math.sqrt(3), pad=0.1): """ Get the data boundaries that allow fitting the data in centered rectangular region of the lattice with a specified height/width ratio, so as to maximize occupied space within the interior lattice. Pad a given distance from the limits if pad > 0. Takes into account geometry of hexagonal lattice: if hw_ratio > math.sqrt(3), the data touches the upper and bottom interior border; otherwise, it touch the left and right borders. Args: hw_ratio (float>0): height/width ratio of rectangular region. pad (float>=0): distance to pad from the limits of the region. Returns: 4-tuple (x_min, x_max, y_min, y_max): data boundaries """ # requires that lattice is hexagonal and lsize*h = 1 (enforced) bottom_right_std = Lattice.bottom_right_std if hw_ratio > math.sqrt(3): # from geometry maximize space usage y_min = bottom_right_std[1] x_min = y_min * (1. / hw_ratio) else: a = (bottom_right_std[0] * 2) / (1 + hw_ratio * math.sqrt(3) / 3) x_min = -a y_min = x_min * hw_ratio x_min, y_min = x_min + pad, y_min + pad x_max, y_max = -x_min, -y_min return x_min.item(), y_min.item(), x_max.item(), y_max.item()
from glob import glob import os import numpy as np import h5py def list_keys(path): keys = [] def get_flat_keys(name, obj): if isinstance(obj, h5py.Dataset): keys.append(name) file = sorted(glob(os.path.join(path, '*.h5')))[0] with h5py.File(file, 'r') as hdf: hdf.visititems(get_flat_keys) scalars = [k for k in keys if k.startswith('scalar')] histograms = [k for k in keys if k.startswith('histrogram')] images = [k for k in keys if k.startswith('image')] arrays = [k for k in keys if k.startswith('array')] print('Scalars:') print('\t' + '\n\t'.join(scalars)) print('Histograms:') print('\t' + '\n\t'.join(histograms)) print('Images:') print('\t' + '\n\t'.join(images)) print('Arrays:') print('\t' + '\n\t'.join(arrays)) def read_from_key(path, key): datas = [] for file in sorted(glob(os.path.join(path, '*.h5'))): with h5py.File(file, 'r') as hdf: data = np.asarray(hdf[key]) print(f'Extracting {key} from {file}, index {data['step'][0]} to {data['step'][-1]}') datas.append(data) datas = np.concatenate(datas, axis=0) return datas
from glob import glob import os import numpy as np import h5py def list_keys(path): keys = [] def get_flat_keys(name, obj): if isinstance(obj, h5py.Dataset): keys.append(name) file = sorted(glob(os.path.join(path, '*.h5')))[0] with h5py.File(file, 'r') as hdf: hdf.visititems(get_flat_keys) scalars = [k for k in keys if k.startswith('scalar')] histograms = [k for k in keys if k.startswith('histrogram')] images = [k for k in keys if k.startswith('image')] arrays = [k for k in keys if k.startswith('array')] print('Scalars:') print('\t' + '\n\t'.join(scalars)) print('Histograms:') print('\t' + '\n\t'.join(histograms)) print('Images:') print('\t' + '\n\t'.join(images)) print('Arrays:') print('\t' + '\n\t'.join(arrays)) def read_from_key(path, key): datas = [] for file in sorted(glob(os.path.join(path, '*.h5'))): with h5py.File(file, 'r') as hdf: data = np.asarray(hdf[key]) print(f'Extracting {key} from {file}, index {data["step"][0]} to {data["step"][-1]}') datas.append(data) datas = np.concatenate(datas, axis=0) return datas
# this python program was written using python 3.8.6 import json import uuid import os import glob import zipfile from typing import Callable import snyk import requests # This lambda function takes a cloudstash.io function artifact and # returns a list of vulnerabilities in the codes/dependencies as reported by snyk # either get the hostname from env variable, or use the default CLOUDSTASH_HOSTNAME = os.getenv("CLOUDSTASH_HOSTNAME", "https://cloudstash.io") # the endpoint from where to download artifacts CLOUDSTASH_DOWNLOAD_ENDPOINT = os.getenv("CLOUDSTASH_DOWNLOAD_ENDPOINT", "artifact_download") # the unique identifier for this invocation, used to create a unique directory to store temporary files INVOCATION_UUID = uuid.uuid4() # prefix for error messages: ERROR_PREFIX = "ERROR:" # the temporary directory the artifact will be downloaded to ARTIFACT_DOWNLOAD_LOCATION = f"/tmp/artifact_{INVOCATION_UUID}" # the directory where artifact files will be extracted to ARTIFACT_EXTRACT_LOCATION = f"{ARTIFACT_DOWNLOAD_LOCATION}/extracted" # the absolute path of the downloaded artifact zip file ARTIFACT_ZIP_FILE = f"{ARTIFACT_DOWNLOAD_LOCATION}/artifact.zip" # the default output format to use if none is specified DEFAULT_OUTPUT_FORMAT = "full" # a personal snyk api key is necassary in order to scan the artifact SNYK_API_KEY = os.getenv("SNYK_API_KEY") def handler(event, context): if "body" in event: # the API gateway will wrap the request body, so we must parse it parameters = json.loads(event["body"]) else: parameters = event # parse parameters and load envrironment variables param_error, snyk_api_key, artifact_url, artifact_id, output_format = parse_parameters(params=parameters) if param_error: return param_error # create the snyk org object to test files with # also verifies that the api key is valid org_error, snyk_org = get_snyk_org(snyk_api_key=snyk_api_key) if org_error: return org_error # download the artifact zip file into a directory /tmp/<inovocation uuid>/artifact.zip artifact_download_error = get_artifact(url=artifact_url) if artifact_download_error: return artifact_download_error # what runtime does the function use? runtime_interpolation_error, runtime = get_function_runtime(artifact_id=artifact_id) if runtime_interpolation_error: return runtime_interpolation_error # vulnerabilities will be a list of snyk.api_response.issues.vulnerabilities # if any vulnerabilities are found, otherwise will be an empty list test_error, vulnerabilities = test_dependencies_for_vulnerabilities( runtime=runtime, artifact_location=ARTIFACT_EXTRACT_LOCATION, snyk_org=snyk_org ) if test_error: return test_error # only attempt to format if there are any vulnerabilitues body = None if vulnerabilities: format_error, formatted_vulnerabilities = format_vulnerabilities( output_format=output_format, vulnerabilities=vulnerabilities ) if format_error: return format_error if formatted_vulnerabilities: body = formatted_vulnerabilities else: body = "No vulnerabilities found." # build the response response = {"statusCode": 200, "body": json.dumps(body)} return response def format_vulnerabilities(output_format: str, vulnerabilities: list) -> (str, list): error = None formatted_vulnerabilities = [] if output_format == "human": for vuln in vulnerabilities: # parse a selection of fields and label for humans to read human_readable_vuln = { "Title": vuln.title, "Snyk ID": vuln.id, "Snyk URL": vuln.url, "Package": f"{vuln.package}:{vuln.version}", "Severity": vuln.severity, "CVSS Score": vuln.cvssScore, "CVE": vuln.identifiers, "Description": vuln.description, } formatted_vulnerabilities.append(human_readable_vuln) elif output_format == "full": for vuln in vulnerabilities: # parse all fields of the snyk object to a JSON parseable dict formatted_vulnerabilities.append(vuln.__dict__) else: error = f"{ERROR_PREFIX} Could not format vulnerabilities using the specified output format: {output_format}" return error, formatted_vulnerabilities def test_dependency_file( snyk_test_func: Callable[[str], list], dependency_file_name: str, artifact_location: str, ) -> (str, list): error = None vulns = [] # use glob to recursively find the path to the dependency file if it is not in the root dependency_file = ( None if not glob.glob(pathname=f"{artifact_location}/**/{dependency_file_name}", recursive=True) else glob.glob(pathname=f"{artifact_location}/**/{dependency_file_name}", recursive=True)[0] ) if dependency_file: with open(dependency_file, "r") as df: try: # use the snyk test function supplied api_response = snyk_test_func(df) if api_response.issues.vulnerabilities: vulns = api_response.issues.vulnerabilities except Exception: error = f"{ERROR_PREFIX} There was an error getting the vulnerabilities for the artifact." else: error = f"{ERROR_PREFIX} No {dependency_file_name} file could be found, please include it in the root of the function archive." return error, vulns def test_dependencies_for_vulnerabilities(runtime: str, artifact_location: str, snyk_org: snyk.client) -> (str, list): # use the appropriate snyk test function based on the runtime # TODO figure out some way of differentiating between runtimes with multiple # dependency file types, like for java - gradle vs maven if runtime == "node": return test_dependency_file( snyk_test_func=snyk_org.test_packagejson, dependency_file_name="package.json", artifact_location=artifact_location, ) return (f"{ERROR_PREFIX} runtime is not supported.", None) def get_function_runtime(artifact_id: str) -> (str, str): # query the cloudstash artifact for it's runtime error = None runtime = None cloudstash_url = f"https://cloudstash.io/artifact/{artifact_id}" response = requests.get(cloudstash_url) if response.status_code == 200: groupid = response.json()["groupId"] else: error = f"{ERROR_PREFIX} could not get cloudstash artifact metadata, make sure that the artifact id is correct." if "node" in groupid: runtime = "node" return error, runtime def get_artifact(url: str) -> str: error = None # create the directories, creating any parent directories needed os.makedirs(ARTIFACT_EXTRACT_LOCATION, exist_ok=True) # download the zipfile request = requests.get(url=url, stream=True) downloaded_successfully = False if request.ok: # write the downloaded file as a stream to the zipfile with open(ARTIFACT_ZIP_FILE, "wb") as writeable_zip_file: for chunk in request.iter_content(chunk_size=128): writeable_zip_file.write(chunk) downloaded_successfully = True else: error = f"{ERROR_PREFIX} could not download the specified artifact, please verify that the url/id is correct." if downloaded_successfully and zipfile.is_zipfile(ARTIFACT_ZIP_FILE): try: with zipfile.ZipFile(ARTIFACT_ZIP_FILE, "r") as zf: # TODO maybe refactor this to use ZipFile.extract() instead # as there is a warning in the documentation about absolute file paths # https://docs.python.org/3.8/library/zipfile.html#zipfile.ZipFile.extractall zf.extractall(ARTIFACT_EXTRACT_LOCATION) except RuntimeError: error = f"{ERROR_PREFIX} There was an error extracting the artifact zip file." return error def get_snyk_org(snyk_api_key: str) -> (str, str): error = None org = None # create the snyk client try: client = snyk.SnykClient(snyk_api_key) # create the orgianzation to use for testing org = client.organizations.first() # if the api key is invalid, return an error except snyk.errors.SnykHTTPError: error = f"{ERROR_PREFIX} Provided Snyk API key is not valid." return error, org def parse_parameters(params: dict) -> (str, str, str): # return an error string if any of the parameters are not parsed correctly, or missing error = None # load snyk api token from environment if it is not provided snyk_api_key = params["body"]["snyk_api_key"] if "snyk_api_key" in params else SNYK_API_KEY # if api key is not set, return error if snyk_api_key is None: error = f"{ERROR_PREFIX} Could not find a Snyk API key, please set the 'SNYK_API_KEY' environment variable, or pass the API key as an argument: 'snyk_api_key':<api_key>." if "artifact_url" in params: url = params["artifact_url"] artifact_url = url # if url ends on / remove it, to make parsing the id easier if url[len(url) - 1] == "/": url = url[:-1] _, artifact_id = os.path.split(url) elif "artifact_id" in params: artifact_url = f"{CLOUDSTASH_HOSTNAME}/{CLOUDSTASH_DOWNLOAD_ENDPOINT}/{params["artifact_id"]}" artifact_id = params["artifact_id"] else: artifact_url = None artifact_id = None error = f"{ERROR_PREFIX} No URL was provided for a CloudStash artifact, you must provide either a url as 'artifact_url':'<url>' or the CloudStash artifact ID as 'artifact_id':'<id>'" # parse the ourput format to return data in if "output_format" in params: of = params["output_format"] if of == "human" or of == "full": output_format = params["output_format"] else: error = f"{ERROR_PREFIX} Invalid output format, must one of 'human', 'full'." else: output_format = DEFAULT_OUTPUT_FORMAT return error, snyk_api_key, artifact_url, artifact_id, output_format # test the code locally # will only be run if called from cli if __name__ == "__main__": from pprint import pprint test_event = {} # test cases test_json_file = "tests/test_artifact_url_vulnerable.json" # test_json_file = "tests/test_artifact_id_vulnerable.json" # test_json_file = "tests/test_artifact_id_no_vulnerabilities.json" # test_json_file = "tests/node_test_artifact_vulns.json" # test_json_file = "tests/node_test_artifact_no_vulns.json" with open(test_json_file) as test_json: test_event = json.load(test_json) test_context = {} test_res = handler(test_event, test_context) # pprint(json.loads(test_res["body"])) print(test_res)
# this python program was written using python 3.8.6 import json import uuid import os import glob import zipfile from typing import Callable import snyk import requests # This lambda function takes a cloudstash.io function artifact and # returns a list of vulnerabilities in the codes/dependencies as reported by snyk # either get the hostname from env variable, or use the default CLOUDSTASH_HOSTNAME = os.getenv("CLOUDSTASH_HOSTNAME", "https://cloudstash.io") # the endpoint from where to download artifacts CLOUDSTASH_DOWNLOAD_ENDPOINT = os.getenv("CLOUDSTASH_DOWNLOAD_ENDPOINT", "artifact_download") # the unique identifier for this invocation, used to create a unique directory to store temporary files INVOCATION_UUID = uuid.uuid4() # prefix for error messages: ERROR_PREFIX = "ERROR:" # the temporary directory the artifact will be downloaded to ARTIFACT_DOWNLOAD_LOCATION = f"/tmp/artifact_{INVOCATION_UUID}" # the directory where artifact files will be extracted to ARTIFACT_EXTRACT_LOCATION = f"{ARTIFACT_DOWNLOAD_LOCATION}/extracted" # the absolute path of the downloaded artifact zip file ARTIFACT_ZIP_FILE = f"{ARTIFACT_DOWNLOAD_LOCATION}/artifact.zip" # the default output format to use if none is specified DEFAULT_OUTPUT_FORMAT = "full" # a personal snyk api key is necassary in order to scan the artifact SNYK_API_KEY = os.getenv("SNYK_API_KEY") def handler(event, context): if "body" in event: # the API gateway will wrap the request body, so we must parse it parameters = json.loads(event["body"]) else: parameters = event # parse parameters and load envrironment variables param_error, snyk_api_key, artifact_url, artifact_id, output_format = parse_parameters(params=parameters) if param_error: return param_error # create the snyk org object to test files with # also verifies that the api key is valid org_error, snyk_org = get_snyk_org(snyk_api_key=snyk_api_key) if org_error: return org_error # download the artifact zip file into a directory /tmp/<inovocation uuid>/artifact.zip artifact_download_error = get_artifact(url=artifact_url) if artifact_download_error: return artifact_download_error # what runtime does the function use? runtime_interpolation_error, runtime = get_function_runtime(artifact_id=artifact_id) if runtime_interpolation_error: return runtime_interpolation_error # vulnerabilities will be a list of snyk.api_response.issues.vulnerabilities # if any vulnerabilities are found, otherwise will be an empty list test_error, vulnerabilities = test_dependencies_for_vulnerabilities( runtime=runtime, artifact_location=ARTIFACT_EXTRACT_LOCATION, snyk_org=snyk_org ) if test_error: return test_error # only attempt to format if there are any vulnerabilitues body = None if vulnerabilities: format_error, formatted_vulnerabilities = format_vulnerabilities( output_format=output_format, vulnerabilities=vulnerabilities ) if format_error: return format_error if formatted_vulnerabilities: body = formatted_vulnerabilities else: body = "No vulnerabilities found." # build the response response = {"statusCode": 200, "body": json.dumps(body)} return response def format_vulnerabilities(output_format: str, vulnerabilities: list) -> (str, list): error = None formatted_vulnerabilities = [] if output_format == "human": for vuln in vulnerabilities: # parse a selection of fields and label for humans to read human_readable_vuln = { "Title": vuln.title, "Snyk ID": vuln.id, "Snyk URL": vuln.url, "Package": f"{vuln.package}:{vuln.version}", "Severity": vuln.severity, "CVSS Score": vuln.cvssScore, "CVE": vuln.identifiers, "Description": vuln.description, } formatted_vulnerabilities.append(human_readable_vuln) elif output_format == "full": for vuln in vulnerabilities: # parse all fields of the snyk object to a JSON parseable dict formatted_vulnerabilities.append(vuln.__dict__) else: error = f"{ERROR_PREFIX} Could not format vulnerabilities using the specified output format: {output_format}" return error, formatted_vulnerabilities def test_dependency_file( snyk_test_func: Callable[[str], list], dependency_file_name: str, artifact_location: str, ) -> (str, list): error = None vulns = [] # use glob to recursively find the path to the dependency file if it is not in the root dependency_file = ( None if not glob.glob(pathname=f"{artifact_location}/**/{dependency_file_name}", recursive=True) else glob.glob(pathname=f"{artifact_location}/**/{dependency_file_name}", recursive=True)[0] ) if dependency_file: with open(dependency_file, "r") as df: try: # use the snyk test function supplied api_response = snyk_test_func(df) if api_response.issues.vulnerabilities: vulns = api_response.issues.vulnerabilities except Exception: error = f"{ERROR_PREFIX} There was an error getting the vulnerabilities for the artifact." else: error = f"{ERROR_PREFIX} No {dependency_file_name} file could be found, please include it in the root of the function archive." return error, vulns def test_dependencies_for_vulnerabilities(runtime: str, artifact_location: str, snyk_org: snyk.client) -> (str, list): # use the appropriate snyk test function based on the runtime # TODO figure out some way of differentiating between runtimes with multiple # dependency file types, like for java - gradle vs maven if runtime == "node": return test_dependency_file( snyk_test_func=snyk_org.test_packagejson, dependency_file_name="package.json", artifact_location=artifact_location, ) return (f"{ERROR_PREFIX} runtime is not supported.", None) def get_function_runtime(artifact_id: str) -> (str, str): # query the cloudstash artifact for it's runtime error = None runtime = None cloudstash_url = f"https://cloudstash.io/artifact/{artifact_id}" response = requests.get(cloudstash_url) if response.status_code == 200: groupid = response.json()["groupId"] else: error = f"{ERROR_PREFIX} could not get cloudstash artifact metadata, make sure that the artifact id is correct." if "node" in groupid: runtime = "node" return error, runtime def get_artifact(url: str) -> str: error = None # create the directories, creating any parent directories needed os.makedirs(ARTIFACT_EXTRACT_LOCATION, exist_ok=True) # download the zipfile request = requests.get(url=url, stream=True) downloaded_successfully = False if request.ok: # write the downloaded file as a stream to the zipfile with open(ARTIFACT_ZIP_FILE, "wb") as writeable_zip_file: for chunk in request.iter_content(chunk_size=128): writeable_zip_file.write(chunk) downloaded_successfully = True else: error = f"{ERROR_PREFIX} could not download the specified artifact, please verify that the url/id is correct." if downloaded_successfully and zipfile.is_zipfile(ARTIFACT_ZIP_FILE): try: with zipfile.ZipFile(ARTIFACT_ZIP_FILE, "r") as zf: # TODO maybe refactor this to use ZipFile.extract() instead # as there is a warning in the documentation about absolute file paths # https://docs.python.org/3.8/library/zipfile.html#zipfile.ZipFile.extractall zf.extractall(ARTIFACT_EXTRACT_LOCATION) except RuntimeError: error = f"{ERROR_PREFIX} There was an error extracting the artifact zip file." return error def get_snyk_org(snyk_api_key: str) -> (str, str): error = None org = None # create the snyk client try: client = snyk.SnykClient(snyk_api_key) # create the orgianzation to use for testing org = client.organizations.first() # if the api key is invalid, return an error except snyk.errors.SnykHTTPError: error = f"{ERROR_PREFIX} Provided Snyk API key is not valid." return error, org def parse_parameters(params: dict) -> (str, str, str): # return an error string if any of the parameters are not parsed correctly, or missing error = None # load snyk api token from environment if it is not provided snyk_api_key = params["body"]["snyk_api_key"] if "snyk_api_key" in params else SNYK_API_KEY # if api key is not set, return error if snyk_api_key is None: error = f"{ERROR_PREFIX} Could not find a Snyk API key, please set the 'SNYK_API_KEY' environment variable, or pass the API key as an argument: 'snyk_api_key':<api_key>." if "artifact_url" in params: url = params["artifact_url"] artifact_url = url # if url ends on / remove it, to make parsing the id easier if url[len(url) - 1] == "/": url = url[:-1] _, artifact_id = os.path.split(url) elif "artifact_id" in params: artifact_url = f"{CLOUDSTASH_HOSTNAME}/{CLOUDSTASH_DOWNLOAD_ENDPOINT}/{params['artifact_id']}" artifact_id = params["artifact_id"] else: artifact_url = None artifact_id = None error = f"{ERROR_PREFIX} No URL was provided for a CloudStash artifact, you must provide either a url as 'artifact_url':'<url>' or the CloudStash artifact ID as 'artifact_id':'<id>'" # parse the ourput format to return data in if "output_format" in params: of = params["output_format"] if of == "human" or of == "full": output_format = params["output_format"] else: error = f"{ERROR_PREFIX} Invalid output format, must one of 'human', 'full'." else: output_format = DEFAULT_OUTPUT_FORMAT return error, snyk_api_key, artifact_url, artifact_id, output_format # test the code locally # will only be run if called from cli if __name__ == "__main__": from pprint import pprint test_event = {} # test cases test_json_file = "tests/test_artifact_url_vulnerable.json" # test_json_file = "tests/test_artifact_id_vulnerable.json" # test_json_file = "tests/test_artifact_id_no_vulnerabilities.json" # test_json_file = "tests/node_test_artifact_vulns.json" # test_json_file = "tests/node_test_artifact_no_vulns.json" with open(test_json_file) as test_json: test_event = json.load(test_json) test_context = {} test_res = handler(test_event, test_context) # pprint(json.loads(test_res["body"])) print(test_res)
import os def get_nextcloud_options(): # _options = {"recv_speed": 50 * (1024**2)} _options = {} if os.getenv('NEXTCLOUD_USERNAME') is not None: _options['webdav_hostname'] = f"https://antistasi.de/dev_drive/remote.php/dav/files/{os.getenv("NEXTCLOUD_USERNAME")}/" _options['webdav_login'] = os.getenv('NEXTCLOUD_USERNAME') _options["webdav_timeout"] = 120 else: if os.getenv('INFO_RUN') != "1": raise RuntimeError('no nextcloud Username set') if os.getenv('NEXTCLOUD_PASSWORD') is not None: _options['webdav_password'] = os.getenv('NEXTCLOUD_PASSWORD') else: if os.getenv('INFO_RUN') != "1": raise RuntimeError('no nextcloud Password set') return _options
import os def get_nextcloud_options(): # _options = {"recv_speed": 50 * (1024**2)} _options = {} if os.getenv('NEXTCLOUD_USERNAME') is not None: _options['webdav_hostname'] = f"https://antistasi.de/dev_drive/remote.php/dav/files/{os.getenv('NEXTCLOUD_USERNAME')}/" _options['webdav_login'] = os.getenv('NEXTCLOUD_USERNAME') _options["webdav_timeout"] = 120 else: if os.getenv('INFO_RUN') != "1": raise RuntimeError('no nextcloud Username set') if os.getenv('NEXTCLOUD_PASSWORD') is not None: _options['webdav_password'] = os.getenv('NEXTCLOUD_PASSWORD') else: if os.getenv('INFO_RUN') != "1": raise RuntimeError('no nextcloud Password set') return _options
import dash_core_components as dcc import dash_html_components as html from dash import Dash from dash.dependencies import Input, Output from dash_extensions import WebSocket # Create example app. app = Dash(prevent_initial_callbacks=True) app.layout = html.Div([ dcc.Input(id="input", autoComplete="off"), html.Div(id="message"), WebSocket(url="wss://echo.websocket.org", id="ws") ]) @app.callback(Output("ws", "send"), [Input("input", "value")]) def send(value): return value @app.callback(Output("message", "children"), [Input("ws", "message")]) def message(e): return f"Response from websocket: {e["data"]}" if __name__ == '__main__': app.run_server()
import dash_core_components as dcc import dash_html_components as html from dash import Dash from dash.dependencies import Input, Output from dash_extensions import WebSocket # Create example app. app = Dash(prevent_initial_callbacks=True) app.layout = html.Div([ dcc.Input(id="input", autoComplete="off"), html.Div(id="message"), WebSocket(url="wss://echo.websocket.org", id="ws") ]) @app.callback(Output("ws", "send"), [Input("input", "value")]) def send(value): return value @app.callback(Output("message", "children"), [Input("ws", "message")]) def message(e): return f"Response from websocket: {e['data']}" if __name__ == '__main__': app.run_server()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Nov 11 16:09:52 2020 @author: chrislovejoy & mitated """ import os from datetime import datetime from typing import List from models import ResultItem from youtube_api import YouTubeAPI yt_driver = YouTubeAPI(os.environ.get('API_KEY', 'default api key')) def search_each_term( search_terms: List[str], uploaded_in_last_days: int = 7, max_results: int = 50, views_threshold: int = 5000, num_to_print: int = 5) -> List[ResultItem]: items = get_all_results_for_search_terms(search_terms, uploaded_in_last_days, max_results) result_items = [] for item in items: views_count = yt_driver.get_views_count_by_video_id(item['id']['videoId']) if views_count < views_threshold: continue subscribers_count = yt_driver.get_subscribers_count_by_channel_id(item['snippet']['channelId']) days_since_published = get_days_ago_last_publication(item) ratio = get_ratio(views_count, subscribers_count) channel_name = yt_driver.get_channel_name_by_channel_id(item['snippet']['channelId']) result_item = ResultItem( title=item['snippet']['title'], video_url=f"https://www.youtube.com/watch?v={item["id"]["videoId"]}", custom_score=custom_score(views_count, ratio, days_since_published), views=views_count, channel_id=item['snippet']['channelId'], channel_name=channel_name, num_subscribers=subscribers_count, view_subscriber_ratio=ratio, channel_url=f"https://www.youtube.com/channel/{item["snippet"]["channelId"]}" ) result_items += [result_item] result_items.sort(reverse=True, key=lambda x: x.custom_score) # print("THE TOP VIDEOS OVERALL ARE:") # print_top_videos(result_items, num_to_print) # print("==========================\n") result_items_dict = [i.__dict__ for i in result_items] return result_items_dict def get_all_results_for_search_terms( search_terms: List[str], uploaded_in_last_days: int = 7, max_results: int = 50, ) -> List[dict]: items = [] for search_term in search_terms: items += yt_driver.find_videos( search_term=search_term, uploaded_in_last_days=uploaded_in_last_days, max_results=max_results )['items'] return items def print_top_videos(videos: List[ResultItem], num_to_print: int = 5): """Prints top videos to console, with details and link to video.""" for i, video in enumerate(videos[:num_to_print]): title = video.title views = video.views subs = video.num_subscribers link = video.video_url print( f"Video #{i + 1}:\n" f"The video '{title}' has {views} views, from a channel " f"with {subs} subscribers and can be viewed here: {link}" f"\n" ) print("==========================\n") def get_custom_score(views_count: int, ratio: float, days_since_published: int) -> float: ratio = min(ratio, 5) score = (views_count * ratio) / days_since_published return score def get_days_ago_last_publication(item: dict) -> int: when_published = item['snippet']['publishedAt'] when_published_datetime_object = datetime.strptime(when_published, '%Y-%m-%dT%H:%M:%SZ') today_date = datetime.today() days_since_published = int((today_date - when_published_datetime_object).days) if days_since_published == 0: days_since_published = 1 return days_since_published def get_ratio(views_count: int, subscribers_count: int) -> float: if subscribers_count == 0: return 0 ratio = views_count / subscribers_count return ratio def custom_score(views_count: int, ratio: float, days_since_published: int) -> float: ratio = min(ratio, 5) score = (views_count * ratio) / days_since_published return score
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Nov 11 16:09:52 2020 @author: chrislovejoy & mitated """ import os from datetime import datetime from typing import List from models import ResultItem from youtube_api import YouTubeAPI yt_driver = YouTubeAPI(os.environ.get('API_KEY', 'default api key')) def search_each_term( search_terms: List[str], uploaded_in_last_days: int = 7, max_results: int = 50, views_threshold: int = 5000, num_to_print: int = 5) -> List[ResultItem]: items = get_all_results_for_search_terms(search_terms, uploaded_in_last_days, max_results) result_items = [] for item in items: views_count = yt_driver.get_views_count_by_video_id(item['id']['videoId']) if views_count < views_threshold: continue subscribers_count = yt_driver.get_subscribers_count_by_channel_id(item['snippet']['channelId']) days_since_published = get_days_ago_last_publication(item) ratio = get_ratio(views_count, subscribers_count) channel_name = yt_driver.get_channel_name_by_channel_id(item['snippet']['channelId']) result_item = ResultItem( title=item['snippet']['title'], video_url=f"https://www.youtube.com/watch?v={item['id']['videoId']}", custom_score=custom_score(views_count, ratio, days_since_published), views=views_count, channel_id=item['snippet']['channelId'], channel_name=channel_name, num_subscribers=subscribers_count, view_subscriber_ratio=ratio, channel_url=f"https://www.youtube.com/channel/{item['snippet']['channelId']}" ) result_items += [result_item] result_items.sort(reverse=True, key=lambda x: x.custom_score) # print("THE TOP VIDEOS OVERALL ARE:") # print_top_videos(result_items, num_to_print) # print("==========================\n") result_items_dict = [i.__dict__ for i in result_items] return result_items_dict def get_all_results_for_search_terms( search_terms: List[str], uploaded_in_last_days: int = 7, max_results: int = 50, ) -> List[dict]: items = [] for search_term in search_terms: items += yt_driver.find_videos( search_term=search_term, uploaded_in_last_days=uploaded_in_last_days, max_results=max_results )['items'] return items def print_top_videos(videos: List[ResultItem], num_to_print: int = 5): """Prints top videos to console, with details and link to video.""" for i, video in enumerate(videos[:num_to_print]): title = video.title views = video.views subs = video.num_subscribers link = video.video_url print( f"Video #{i + 1}:\n" f"The video '{title}' has {views} views, from a channel " f"with {subs} subscribers and can be viewed here: {link}" f"\n" ) print("==========================\n") def get_custom_score(views_count: int, ratio: float, days_since_published: int) -> float: ratio = min(ratio, 5) score = (views_count * ratio) / days_since_published return score def get_days_ago_last_publication(item: dict) -> int: when_published = item['snippet']['publishedAt'] when_published_datetime_object = datetime.strptime(when_published, '%Y-%m-%dT%H:%M:%SZ') today_date = datetime.today() days_since_published = int((today_date - when_published_datetime_object).days) if days_since_published == 0: days_since_published = 1 return days_since_published def get_ratio(views_count: int, subscribers_count: int) -> float: if subscribers_count == 0: return 0 ratio = views_count / subscribers_count return ratio def custom_score(views_count: int, ratio: float, days_since_published: int) -> float: ratio = min(ratio, 5) score = (views_count * ratio) / days_since_published return score
from __future__ import annotations from pathlib import Path try: import dearpygui.dearpygui as dpg dearpygui_imported = True except ImportError: dearpygui_imported = False from .. import __version__, config from ..utils.module_ops import scene_classes_from_file if dearpygui_imported: window = dpg.generate_uuid() def configure_pygui(renderer, widgets, update=True): if not dearpygui_imported: raise RuntimeError("Attempted to use DearPyGUI when it isn't imported.") if update: dpg.delete_item(window) else: dpg.setup_viewport() dpg.set_viewport_title(title=f"Manim Community v{__version__}") dpg.set_viewport_width(1015) dpg.set_viewport_height(540) def rerun_callback(sender, data): renderer.scene.queue.put(("rerun_gui", [], {})) def continue_callback(sender, data): renderer.scene.queue.put(("exit_gui", [], {})) def scene_selection_callback(sender, data): config["scene_names"] = (dpg.get_value(sender),) renderer.scene.queue.put(("rerun_gui", [], {})) scene_classes = scene_classes_from_file(Path(config["input_file"]), full_list=True) scene_names = [scene_class.__name__ for scene_class in scene_classes] with dpg.window( id=window, label="Manim GUI", pos=[config["gui_location"][0], config["gui_location"][1]], width=1000, height=500, ): dpg.set_global_font_scale(2) dpg.add_button(label="Rerun", callback=rerun_callback) dpg.add_button(label="Continue", callback=continue_callback) dpg.add_combo( label="Selected scene", items=scene_names, callback=scene_selection_callback, default_value=config["scene_names"][0], ) dpg.add_separator() if len(widgets) != 0: with dpg.collapsing_header( label=f"{config["scene_names"][0]} widgets", default_open=True, ): for widget_config in widgets: widget_config_copy = widget_config.copy() name = widget_config_copy["name"] widget = widget_config_copy["widget"] if widget != "separator": del widget_config_copy["name"] del widget_config_copy["widget"] getattr(dpg, f"add_{widget}")(name, **widget_config_copy) else: dpg.add_separator() if not update: dpg.start_dearpygui()
from __future__ import annotations from pathlib import Path try: import dearpygui.dearpygui as dpg dearpygui_imported = True except ImportError: dearpygui_imported = False from .. import __version__, config from ..utils.module_ops import scene_classes_from_file if dearpygui_imported: window = dpg.generate_uuid() def configure_pygui(renderer, widgets, update=True): if not dearpygui_imported: raise RuntimeError("Attempted to use DearPyGUI when it isn't imported.") if update: dpg.delete_item(window) else: dpg.setup_viewport() dpg.set_viewport_title(title=f"Manim Community v{__version__}") dpg.set_viewport_width(1015) dpg.set_viewport_height(540) def rerun_callback(sender, data): renderer.scene.queue.put(("rerun_gui", [], {})) def continue_callback(sender, data): renderer.scene.queue.put(("exit_gui", [], {})) def scene_selection_callback(sender, data): config["scene_names"] = (dpg.get_value(sender),) renderer.scene.queue.put(("rerun_gui", [], {})) scene_classes = scene_classes_from_file(Path(config["input_file"]), full_list=True) scene_names = [scene_class.__name__ for scene_class in scene_classes] with dpg.window( id=window, label="Manim GUI", pos=[config["gui_location"][0], config["gui_location"][1]], width=1000, height=500, ): dpg.set_global_font_scale(2) dpg.add_button(label="Rerun", callback=rerun_callback) dpg.add_button(label="Continue", callback=continue_callback) dpg.add_combo( label="Selected scene", items=scene_names, callback=scene_selection_callback, default_value=config["scene_names"][0], ) dpg.add_separator() if len(widgets) != 0: with dpg.collapsing_header( label=f"{config['scene_names'][0]} widgets", default_open=True, ): for widget_config in widgets: widget_config_copy = widget_config.copy() name = widget_config_copy["name"] widget = widget_config_copy["widget"] if widget != "separator": del widget_config_copy["name"] del widget_config_copy["widget"] getattr(dpg, f"add_{widget}")(name, **widget_config_copy) else: dpg.add_separator() if not update: dpg.start_dearpygui()
# Author: Christian Brodbeck <christianbrodbeck@nyu.edu> """Framework for figures embedded in a GUI Implementation ============== Plotting is implemented hierarchically in 3 different types of functions/classes: top-level (public names) Top-level functions or classes have public names create an entire figure. Some classes also retain the figure and provide methods for manipulating it. _ax_ Functions beginning with _ax_ organize an axes object. They do not create their own axes object (this is provided by the top-level function), but change axes formatting such as labels and extent. _plt_ Functions beginning with _plt_ only plot data to a given axes object without explicitly changing aspects of the axes themselves. Top-level plotters can be called with nested lists of data-objects (NDVar instances). They create a separate axes for each list element. Axes themselves can have multiple layers (e.g., a difference map visualized through a colormap, and significance levels indicated by contours). Example: t-test --------------- For example, the default plot for testnd.ttest() results is the following list (assuming the test compares A and B): ``[A, B, [diff(A,B), p(A, B)]]`` where ``diff(...)`` is a difference map and ``p(...)`` is a map of p-values. The main plot function creates a separate axes object for each list element: - ``A`` - ``B`` - ``[diff(A,B), p(A, B)]`` Each of these element is then plotted with the corresponding _ax_ function. The _ax_ function calls _plt_ for each of its input elements. Thus, the functions executed are: #. plot([A, B, [diff(A,B), p(A, B)]]) #. ---> _ax_(A) #. ------> _plt_(A) #. ---> _ax_(B) #. ------> _plt_(B) #. ---> _ax_([diff(A,B), p(A, B)]) #. ------> _plt_(diff(A,B)) #. ------> _plt_(p(A, B)) Vision ------ Modularize organization Data organizers: Take data from input arguments and organize it into axes and layers Style mappers: Take data and input arguments and determine matplotlib parameters Figure components Manage styling and interaction for figure properties (XAxisMixin, TimeController, ...) """ from __future__ import annotations import __main__ from collections.abc import Iterable from collections import defaultdict from copy import copy from dataclasses import dataclass, replace from enum import Enum, auto from functools import cached_property, reduce from itertools import chain, cycle, repeat from logging import getLogger import math from numbers import Number import os import re import time from typing import Any, Callable, Dict, Iterator, List, Literal, Optional, Sequence, Tuple, Union import weakref import matplotlib as mpl import matplotlib.axes import matplotlib.font_manager import matplotlib.patches import matplotlib.text from matplotlib.colors import Colormap from matplotlib.figure import SubplotParams from matplotlib.ticker import FuncFormatter import numpy as np from .._celltable import Celltable from .._colorspaces import LocatedColormap, symmetric_cmaps, zerobased_cmaps, ALPHA_CMAPS from .._config import CONFIG from .._data_obj import Dimension, Dataset, Factor, Interaction, NDVar, Var, Case, UTS, NDVarArg, CategorialArg, IndexArg, CellArg, NDVarTypes, ascategorial, asndvar, assub, isnumeric, isdataobject, combine_cells, cellname from .._utils.notebooks import use_inline_backend from .._stats import testnd from .._utils import IS_WINDOWS, intervals, ui from .._ndvar import erode, resample from .._text import enumeration, ms from ..fmtxt import FMTextArg, Image, asfmtext, asfmtext_or_none from ..table import melt_ndvar from ._decorations import mark_difference from ._styles import Style, find_cell_styles from ._utils import adjust_hsv # constants POINT = 0.013888888888898 # defaults defaults = {'maxw': 16, 'maxh': 10} # Types CMapArg = Any ColorArg = Any LegendArg = Optional[Union[str, int, Tuple[float, float], bool]] class PlotType(Enum): GENERAL = auto() LEGACY = auto() LINE = auto() IMAGE = auto() CONTOUR = auto() def do_autorun(run=None): # http://stackoverflow.com/a/2356420/166700 if run is not None: return run elif CONFIG['autorun'] is None: return not hasattr(__main__, '__file__') else: return CONFIG['autorun'] def mpl_font_size(key: str) -> float: "Font size in inches" p = matplotlib.font_manager.FontProperties(size=mpl.rcParams[key]) return p.get_size() * POINT def inch_to_figure(figure: matplotlib.figure.Figure, x: float = 0, y: float = 0): "Transform (x, y) vector in inches to figure coordinates" coords = figure.dpi_scale_trans.transform((x, y)) return figure.transFigure.inverted().transform(coords) DISPLAY_UNIT = { 's': 'ms', 'V': 'µV', 'T': 'fT', 'sensor': int, } UNIT_FORMAT = { 'A': 1, 'Am': 1, 'V': 1, 'ms': 1e3, 'mV': 1e3, 'µV': 1e6, 'pT': 1e12, 'fT': 1e15, 'dSPM': 1, 'p': 1, 'T': 1, 'n': int, # %i format 'normalized': 1, int: int, } SCALE_FORMATTERS = { 1: None, 1e3: FuncFormatter(lambda x, pos: '%g' % (1e3 * x)), 1e6: FuncFormatter(lambda x, pos: '%g' % (1e6 * x)), 1e9: FuncFormatter(lambda x, pos: '%g' % (1e9 * x)), 1e12: FuncFormatter(lambda x, pos: '%g' % (1e12 * x)), 1e15: FuncFormatter(lambda x, pos: '%g' % (1e15 * x)), int: FuncFormatter(lambda x, pos: '%i' % round(x)), } DEFAULT_CMAPS = { 'B': 'xpolar', 'V': 'xpolar', 'p': 'sig', 'f': 'viridis', 'r': 'xpolar', 't': 'xpolar', } INITIAL_RC = mpl.rcParams.copy() del INITIAL_RC['backend'] def reset_rc(): "Reset matplotlib rc-parameters to state at Eelbrain initialization" mpl.rcParams.update(INITIAL_RC) class AxisScale: """Find matching number formatter and label for display unit (!= data unit) Parameters ---------- v Display unit or scale of the axis, or daat to infer these. See ``unit_format`` dict above for options. label If ``label is True``, try to infer a label from ``v``. """ def __init__( self, v: Union[NDVar, Var, Number, str, 'PlotData'], label: Union[bool, str, Sequence[str]] = True, ): if isinstance(v, str): data_unit = None meas = None unit = v scale = UNIT_FORMAT.get(v, 1) elif isinstance(v, Number): data_unit = None meas = None unit = None scale = v else: if isnumeric(v): meas = v.info.get('meas') data_unit = v.info.get('unit') elif isinstance(v, PlotData): meas = v.meas data_unit = v.unit else: raise TypeError(f"unit={v!r}") if data_unit in DISPLAY_UNIT: unit = DISPLAY_UNIT[data_unit] scale = UNIT_FORMAT[unit] if data_unit in UNIT_FORMAT: scale /= UNIT_FORMAT[data_unit] else: scale = 1 unit = data_unit self.data_unit = data_unit # None | str self.display_unit = unit # ScalarFormatter: disabled because it always used e notation in status bar # (needs separate instance because it adapts to data) # fmt = ScalarFormatter() if scale == 1 else scale_formatters[scale] self.formatter = SCALE_FORMATTERS[scale] # Matplotlib tick formatter if label is True: if meas and unit and meas not in unit: label = f'{meas} [{unit}]' elif unit: label = unit elif meas: label = meas elif isinstance(v, PlotData): label = v.default_y_label elif isnumeric(v): label = v.name else: label = None self.label = label def find_uts_hlines(ndvar): """Find horizontal lines for uts plots (based on contours) Parameters ---------- ndvar : NDVar Data to be plotted. Returns ------- h_lines : iterator Iterator over (y, kwa) tuples. """ contours = ndvar.info.get('contours', None) if contours: for level in sorted(contours): args = contours[level] if isinstance(args, dict): yield level, args.copy() else: yield level, {'color': args} def find_uts_ax_vlim( layers: Sequence[NDVar], vlims: Dict = (), ) -> (Optional[float], Optional[float]): """Find y axis limits for uts axes Parameters ---------- layers Data to be plotted. vlims Vmax and vmin values by (meas, cmap). Returns ------- bottom Lowest value on y axis. top Highest value on y axis. """ bottom = None top = None for ndvar in layers: meas = ndvar.info.get('meas') if meas in vlims: bottom_, top_ = vlims[meas] if bottom is None: bottom = bottom_ elif bottom_ != bottom: bottom = min(bottom, bottom_) if top is None: top = top_ elif top_ != top: top = max(top, top_) return bottom, top def find_fig_cmaps( epochs: Sequence[Sequence[NDVar]], cmap: Union[dict, CMapArg] = None, alpha: bool = False, ) -> Dict[str, CMapArg]: """Find cmap for every meas Parameters ---------- epochs All NDVars in the plot. cmap Use this instead of the default for the first ``meas`` (for user argument). alpha If possible, use cmaps with alpha. Returns ------- cmaps {meas: cmap} dict for all meas. """ if isinstance(cmap, dict): out = cmap.copy() cmap = None else: out = {} for ndvar in chain(*epochs): meas = ndvar.info.get('meas') if meas in out and out[meas]: pass elif cmap is not None: out[meas] = cmap cmap = None elif 'cmap' in ndvar.info: out[meas] = ndvar.info['cmap'] else: out[meas] = None for k in out.keys(): if out[k] is None: out[k] = DEFAULT_CMAPS.get(meas, 'xpolar') # replace with cmap with alpha if alpha and out[k] in ALPHA_CMAPS: out[k] = ALPHA_CMAPS[out[k]] return out def find_fig_contours(epochs, vlims, contours_arg): """Find contour arguments for every meas type Parameters ---------- epochs : list of list of NDVar Data to be plotted. vlims : dist Vlims dict (used to interpret numerical arguments) contours_arg : int | sequence | dict User argument. Can be an int (number of contours), a sequence (values at which to draw contours), a kwargs dict (must contain the "levels" key), or a {meas: kwargs} dictionary. Returns ------- contours : dict {meas: kwargs} mapping for contour plots. Notes ----- The NDVar's info dict contains default arguments that determine how the NDVar is plotted as base and as overlay. In case of insufficient information, defaults apply. On the other hand, defaults can be overridden by providing specific arguments to plotting functions. """ if isinstance(contours_arg, dict) and 'levels' not in contours_arg: out = contours_arg.copy() contours_arg = None else: out = {} for ndvars in epochs: for layer, ndvar in enumerate(ndvars): meas = ndvar.info.get('meas') if meas in out: continue if contours_arg is not None: param = contours_arg contours_arg = None else: if layer: # overlay kind = ndvar.info.get('overlay', ('contours',)) else: kind = ndvar.info.get('base', ()) if 'contours' in kind: param = ndvar.info.get('contours', None) if layer: param = ndvar.info.get('overlay_contours', param) else: param = ndvar.info.get('base_contours', param) if isinstance(param, dict) and 'levels' not in param: levels = sorted(param) colors = [param[v] for v in levels] param = {'levels': levels, 'colors': colors} else: param = None if param is None: out[meas] = None elif isinstance(param, dict): out[meas] = param elif isinstance(param, int): vmin, vmax = vlims[meas] out[meas] = {'levels': np.linspace(vmin, vmax, param), 'colors': 'k'} else: out[meas] = {'levels': tuple(param), 'colors': 'k'} return out def find_fig_vlims(plots, vmax=None, vmin=None, cmaps=None): """Find vmin and vmax parameters for every (meas, cmap) combination Parameters ---------- plots : nested list of NDVar Unpacked plot data. vmax : None | dict | scalar Dict: predetermined vlims (take precedence). Scalar: user-specified vmax parameter (used for for the first meas kind). vmin : None | scalar User-specified vmin parameter. If vmax is user-specified but vmin is None, -vmax is used. cmaps : dict If provided, vlims will be fixed to match symmetric or 0-based cmaps. Returns ------- vlims : dict Dictionary of im limits: {meas: (vmin, vmax)}. """ vlims = {} if isinstance(vmax, dict): vlims.update(vmax) ndvars = [v for v in chain.from_iterable(plots) if v.info.get('meas') not in vlims] else: ndvars = [*chain.from_iterable(plots)] if vmin is None and vmax is not None: if cmaps is None and any(v.min() < 0 for v in ndvars): vmin = -vmax else: vmin = 0 # apply user specified vlim if vmin is not None or vmax is not None: meas = ndvars[0].info.get('meas') if vmax is None: meas_ndvars = [v for v in ndvars if v.info.get('meas') == meas] for ndvar in meas_ndvars: _, vmax_ = find_vlim_args(ndvar) vmax = vmax_ if vmax is None else max(vmax, vmax_) vlims[meas] = (vmin, vmax) ndvars = [v for v in ndvars if v.info.get('meas') != meas] # for other meas, fill in data limits for ndvar in ndvars: meas = ndvar.info.get('meas') vmin, vmax = find_vlim_args(ndvar) if meas in vlims: vmin_, vmax_ = vlims[meas] vmin = vmin if vmin_ is None else min(vmin, vmin_) vmax = vmax if vmax_ is None else max(vmax, vmax_) if vmin == vmax: vmin -= 1 vmax += 1 vlims[meas] = (vmin, vmax) # fix vlims based on cmaps if cmaps is not None: for meas in vlims.keys(): vmin, vmax = vlims[meas] vlims[meas] = fix_vlim_for_cmap(vmin, vmax, cmaps[meas]) return vlims def find_vlim_args(ndvar, vmin=None, vmax=None): if vmax is None: vmax = ndvar.info.get('vmax', None) if vmin is None: vmin = ndvar.info.get('vmin', None) if vmax is None or vmin is None: xmax = np.nanmax(ndvar.x) if np.ma.isMaskedArray(xmax): xmax = xmax.data xmin = np.nanmin(ndvar.x) if np.ma.isMaskedArray(xmin): xmin = xmin.data abs_max = max(abs(xmax), abs(xmin)) or 1e-14 if np.isnan(abs_max): raise ValueError(f"Can't plot all NaN input") scale = math.floor(np.log10(abs_max)) if vmax is None: vmax = math.ceil(xmax * 10 ** -scale) * 10 ** scale if vmin is None: vmin = math.floor(xmin * 10 ** -scale) * 10 ** scale return vmin, vmax def fix_vlim_for_cmap(vmin, vmax, cmap): "Fix the vmin value to yield an appropriate range for the cmap" if isinstance(cmap, LocatedColormap): vmin, vmax = cmap.vmin, cmap.vmax is_symmetric = cmap.symmetric starts_at_zero = False else: if isinstance(cmap, Colormap): cmap = cmap.name is_symmetric = cmap in symmetric_cmaps starts_at_zero = cmap in zerobased_cmaps if is_symmetric: if vmax is None and vmin is None: pass elif vmin is None: vmax = abs(vmax) vmin = -vmax elif vmax is None: vmax = abs(vmin) vmin = -vmax else: vmax = max(abs(vmax), abs(vmin)) vmin = -vmax elif starts_at_zero: vmin = 0 return vmin, vmax def find_data_dims( ndvar: NDVar, dims: Union[int, Tuple[str, ...]], extra_dim: str = None, ) -> Tuple[Union[str, None], List[str]]: """Find dimensions in data. Raise a ValueError if the dimensions don't match, except when the ``case`` dimension is omitted in ``dims``. Parameters ---------- ndvar : NDVar NDVar instance to query. dims : int | tuple of str The requested dimensions. extra_dim : str Dimension that will be removed by other operation (e.g. ``xax``). Returns ------- agg : None | str Dimension to aggregate over. dims : list of str Dimension names with all instances of ``None`` replaced by a string. """ if isinstance(dims, int): if extra_dim: dims += 1 dimnames = list(ndvar.dimnames) if ndvar.ndim == dims: agg = None elif ndvar.ndim == dims + 1: for agg in dimnames: if agg != extra_dim: break dimnames.remove(agg) else: raise ValueError(f"y={ndvar} has wrong number of dimensions; {dims} or {dims + 1} required") else: required_dims = (extra_dim, *dims) if extra_dim else dims if ndvar.ndim == len(required_dims): agg = None dimnames = list(ndvar.get_dimnames(required_dims)) elif ndvar.ndim == len(required_dims) + 1: if any(d is None for d in required_dims): if ndvar.has_case and 'case' not in required_dims: agg = 'case' else: raise ValueError(f"y={ndvar} is ambiguous for required dimensions {required_dims}") else: agg = None dimnames = list(ndvar.get_dimnames((agg, *required_dims))) agg = dimnames.pop(0) else: raise ValueError(f"y={ndvar} has wrong dimensions; {required_dims} or one more required") if extra_dim: dimnames.remove(extra_dim) return agg, dimnames def find_labels( cells: Sequence[CellArg], labels_arg: Dict[CellArg: str] = None, delim: str = ' ', ) -> Dict[CellArg, str]: if not labels_arg: return {cell: cellname(cell, delim) for cell in cells} labels = {} for cell in cells: if cell in labels_arg: label = labels_arg[cell] elif isinstance(cell, str): label = cell elif isinstance(cell, tuple): label = cellname([labels_arg.get(item, item) for item in cell], delim) else: raise TypeError(f"{cell=}") labels[cell] = label return labels def brain_data( data: Union[NDVar, testnd.NDTest], ): # for GlassBrain and surfer brain if isinstance(data, testnd.NDDifferenceTest): return data.masked_difference() else: return asndvar(data) def butterfly_data( data: Union[NDVar, testnd.NDTest], hemi: str, resample_: int = None, colors: bool = False, return_vector_data: bool = False, ): """Data for plotting butterfly plot with brain Returns ------- hemis : list of str Hemispheres in the data. butterfly_daya : Data for Butterfly plot. brain_data : Data for brain plot. """ # find input type if isinstance(data, NDVar): y = data kind = 'ndvar' elif isinstance(data, testnd.NDDifferenceTest): y = data.masked_difference() kind = 'ndvar' else: raise TypeError(f"ndvar={data!r}") source = y.get_dim('source') # find samplingrate if resample_ is not None: raise NotImplementedError(f"resample_={resample_}") # find hemispheres to include if hemi is None: hemis = [] if source.lh_n: hemis.append('lh') if source.rh_n: hemis.append('rh') elif hemi in ('lh', 'rh'): hemis = [hemi] else: raise ValueError("hemi=%r" % (hemi,)) if kind == 'ndvar': if y.has_case: y = y.mean('case') if resample_: y = resample(y, resample_, window='hamming') if y.has_dim('space'): if return_vector_data: brain_data = y y = y.norm('space') else: y = y.norm('space') brain_data = y else: brain_data = y bfly_data = [y.sub(source=hemi, name=hemi.capitalize()) for hemi in hemis] elif kind == 'test': sig = data.p <= 0.05 y_magnitude = y.rms('time') # resample if resample_: y = resample(y, resample_, window='hamming') sig = resample(sig, resample_) > 0.5 brain_data = y.mask(~sig) # mask non_sig = erode(~sig, 'time') y_sig = y.mask(non_sig) y_ns = y.mask(sig) # line-styles from ._colors import Style if colors: lh_color = '#046AAD' rh_color = '#A60628' line_color_sig = {'lh': lh_color, 'rh': rh_color} line_color_ns = {'lh': adjust_hsv(lh_color, 0, -0.5, -0.), 'rh': adjust_hsv(rh_color, 0, -0.7, -0.)} else: color_sig = (0,) * 3 color_ns = (.7,) * 3 line_color_sig = {'lh': color_sig, 'rh': color_sig} line_color_ns = {'lh': color_ns, 'rh': color_ns} linestyle_ns = {'linewidth': 0.2, 'color': line_color_ns, 'alpha': 0.2} linestyle_sig = {'linewidth': 0.2, 'color': line_color_sig, 'alpha': 1.0} # layer-data axes = [] for hemi in hemis: # z-order y_mag = y_magnitude.sub(source=hemi) z_order = dict(zip(y_mag.source, -y_mag.x.argsort())) # data layers = [] for y, linestyle in ((y_ns, linestyle_ns), (y_sig, linestyle_sig)): kwargs = {'zorder': z_order, **linestyle} layers.append(DataLayer(y.sub(source=hemi), PlotType.LINE, kwargs)) axes.append(AxisData(layers)) bfly_data = PlotData(axes, ('time', 'source'), plot_names=hemis) else: raise RuntimeError(f"kind={kind}") return hemis, bfly_data, brain_data def pop_if_dict(kwargs, key): "Helper for artist-sepcific matplotlib kwargs" if key in kwargs and isinstance(kwargs[key], dict): return kwargs.pop(key) def set_dict_arg(key, arg, line_dim_obj, artists, legend_handles=None): "Helper for artist-sepcific matplotlib kwargs" set_attr_name = 'set_' + key for dim_index, value in arg.items(): index = line_dim_obj._array_index(dim_index) if isinstance(index, int): key_artists = [artists[index]] else: key_artists = artists[index] if not key_artists: continue for artist in key_artists: getattr(artist, set_attr_name)(value) if legend_handles is not None: for artist in key_artists: artist.set_label(dim_index) legend_handles[dim_index] = artist _remap_args = {'c': 'color'} def _dict_arg(arg: dict = None) -> dict: if arg is None: return {} elif any(k in arg for k in _remap_args): return {_remap_args.get(k, k): v for k, v in arg.items()} else: return arg @dataclass(eq=False) class Layer: y: NDVar plot_type: PlotType = PlotType.GENERAL def bin(self, bin_length, tstart, tstop): raise NotImplementedError def sub_time(self, time: float, data_only: bool = False): raise NotImplementedError def for_plot(self, plot_type: PlotType) -> Iterator['DataLayer']: raise NotImplementedError @dataclass(eq=False) class DataLayer(Layer): """Data for one subplot layer""" _plot_args: dict = None _plot_args_2: dict = None # alternate (contour plot of IMAGE layer) _bin_func: callable = np.mean def __post_init__(self): self._plot_args = _dict_arg(self._plot_args) if self.plot_type == PlotType.IMAGE: self._plot_args_2 = _dict_arg(self._plot_args_2) elif self._plot_args_2: raise TypeError(f"plot_args_2={self._plot_args_2!r} for {self.plot_type}") def plot_args(self, kwargs: dict) -> dict: # needs to be a copy? return {**_dict_arg(kwargs), **self._plot_args} def contour_plot_args(self, contours): out = {} # contours arg meas = self.y.info.get('meas') if meas in contours: if contours[meas] is not None: out.update(contours[meas]) # layer if self.plot_type == PlotType.IMAGE: out.update(self._plot_args_2) elif self.plot_type == PlotType.CONTOUR: out.update(self._plot_args) else: raise RuntimeError(f"layer of type {self.plot_type}") return out def im_plot_args(self, vlims: dict, cmaps: dict) -> dict: assert self.plot_type == PlotType.IMAGE meas = self.y.info.get('meas') if meas in cmaps: cmap = cmaps[meas] elif 'cmap' in self.y.info: cmap = self.y.info['cmap'] else: cmap = DEFAULT_CMAPS.get(meas, 'xpolar') if meas in vlims: vmin, vmax = vlims[meas] else: vmin, vmax = find_vlim_args(self.y) vmin, vmax = fix_vlim_for_cmap(vmin, vmax, cmap) return {'cmap': cmap, 'vmin': vmin, 'vmax': vmax, **self._plot_args} def for_plot(self, plot_type: PlotType) -> Iterator['DataLayer']: if self.plot_type == plot_type: yield self elif not np.ma.isMaskedArray(self.y.x): yield DataLayer(self.y, plot_type, self._plot_args) elif plot_type == PlotType.LEGACY: yield DataLayer(self.y.unmask(), plot_type, self._plot_args) elif self.plot_type != PlotType.GENERAL: raise RuntimeError(f"Invalid PlotData conversion: {self.plot_type} -> {plot_type}") elif plot_type == PlotType.LINE: un_mask = NDVar(~self.y.x.mask, self.y.dims) # kwargs = {} if self.y.has_dim('time'): un_mask = erode(un_mask, 'time') # if self.y.ndim == 2: # mag = self.y.rms('time') # z_dim = mag.dimnames[0] # kwargs['zorder'] = dict(zip(mag.get_dim(z_dim), -mag.x.argsort())) y_masked = self.y.unmask().mask(un_mask) args_main = {'alpha': 1., 'zorder': 1} args_masked = {'alpha': 0.4, 'color': (.7, .7, .7), 'zorder': 0} for y, args in ((self.y, args_main), (y_masked, args_masked)): yield DataLayer(y, plot_type, args) elif plot_type == PlotType.IMAGE: x = NDVar(self.y.x.data, self.y.dims, self.y.name, self.y.info) yield DataLayer(x, PlotType.IMAGE) x = NDVar(1. - self.y.x.mask, self.y.dims, self.y.name, {'meas': 'mask'}) yield DataLayer(x, PlotType.CONTOUR, {'levels': [0.5], 'colors': ['black']}, _bin_func=np.max) else: raise RuntimeError(f"plot_type={plot_type!r}") def sub_time(self, time: float, data_only: bool = False): y = self.y.sub(time=time) if data_only: return y else: return DataLayer(y, self.plot_type, self._plot_args, self._plot_args_2, self._bin_func) def bin(self, bin_length, tstart, tstop): y = self.y.bin(bin_length, tstart, tstop, self._bin_func) return replace(self, y=y) @dataclass(eq=False) class StatLayer(Layer): style: Style = None ct: Celltable = None cell: CellArg = None mask: NDVar = None # mask needs to be applied to stats mask_missing: bool = True def _apply_mask(self, y: np.ndarray) -> np.ndarray: if self.mask is None: return y if np.ma.isMaskedArray(y): y = y.data return NDVar(y, self.y.dims[1:]).mask(self.mask, missing=self.mask_missing).x def get_statistic(self, func: Callable = np.mean) -> np.ndarray: return self._apply_mask(self.ct._get_func(self.cell, func)) def get_dispersion(self, spec, pool) -> np.ndarray: return self._apply_mask(self.ct._get_dispersion(self.cell, spec, pool)) def for_plot(self, plot_type: PlotType) -> Iterator['DataLayer']: if self.plot_type == plot_type: yield self elif self.mask is None: yield replace(self, plot_type=plot_type) elif plot_type == PlotType.LINE: inverse_mask = ~self.mask if self.y.has_dim('time'): inverse_mask = erode(inverse_mask, 'time') yield replace(self, plot_type=plot_type, style=self.style.masked_style, mask=inverse_mask, mask_missing=False) yield replace(self, plot_type=plot_type) else: raise NotImplementedError @dataclass(eq=False) class AxisData: """Represent one axis (multiple layers)""" layers: List[Layer] title: str = None def __iter__(self): return iter(self.layers) @property def y0(self): for layer in self.layers: return layer.y raise IndexError("No data") def for_plot(self, plot_type: PlotType) -> 'AxisData': return replace(self, layers=[l for layer in self.layers for l in layer.for_plot(plot_type)]) def bin(self, bin_length, tstart, tstop): return replace(self, layers=[l.bin(bin_length, tstart, tstop) for l in self.layers]) def sub_time(self, time: float, data_only: bool = False): axis = [] for layer in self.layers: if time in layer.y.time: axis.append(layer.sub_time(time, data_only)) if data_only: return axis else: return replace(self, layers=axis) def x_arg(x: CategorialArg): if isinstance(x, str) and x.startswith('.'): return None, x else: return x, None def combine_x_args(x, xax): if x is None: return xax elif xax is None: return x elif not isinstance(xax, x.__class__): raise TypeError(f"x={x}, xax={xax}: x and xax must be of same type or None") elif isinstance(xax, str): return f"({x}) % ({xax})" else: return x % xax @dataclass(eq=False) class PlotData: """Organize nd-data for plotting Notes ----- Two-stage initialization: - Initially independent of plot type - Layers contain masked NDVars - Converted into specific plot-types with :meth:`.for_plot` methods. - Masks converted into layers Additional consideration for statistics-plots (UTSStat) - Need central tendency and dispersion - Dispersion is not derivable from layer data (within-subject SEM) - Ideally potential to be dynamic (switch between viewing all data and statistic) Implementation - DataLayer subclass that keeps reference to a CellTable? """ plot_data: List[AxisData] # Data for each axis dims: Sequence[str] # Dimensions assigned to the axes frame_title: str = "unnamed data" # Default window title plot_names: List[Union[str, None]] = None # Titles for the plots (all non-None axes) plot_used: List[bool] = None # List indicating which plot slots are used plot_type: PlotType = PlotType.GENERAL ct: Celltable = None x: Union[Factor, Interaction] = None xax: Union[Factor, Interaction] = None def __post_init__(self): self.n_plots = len(self.plot_data) if self.plot_used is None: self.plot_used = [True] * self.n_plots else: assert sum(self.plot_used) == self.n_plots if self.plot_names is None: self.plot_names = [] for layers in self.plot_data: for layer in layers: if layer.y.name: self.plot_names.append(layer.y.name) break else: self.plot_names.append(None) def __repr__(self): desc = [f'{self.n_plots} plots'] if not all(self.plot_used): desc.append(f'{len(self.plot_used) - self.n_plots} empty') desc.append(' x '.join(self.dims)) return f"<PlotData {self.frame_title!r}: {", ".join(desc)}>" def _cannot_skip_axes(self, parent): if not all(self.plot_used): raise NotImplementedError(f"y can not contain None for {parent.__class__.__name__} plot") def __iter__(self): return iter(self.plot_data) @classmethod def from_args( cls, y: Union[NDVarArg, Sequence[NDVarArg]], dims: Union[int, Tuple[Optional[str], ...]], xax: CategorialArg = None, ds: Dataset = None, sub: IndexArg = None, ): """Unpack the first argument to top-level NDVar plotting functions Parameters ---------- y the first argument. dims The dimensions needed for the plotting function. ``None`` to indicate arbitrary dimensions. xax A model to divide ``y`` into different axes. ``xax`` is currently applied on the first level, i.e., it assumes that ``y``'s first dimension is cases. ds Dataset containing data objects which are provided as :class:`str`. sub Index selecting a subset of cases. Notes ----- Ndvar plotting functions above 1-d UTS level should support the following API: - simple NDVar: summary ``plot(meg)`` - by dim: each case ``plot(meg, '.case')`` - NDVar and xax argument: summary for each ``plot(meg, subject) - nested list of layers (e.g., ttest results: [c1, c0, [c1-c0, p]]) """ if isinstance(y, cls): return y elif isinstance(y, AxisData): for layer in y.layers: dims = find_data_dims(layer.y, dims) return PlotData([y], dims) sub = assub(sub, ds) if hasattr(y, '_default_plot_obj'): ys = getattr(y, '_default_plot_obj')() else: ys = y if isinstance(ys, NDVarTypes): ys = (ys,) ax_names = None if xax is None: # y=[[y1], y2], xax=None axes = [] for ax in ys: if ax is None: axes.append(None) elif isinstance(ax, NDVarTypes): ax = asndvar(ax, sub, ds) agg, dims = find_data_dims(ax, dims) layer = aggregate(ax, agg) axes.append([layer]) else: layers = [] for layer in ax: layer = asndvar(layer, sub, ds) agg, dims = find_data_dims(layer, dims) layers.append(aggregate(layer, agg)) axes.append(layers) x_name = None # determine y names y_names = [] for layers in axes: if layers is None: continue for layer in layers: if layer.name and layer.name not in y_names: y_names.append(layer.name) elif all(ax is None or isinstance(ax, NDVarTypes) for ax in ys): ys = [asndvar(layer, sub, ds) for layer in ys] y_names = [layer.name for layer in ys] layers = [] if isinstance(xax, str) and xax.startswith('.'): # y=[y1, y2], xax='.dim' dimname, attr = re.match(r'\.(\w+)(?:\.(\w+))?$', xax).groups() xax_dim = indexes = dissolve_dim = None for layer in ys: dim = layer.get_dim(dimname) if xax_dim is None: xax_dim = dim if attr is None: indexes = dim dissolve_dim = dimname # dissolved by indexing # axis labels unit = f' {xax_dim._axis_unit}' if xax_dim._axis_unit else '' ax_names = [f'{v}{unit}' for v in xax_dim] else: f = getattr(dim, attr) if not isinstance(f, Factor): raise ValueError(f'xax={xax!r}') indexes = [f == cell for cell in f.cells] ax_names = f.cells elif dim != xax_dim: raise ValueError(f"y={y}, xax={xax!r}: dimension not equal on different y") agg, dims = find_data_dims(layer, dims, dissolve_dim) layers.append([aggregate(layer.sub(**{dimname: i}), agg) for i in indexes]) x_name = xax else: # y=[y1, y2], xax=categorial xax = ascategorial(xax, sub, ds) xax_indexes = [xax == cell for cell in xax.cells] for layer in ys: agg, dims = find_data_dims(layer, dims) layers.append([aggregate(layer.sub(index), agg) for index in xax_indexes]) x_name = xax.name ax_names = [cellname(cell) for cell in xax.cells] axes = list(zip(*layers)) else: raise TypeError(f"{y=}, {xax=}: y can't be nested list if xax is specified, use single list") if len(y_names) == 0: y_name = None elif len(y_names) == 1: y_name = y_names[0] else: y_name = ', '.join(y_names) use_axes = [ax is not None for ax in axes] axes = [AxisData([DataLayer(l) for l in ax]) for ax in axes if ax] title = frame_title(y_name, x_name) return cls(axes, dims, title, ax_names, use_axes) @classmethod def from_stats( cls, y: Union[NDVarArg, Sequence[NDVarArg]], x: CategorialArg = None, xax: CategorialArg = None, match: CategorialArg = None, sub: IndexArg = None, ds: Dataset = None, dims: Tuple[Union[str, None]] = None, colors: dict = None, mask: Union[NDVar, Dict[CellArg, NDVar]] = None, ): if isinstance(y, (tuple, list)): if xax is not None: raise TypeError(f"{y=}, {xax=}: xax cannot be specified with multiple y") axes_data = [cls.from_stats(yi, x, xax, match, sub, ds, dims, colors, mask) for yi in y] axes = list(chain.from_iterable(ax.plot_data for ax in axes_data)) return replace(axes_data[0], plot_data=axes, plot_used=None, plot_names=None) x, x_dim = x_arg(x) xax, xax_dim = x_arg(xax) if x_dim or xax_dim: if isinstance(y, NDVar): varname = Dataset.as_key(y.name) else: varname = y if x_dim: dim = x_dim[1:] ds = melt_ndvar(y, dim, ds=ds, varname=varname) y = varname x = combine_x_args(x, dim) if xax_dim: dim = xax_dim[1:] ds = melt_ndvar(y, dim, ds=ds, varname=varname) y = varname xax = combine_x_args(xax, dim) x_full = combine_x_args(x, xax) ct = Celltable(y, x_full, match, sub, ds=ds) # data dimensions agg, dims = find_data_dims(ct.y, dims, 'case') if agg: raise NotImplementedError # reconstruct x/xax if xax is None: ax_cells = [None] else: xax = ct._align(xax, ds=ds, coerce=ascategorial) ax_cells = xax.cells if x is not None: x = ct._align(x, ds=ds, coerce=ascategorial) title = frame_title(y, x, xax) # find styles styles = find_cell_styles(ct.cells, colors) # find masks if mask is None: masks = defaultdict(lambda: None) elif isinstance(mask, NDVar): masks = defaultdict(lambda: mask) elif isinstance(mask, dict): masks = defaultdict(lambda: None, **mask) else: raise TypeError(f"{mask=}") # assemble layers axes = [] for ax_cell in ax_cells: if x is None: cells = [ax_cell] elif ax_cell is None: cells = x.cells else: x_cells = x.cells cells = [combine_cells(x_cell, ax_cell) for x_cell in x_cells] cells = [cell for cell in cells if cell in ct.data] layers = [StatLayer(ct.data[cell], style=styles[cell], ct=ct, cell=cell, mask=masks[cell]) for cell in cells] axes.append(AxisData(layers, cellname(ax_cell))) return cls(axes, dims, title, ct=ct, x=x, xax=xax) @classmethod def empty(cls, plots: Union[int, List[bool]], dims: Sequence[str], title: str): """Empty PlotData object that can be filled by appending to layers Parameters ---------- plots : int | list of bool Number of plots, or list of booleans indicating for each plot whether its slot is used. dims : sequence of str Names of the dimensions. title : str Data description for the plot frame. """ if isinstance(plots, int): plots = [AxisData([]) for _ in range(plots)] else: plots = [AxisData([]) if p else None for p in plots] return cls(plots, dims, title) @property def y0(self): for ax in self.plot_data: for layer in ax: return layer.y raise IndexError("No data") @property def default_y_label(self): "Y-label in case meas and unit are uninformative" names = {l.y.name for ax in self.plot_data for l in ax} names.discard(None) if len(names) == 1: return names.pop() return None @property def meas(self): meass = {l.y.info.get('meas') for ax in self.plot_data for l in ax} meass.discard(None) if len(meass) == 1: return meass.pop() return None @property def unit(self): units = {l.y.info.get('unit') for ax in self.plot_data for l in ax} units.discard(None) if len(units) == 1: return units.pop() return None @cached_property def data(self): "For backwards compatibility with nested list of NDVar" data = self.for_plot(PlotType.LEGACY) return [[l.y for l in layers] for layers in data.plot_data] @cached_property def time_dim(self): "UTS dimension to expose for time slicer" time_dims = [l.y.get_dim('time') for ax in self.plot_data for l in ax.layers if l.y.has_dim('time')] if time_dims: return reduce(UTS._union, time_dims) def for_plot(self, plot_type: PlotType) -> 'PlotData': if self.plot_type == plot_type: return self plot_data = [ax.for_plot(plot_type) for ax in self.plot_data] return replace(self, plot_data=plot_data, plot_type=plot_type) def bin(self, bin_length, tstart, tstop): axes = [ax.bin(bin_length, tstart, tstop) for ax in self.plot_data] return PlotData(axes, self.dims, self.frame_title, self.plot_names, self.plot_used, self.plot_type) def sub_time(self, time: float, data_only: bool = False): axes = [ax.sub_time(time, data_only) for ax in self.plot_data] if data_only: return axes else: dims = [dim for dim in self.dims if dim != 'time'] return PlotData(axes, dims, self.frame_title, self.plot_names, self.plot_used, self.plot_type) def aggregate(y, agg): return y if agg is None else y.mean(agg) class FigureFrame: def __init__(self, figure): self.figure = figure self.canvas = self.figure.canvas self._background = None def Close(self): pass def SetStatusText(self, text): pass def Show(self): pass def redraw(self, axes=(), artists=()): "Adapted duplicate of mpl_canvas.FigureCanvasPanel" self.canvas.restore_region(self._background) for ax in axes: ax.draw_artist(ax) extent = ax.get_window_extent() self.canvas.blit(extent) for artist in artists: artist.axes.draw_artist(artist.axes) extent = artist.axes.get_window_extent() self.canvas.blit(extent) def store_canvas(self): self._background = self.canvas.copy_from_bbox(self.figure.bbox) class MatplotlibFrame(FigureFrame): "Cf. _wxgui.mpl_canvas" def __init__(self, **fig_kwargs): "Create self.figure and self.canvas attributes and return the figure" from matplotlib import pyplot figure = pyplot.figure(**fig_kwargs) FigureFrame.__init__(self, figure) self._plt = pyplot def Close(self): self._plt.close(self.figure) def Show(self): if mpl.get_backend() == 'WXAgg' and do_autorun(): self._plt.show() def frame_title(y, x=None, xax=None): """Generate frame title from common data structure Parameters ---------- y : data-obj | str Dependent variable. x : data-obj | str Predictor. xax : data-obj | str Grouping variable for axes. """ if isdataobject(y): y = y.name if isdataobject(x): x = x.name if isdataobject(xax): xax = xax.name if xax is None: if x is None: return "%s" % (y,) else: return "%s ~ %s" % (y, x) elif x is None: return "%s | %s" % (y, xax) else: return "%s ~ %s | %s" % (y, x, xax) class MatplotlibFigure: """Wrap a matplotlib figure for FMText""" def __init__(self, figure): self.figure = figure def _asfmtext( self, rasterize: bool = None, close_figures: bool = None, ): if rasterize is None: format = None elif rasterize: format = 'png' else: format = 'svg' return self.image(format=format, close=close_figures) def close(self): from matplotlib import pyplot pyplot.close(self.figure) def image(self, name: str = None, format: str = None, close: bool = None): """Create FMTXT Image from the figure Parameters ---------- name Name for the file (without extension; default is 'image'). format File format. For HTML, use ``svg`` for vector graphics and ``png`` for pixel graphics. The default is ``svg`` and can be changed with :func:`configure`). close Close the figure after writing to the ``image``. By default, this is ``True`` when in an inline context (Jupyter notebook), ``False`` otherwise). Returns ------- image : fmtxt.Image Image FMTXT object. """ if format is None: format = CONFIG['format'] image = Image(name, format) self.figure.savefig(image, format=format) if close or (close is None and use_inline_backend()): self.close() return image class EelFigure(MatplotlibFigure): """Parent class for Eelbrain figures. In order to subclass: - find desired figure properties and then use them to initialize the _EelFigure superclass; then use the :py:attr:`_EelFigure.figure` and :py:attr:`_EelFigure.canvas` attributes. - end the initialization by calling `_EelFigure._show()` - add the :py:meth:`_fill_toolbar` method """ _default_xlabel_ax = -1 _default_ylabel_ax = 0 _make_axes = True _can_set_time = False _can_set_vlim = False _can_set_ylim = False _can_set_xlim = False _has_frame = False def __init__(self, data_desc: Optional[str], layout: BaseLayout): """Parent class for Eelbrain figures. Parameters ---------- data_desc Data description for frame title. layout Layout that determines figure dimensions. """ name = self.__class__.__name__ desc = layout.name or data_desc self._title = f'{name}: {desc}' if desc else name # Use Eelbrain frame or pyplot if layout.user_axes: ax = layout.user_axes[0] frame = FigureFrame(ax.get_figure()) elif CONFIG['eelbrain'] and not use_inline_backend(): from .._wxgui import wx, get_app from .._wxgui.mpl_canvas import CanvasFrame get_app() pos = wx.DefaultPosition if layout.pos is None else layout.pos frame = CanvasFrame(title=self._title, eelfigure=self, pos=pos, **layout.fig_kwa()) self._has_frame = True else: frame = MatplotlibFrame(**layout.fig_kwa()) figure = frame.figure if layout.title: self._figtitle = figure.suptitle(layout.title) else: self._figtitle = None # make axes if self._make_axes: axes = layout.make_axes(figure) else: axes = [] # store attributes MatplotlibFigure.__init__(self, figure) self._frame = frame self.axes = axes self.canvas = frame.canvas self._layout = layout self._last_draw_time = 1. self.__callback_key_press = {} self.__callback_key_release = {} # containers for hooks self._draw_hooks = [] self._untight_draw_hooks = [] # options self._draw_crosshairs = False self._crosshair_lines = None self._crosshair_axes = None # add callbacks self.canvas.mpl_connect('motion_notify_event', self._on_motion) self.canvas.mpl_connect('axes_leave_event', self._on_leave_axes) self.canvas.mpl_connect('resize_event', self._on_resize) self.canvas.mpl_connect('key_press_event', self._on_key_press) self.canvas.mpl_connect('key_release_event', self._on_key_release) def __repr__(self): title = self._frame.GetTitle() if self._has_frame else self._title return f'<{title}>' def _ipython_display_(self): from IPython.display import display display(self.figure) def _set_axtitle( self, axtitle: Union[bool, str, Iterator[str]] = None, data: PlotData = None, axes: Union[List[matplotlib.axes.Axes], int] = None, names: Sequence[str] = None, **kwargs, ): """Set axes titles automatically Parameters ---------- axtitle Plot parameter. data Plotted data (if available). axes Axes for which to set title (default is self.axes). If an int, (n axes) the method does not set axes title but returns ``None`` or a tuple of titles. names Instead of using ``epochs`` name attributes, use these names. ... Matplotlib ``Axes.set_title()`` parameters. """ if axtitle is False or axtitle is None: return if axes is None: axes = self.axes naxes = axes if isinstance(axes, int) else len(axes) if axtitle is True and naxes == 1: return elif axtitle is True or isinstance(axtitle, str): if names is None: if data is None: raise RuntimeError(f"data=None and names=None with {axtitle=}") names = data.plot_names if axtitle is True: axtitle = names else: axtitle = [axtitle.format(name=n) if n else None for n in names] if isinstance(axes, int): return axtitle for title, ax in zip(axtitle, axes): if title is not None: ax.set_title(asfmtext(title), **kwargs) def _show(self, crosshair_axes=None): if self._layout.user_axes: return if self._layout.tight: self._tight() if crosshair_axes is None: self._crosshair_axes = self.axes else: self._crosshair_axes = crosshair_axes self.draw() # Allow hooks to modify figure after first draw need_redraw = any([func() for func in self._draw_hooks]) if not self._layout.tight: need_redraw = any([func() for func in self._untight_draw_hooks]) or need_redraw if need_redraw: self.draw() if CONFIG['show'] and self._layout.show: self._frame.Show() if self._has_frame and do_autorun(self._layout.run): from .._wxgui import run run() if self._has_frame and not self.canvas._background: self._frame.store_canvas() def _tight(self): "Default implementation based on matplotlib" try: self.figure.tight_layout() except ValueError as exception: getLogger('eelbrain').debug('tight-layout: %s', exception) if self._figtitle: trans = self.figure.transFigure.inverted() extent = self._figtitle.get_window_extent(self.figure.canvas.renderer) bbox = trans.transform(extent) t_bottom = bbox[0, 1] self.figure.subplots_adjust(top=1 - 2 * (1 - t_bottom)) def _on_key_press(self, event): if event.key in self.__callback_key_press: self.__callback_key_press[event.key](event) event.guiEvent.Skip(False) # Matplotlib Skip()s all events def _on_key_release(self, event): if event.key in self.__callback_key_release: self.__callback_key_release[event.key](event) event.guiEvent.Skip(False) def _on_leave_axes(self, event): "Update the status bar when the cursor leaves axes" if self._frame is None: return self._frame.SetStatusText(self._on_leave_axes_status_text(event)) if self._draw_crosshairs: self._remove_crosshairs(True) def _on_leave_axes_status_text(self, event): return '☺︎' def _on_motion(self, event): "Update the status bar for mouse movement" if self._frame is None: return redraw_axes = self._on_motion_sub(event) ax = event.inaxes # draw crosshairs if self._draw_crosshairs and ax in self._crosshair_axes: if self._crosshair_lines is None: self._crosshair_lines = tuple( (ax.axhline(event.ydata, color='k'), ax.axvline(event.xdata, color='k')) for ax in self._crosshair_axes) else: for hline, vline in self._crosshair_lines: hline.set_ydata([event.ydata, event.ydata]) vline.set_xdata([event.xdata, event.xdata]) redraw_axes.update(self._crosshair_axes) # update status bar self._frame.SetStatusText(self._on_motion_status_text(event)) # redraw self.canvas.redraw(redraw_axes) @staticmethod def _on_motion_status_text(event): ax = event.inaxes if ax: return ('x = %s, y = %s' % ( ax.xaxis.get_major_formatter().format_data_short(event.xdata), ax.yaxis.get_major_formatter().format_data_short(event.ydata))) return '' def _on_motion_sub(self, event): "Subclass action on mouse motion, return set of axes to redraw" return set() def _on_resize(self, event): if self._layout.tight: self._tight() def _register_key(self, key, press=None, release=None): if press: if key in self.__callback_key_press: raise RuntimeError("Attempting to assign key press %r twice" % key) self.__callback_key_press[key] = press if release: if key in self.__callback_key_release: raise RuntimeError("Attempting to assign key release %r twice" % key) self.__callback_key_release[key] = release def _remove_crosshairs(self, draw=False): if self._crosshair_lines is not None: for hline, vline in self._crosshair_lines: hline.remove() vline.remove() self._crosshair_lines = None if draw: self.canvas.redraw(self._crosshair_axes) def _fill_toolbar(self, tb): """ Add toolbar tools Subclasses should add their toolbar items in this function which is called by ``CanvasFrame.FillToolBar()``. """ pass def close(self): "Close the figure." self._frame.Close() def _get_axes(self, axes): "Iterate over axes corresponding to ``axes`` parameter" if axes is None: return self.axes elif isinstance(axes, int): return self.axes[axes], else: return (self.axes[i] for i in axes) def _configure_axis( self, axis: str, # 'x' | 'y' ticklabels: Union[str, int, Sequence[int]], # where to show tick-labels params: Iterable, # (formatter, locator, label) for each Axes axes: List[matplotlib.axes.Axes] = None, # axes which to format ): if axes is None: axes = self.axes # find axes with tick-labels nax = len(axes) if isinstance(ticklabels, bool): show_ticklabels = [ticklabels] * nax elif isinstance(ticklabels, str): if ticklabels == 'bottom': if all(isinstance(ax, matplotlib.axes.SubplotBase) for ax in axes): subplotspecs = [ax.get_subplotspec() for ax in axes] bottom = min([spec.rowspan.stop for spec in subplotspecs]) show_ticklabels = [spec.rowspan.stop == bottom for spec in subplotspecs] else: first = len(axes) - min(self._layout.ncol, nax) show_ticklabels = [i >= first for i in range(len(axes))] elif ticklabels == 'left': if all(isinstance(ax, matplotlib.axes.SubplotBase) for ax in axes): subplotspecs = [ax.get_subplotspec() for ax in axes] left = min([spec.colspan.start for spec in subplotspecs]) show_ticklabels = [spec.colspan.start == left for spec in subplotspecs] else: ncol = self._layout.ncol or nax show_ticklabels = [i % ncol == 0 for i in range(len(axes))] elif ticklabels == 'all': show_ticklabels = [True] * nax elif ticklabels == 'none': show_ticklabels = [False] * nax else: raise ValueError(f"ticklabels={ticklabels!r}") else: show_ticklabels = [False] * nax if isinstance(ticklabels, int): show_ticklabels[ticklabels] = True else: for i in ticklabels: show_ticklabels[i] = True # parameter for hiding tick-labels if axis == 'y': tick_params = {'labelleft': False} else: tick_params = {'labelbottom': False} # format ticks labels = [] for ax, (formatter, locator, label_), show_ticklabels_ in zip(axes, params, show_ticklabels): axis_ = ax.yaxis if axis == 'y' else ax.xaxis if locator: axis_.set_major_locator(locator) if formatter: axis_.set_major_formatter(formatter) if not show_ticklabels_: ax.tick_params(**tick_params) labels.append(label_) # set labels if any(labels): if len(set(labels)) == 1: # default positioning if axis == 'y': self.set_ylabel(labels[0]) else: self.set_xlabel(labels[0]) else: for ax, label in zip(axes, labels): if label: if axis == 'y': ax.set_ylabel(label) else: ax.set_xlabel(label) def _configure_axis_data( self, axis: str, # 'x' | 'y' data: NDVar, # data for default label label: Union[bool, str], # override label ticklabels: Union[str, int, Sequence[int]] = True, # where to show tick-labels axes: List[matplotlib.axes.Axes] = None, # axes which to format ): "Configure an axis based on data" scale = AxisScale(data, label) formatters = repeat(scale.formatter) if not isinstance(scale.label, str) and isinstance(scale.label, Iterable): labels = chain(scale.label, repeat(None)) else: labels = repeat(scale.label) params = zip(formatters, repeat(None), labels) self._configure_axis(axis, ticklabels, params, axes) def _configure_axis_dim( self, axis: str, # 'x' | 'y' dim: Union[str, Dimension], # The dimension assigned to the axis label: Union[bool, str], # axis labale ticklabels: Union[str, int, Sequence[int]], # where to show tick-labels axes: List[matplotlib.axes.Axes] = None, # axes which to format scalar: bool = True, data: List = None, ): "Configure an axis based on a dimension" # Dimension objects if isinstance(dim, str): dims = [layers[0].get_dim(dim) for layers in data] else: dims = repeat(dim) params = (dim._axis_format(scalar, label) for dim in dims) self._configure_axis(axis, ticklabels, params, axes) def draw(self): "(Re-)draw the figure (after making manual changes)." if self._frame is None: return t0 = time.time() self._frame.canvas.draw() self._last_draw_time = time.time() - t0 def draw_crosshairs(self, enable=True): """Draw crosshairs under the cursor Parameters ---------- enable : bool Enable drawing crosshairs (default True, set to False to disable). """ self._draw_crosshairs = enable if not enable: self._remove_crosshairs(True) def draw_outline(self, color='k', **kwargs): """Draw the outline of the figure Mainly for fine-tuning the figure layout in Jupyter, which crops the display area based on figure elements rather than actual figure size. """ kwargs.setdefault('fc', 'none') artist = matplotlib.patches.Rectangle((0, 0), 1, 1, ec=color, **kwargs) self.figure.add_artist(artist) def save(self, *args, **kwargs): "Short-cut for Matplotlib's :meth:`~matplotlib.figure.Figure.savefig()`" self.figure.savefig(*args, **kwargs) def add_hline(self, y, axes=None, *args, **kwargs): """Draw a horizontal line on one or more axes Parameters ---------- y : scalar Level at which to draw the line. axes : int | list of int Which axes to mark (default is all axes). ... :meth:`matplotlib.axes.Axes.axhline` parameters. Notes ----- See Matplotlib's :meth:`matplotlib.axes.Axes.axhline` for more arguments. """ for ax in self._get_axes(axes): ax.axhline(y, *args, **kwargs) self.draw() def add_hspan(self, bottom, top, axes=None, *args, **kwargs): """Draw a horizontal bar on one or more axes Parameters ---------- bottom : scalar Bottom end of the horizontal bar. top : scalar Top end of the horizontal bar. axes : int | list of int Which axes to mark (default is all axes). ... :meth:`matplotlib.axes.Axes.axvspan` parameters. Notes ----- See Matplotlib's :meth:`matplotlib.axes.Axes.axhspan` for more arguments. """ for ax in self._get_axes(axes): ax.axhspan(bottom, top, *args, **kwargs) self.draw() def add_vline(self, x, axes=None, *args, **kwargs): """Draw a vertical line on one or more axes Parameters ---------- x : scalar Value at which to place the vertical line. axes : int | list of int Which axes to mark (default is all axes). ... :meth:`matplotlib.axes.Axes.axvspan` parameters. Notes ----- See Matplotlib's :meth:`matplotlib.axes.Axes.axvline` for more arguments. """ for ax in self._get_axes(axes): ax.axvline(x, *args, **kwargs) self.draw() def add_vspan(self, xmin, xmax, axes=None, *args, **kwargs): """Draw a vertical bar on one or more axes Parameters ---------- xmin : scalar Start value on the x-axis. xmax : scalar Last value on the x-axis. axes : int | list of int Which axes to mark (default is all axes). ... :meth:`matplotlib.axes.Axes.axvspan` parameters. Notes ----- See Matplotlib's :meth:`matplotlib.axes.Axes.axvspan` for more arguments. """ for ax in self._get_axes(axes): ax.axvspan(xmin, xmax, *args, **kwargs) self.draw() def set_name(self, name): """Set the figure window title""" plot_name = self.__class__.__name__ self._frame.SetTitle(f'{plot_name}: {name}' if name else plot_name) def set_xtick_rotation(self, rotation): """Rotate every x-axis tick-label by an angle (counterclockwise, in degrees) Parameters ---------- rotation : scalar Counterclockwise rotation angle, in degrees. """ for ax in self.axes: for t in ax.get_xticklabels(): t.set_rotation(rotation) self.draw() def set_xlabel(self, label: str, ax: int = None): """Set the label for the x-axis Parameters ---------- label X-axis label. ax Axis on which to set the label (default is usually the last axis). """ if ax is None: ax = self._default_xlabel_ax self.axes[ax].set_xlabel(label) def set_ylabel(self, label: str, ax: int = None): """Set the label for the y-axis Parameters ---------- label Y-axis label. ax Axis on which to set the label (default is usually the first axis). """ if ax is None: ax = self._default_ylabel_ax self.axes[ax].set_ylabel(label) def format_axes( ax: mpl.axes.Axes, frame: Union[bool, str], yaxis: bool, ): if frame == 't': ax.tick_params(direction='inout', bottom=False, top=True, left=False, right=True, labelbottom=True, labeltop=False, labelleft=True, labelright=False) ax.spines['right'].set_position('zero') ax.spines['left'].set_visible(False) ax.spines['top'].set_position('zero') ax.spines['bottom'].set_visible(False) elif frame == 'none': for spine in ax.spines.values(): spine.set_visible(False) elif frame == 'off': ax.axis('off') elif not frame: ax.yaxis.set_ticks_position('left') ax.spines['right'].set_visible(False) ax.xaxis.set_ticks_position('bottom') ax.spines['top'].set_visible(False) if not yaxis: ax.yaxis.set_ticks(()) ax.spines['left'].set_visible(False) class BaseLayout: def __init__( self, h: float, w: float, dpi: float, tight: bool, show: bool, run: bool, title: FMTextArg = None, autoscale: bool = False, name: str = None, right_of: Union[EelFigure, int] = None, below: Union[EelFigure, int] = None, axes: Union[matplotlib.axes.Axes, List[matplotlib.axes.Axes]] = None, ): self.h = h self.w = w self.dpi = dpi or mpl.rcParams['figure.dpi'] self.tight = tight self.show = show self.run = run self.autoscale = autoscale self.title = asfmtext_or_none(title) self.name = asfmtext_or_none(name) or title if isinstance(axes, matplotlib.axes.Axes): axes = [axes] elif axes is not None: axes = list(axes) self.user_axes = axes x = y = None if hasattr(right_of, '_frame'): rect = right_of._frame.GetRect() x = rect.GetRight() + 1 if below is None: y = rect.GetTop() elif isinstance(right_of, int): x = right_of elif right_of is not None: raise TypeError(f"{right_of=}") if hasattr(below, '_frame'): rect = below._frame.GetRect() y = rect.GetBottom() + 1 if x is None: x = rect.GetLeft() elif isinstance(below, int): y = below elif below is not None: raise TypeError(f"{below=}") if x is None and y is None: self.pos = None else: if x is None: x = -1 if y is None: y = -1 self.pos = (x, y) def fig_kwa(self): out = {'figsize': (self.w, self.h), 'dpi': self.dpi} if CONFIG['figure_background'] is not False: out['facecolor'] = CONFIG['figure_background'] return out def make_axes(self, figure): if self.user_axes: axes = self.user_axes else: axes = self._make_axes(figure) self._configure_axes(axes) return axes def _make_axes(self, figure): raise NotImplementedError def _configure_axes(self, axes): raise NotImplementedError def resolve_plot_rect(w, h, dpi): # infer figure dimensions from screen size w_applies = w is not None and w <= 0 h_applies = h is not None and h <= 0 if w_applies or h_applies: from .._wxgui import wx, get_app get_app() effective_dpi = dpi or mpl.rcParams['figure.dpi'] display_w, display_h = wx.GetDisplaySize() if h_applies: effective_display_h = display_h - 50 h = effective_display_h / effective_dpi + h if w_applies: w = display_w / effective_dpi + w return w, h class LayoutDim: "Helper function to determine figure spacing" _properties = ('total', 'ax', 'first', 'last', 'space') _equations = dict( total='first + n_ax * ax + (n_ax - 1) * space + last', ax='(total - first - last - (n_ax - 1) * space) / n_ax', first='total - n_ax * ax - (n_ax - 1) * space - last', last='total - first - n_ax * ax - (n_ax - 1) * space', space='(total - first - n_ax * ax - last) / (n_ax - 1)', ) def __init__(self, n_ax, total, ax, first, space, last, ax_default, first_default, space_default, last_default): if space is None and n_ax == 1: space = 0. values = {'total': total, 'first': first, 'space': space, 'last': last, 'ax': ax, 'n_ax': n_ax} defaults = {'first': first_default, 'space': space_default, 'last': last_default, 'ax': ax_default} for i, p in enumerate(self._properties): if values[p] is None: for p2 in self._properties[i + 1:]: if values[p2] is None: values[p2] = defaults[p2] values[p] = eval(self._equations[p], values) break self.total = values['total'] self.ax = values['ax'] self.first = values['first'] self.space = values['space'] self.last = values['last'] class Layout(BaseLayout): """Layout for figures with several axes of the same size""" _default_margins = {'left': 0.4, 'bottom': 0.5, 'right': 0.05, 'top': 0.05, 'wspace': 0.1, 'hspace': 0.1} def __init__( self, nax: Union[int, List[bool]], ax_aspect: float, # width / height axh_default: float, tight: bool = True, title: str = None, h: float = None, w: float = None, axh: float = None, axw: float = None, nrow: int = None, ncol: int = None, dpi: float = None, margins: Dict[str, float] = None, show: bool = True, run: bool = None, frame: Union[bool, str] = True, yaxis=True, share_axes: bool = False, **kwargs): """Create a grid of axes based on variable parameters. Parameters ---------- nax Number of axes required. If provided as a list, axes are only added for items where ``item`` is True. ax_aspect Width / height aspect of the axes. axh_default The default axes height if it can not be determined from the other parameters. tight Rescale axes so that the space in the figure is used optimally (default True). title : str Figure title. h Height of the figure. w Width of the figure. axh Height of the axes. axw Width of the axes. nrow Set a limit to the number of rows (default is no limit). ncol Set a limit to the number of columns (defaut is no limit). If neither nrow or ncol is specified, a square layout is preferred. dpi DPI for the figure (default is to use matplotlib rc parameters). margins Absolute subplot parameters (in inches). Implies ``tight=False``. If ``margins`` is specified, ``axw`` and ``axh`` are interpreted exclusive of the margins, i.e., ``axh=2, margins={'top': .5}`` for a plot with one axes will result in a total height of 2.5. show Show the figure in the GUI (default True). Use False for creating figures and saving them without displaying them on the screen. run Run the Eelbrain GUI app (default is True for interactive plotting and False in scripts). frame : bool | 't' | 'none' Draw frame around axes: - True: all four spines - False: only spines with ticks - 't': spines at x=0 and y=0 - 'none': no spines at all """ if h and axh: if h < axh: raise ValueError("h < axh") if w and axw: if w < axw: raise ValueError("w < axw") w, h = resolve_plot_rect(w, h, dpi) self.h_fixed = h self.w_fixed = w if w is not None else axw self._margins_arg = margins if margins is True: use_margins = True tight = False margins = self._default_margins.copy() elif margins is not None: use_margins = True tight = False margins = dict(margins) invalid = set(margins).difference(self._default_margins) if invalid: raise ValueError(f"{margins=}: Unknown keys {invalid}") else: margins = {k: 0 for k in self._default_margins} use_margins = False h_is_implicit = h is None w_is_implicit = w is None if nax is None: axes = None elif isinstance(nax, int): axes = list(range(nax)) elif isinstance(nax, (list, tuple)): axes = [i for i, ax in enumerate(nax) if ax] nax = len(nax) else: raise TypeError("nax=%r" % (nax,)) trim = None if not nax: if w is None: if h is None: h = axh_default w = ax_aspect * h elif h is None: h = w / ax_aspect elif nax == 1: ncol = ncol or 1 nrow = nrow or 1 elif nrow is None and ncol is None: if w and axw: trim = 'row' ncol = math.floor(w / axw) elif h and axh: trim = 'col' nrow = math.floor(h / axh) elif w: trim = 'row' if axh: ncol = round(w / (axh * ax_aspect)) else: ncol = round(w / (axh_default * ax_aspect)) ncol = max(1, min(nax, ncol)) elif h: trim = 'col' if axw: nrow = round(h / (axw / ax_aspect)) else: nrow = round(h / axh_default) nrow = max(1, min(nax, nrow)) elif axh or axw: trim = 'row' if not axh: axh = axw / ax_aspect nrow = min(nax, math.floor(defaults['maxh'] / axh)) else: trim = 'row' # default: minimum number of columns (max number of rows) hspace = margins.get('hspace', 0) maxh = defaults['maxh'] - margins.get('top', 0) - margins.get('bottom', 0) + hspace axh_with_space = axh_default + hspace nrow = min(nax, math.floor(maxh / axh_with_space)) ncol = math.ceil(nax / nrow) # test width wspace = margins.get('wspace', 0) maxw = defaults['maxw'] - margins.get('left', 0) - margins.get('right', 0) + wspace axw_with_space = axh_default * ax_aspect + wspace if ncol * axw_with_space > maxw: # nrow/ncol proportional to (maxh / axh) / (maxw / axw) ratio = (maxh / axh_with_space) / (maxw / axw_with_space) # nax = ncol * (ncol * ratio) # ncol = sqrt(nax / ratio) ncol = math.floor(math.sqrt(nax / ratio)) nrow = math.ceil(nax / ncol) axh = (maxh - nrow * hspace) / nrow axw = axh * ax_aspect if nax: if nrow is None: nrow = math.ceil(nax / ncol) elif ncol is None: ncol = math.ceil(nax / nrow) if trim == 'row': if (nrow * ncol) - nax >= ncol: nrow -= 1 elif trim == 'col': if (nrow * ncol) - nax >= nrow: nrow -= 1 if axw: axh_default = axw / ax_aspect elif w: axh_default = w / ncol / ax_aspect h_dim = LayoutDim(nrow, h, axh, margins.get('top'), margins.get('hspace'), margins.get('bottom'), axh_default, self._default_margins['top'], self._default_margins['hspace'], self._default_margins['bottom']) w_dim = LayoutDim(ncol, w, axw, margins.get('left'), margins.get('wspace'), margins.get('right'), h_dim.ax * ax_aspect, self._default_margins['left'], self._default_margins['wspace'], self._default_margins['right']) h = h_dim.total w = w_dim.total axh = h_dim.ax axw = w_dim.ax margins = { 'top': h_dim.first, 'bottom': h_dim.last, 'hspace': h_dim.space, 'left': w_dim.first, 'right': w_dim.last, 'wspace': w_dim.space} h_is_implicit = w_is_implicit = False if h_is_implicit: hspace = 0 if nrow is None else margins['hspace'] * (nrow - 1) h += margins['bottom'] + hspace + margins['top'] if w_is_implicit: wspace = 0 if ncol is None else margins['wspace'] * (ncol - 1) w += margins['left'] + wspace + margins['right'] BaseLayout.__init__(self, h, w, dpi, tight, show, run, title, **kwargs) self.nax = nax self.axes = axes self.axh = axh self.axw = axw self.nrow = nrow self.ncol = ncol self.frame = frame self.yaxis = yaxis self.share_axes = share_axes self.margins = margins if use_margins else None def __repr__(self): kwargs = self.fig_kwa() if 'subplotpars' in kwargs: pars = kwargs['subplotpars'] attrs = ((k, getattr(pars, k)) for k in ('left', 'right', 'bottom', 'top', 'wspace', 'hspace')) desc = ', '.join(f'{k}={v}' for k, v in attrs if v is not None) kwargs['subplotpars'] = f"<{desc}>" args = ', '.join(f'{k}={v}' for k, v in kwargs.items()) return f'<Layout: {args}>' def fig_kwa(self): out = BaseLayout.fig_kwa(self) if self.margins: # absolute subplot parameters out['subplotpars'] = SubplotParams( self.margins['left'] / self.w, self.margins['bottom'] / self.h, 1 - self.margins['right'] / self.w, 1 - self.margins['top'] / self.h, # space expressed as a fraction of the average axis height/width self.margins['wspace'] / self.axw, self.margins['hspace'] / self.axh) return out def _make_axes(self, figure): if not self.nax: return [] axes = [] kwargs = {} for i in self.axes: ax = figure.add_subplot(self.nrow, self.ncol, i + 1, autoscale_on=self.autoscale, **kwargs) axes.append(ax) if self.share_axes: kwargs.update(sharex=ax, sharey=ax) return axes def _configure_axes(self, axes): for ax in axes: format_axes(ax, self.frame, self.yaxis) return axes class ImLayout(Layout): """Layout subclass for axes without space Make sure to specify the ``margins`` parameter for absolute spacing """ def __init__( self, nax: Union[int, List[bool]], ax_aspect: float, # width / height axh_default: float, margins: dict = None, default_margins: dict = None, title: str = None, axtitle: Union[bool, Sequence[str]] = False, # for default spacing **kwargs, ): if axtitle is True: has_axtitle = (len(nax) if isinstance(nax, list) else nax) > 1 else: has_axtitle = True if isinstance(axtitle, np.ndarray) else bool(axtitle) title_space = 1.5 * mpl_font_size('figure.titlesize') if title else 0 axtitle_space = 1.5 * mpl_font_size('axes.titlesize') if has_axtitle else 0 margins_ = { 'left': 0, 'wspace': 0, 'right': 0, 'top': axtitle_space + title_space, 'hspace': axtitle_space, 'bottom': 0, } if default_margins: margins_.update(default_margins) if margins: margins_.update(margins) Layout.__init__(self, nax, ax_aspect, axh_default, title=title, margins=margins_, **kwargs) def _make_axes(self, figure): axes = [] for i in self.axes: ax = figure.add_subplot(self.nrow, self.ncol, i + 1, autoscale_on=self.autoscale) axes.append(ax) return axes def _configure_axes(self, axes): for ax in axes: ax.axis('off') class VariableAspectLayout(BaseLayout): """Layout with a fixed number of columns that differ in spacing Axes are originally created to fill the whole rectangle allotted to them. Developed for TopoButterfly plot: one variable aspect butterfly plot, and one square topomap plot. Parameters ---------- nrow Number of rows. axh_default Default row height. w_default Default figure width. aspect Axes aspect ratio (w/h) for each column; None for axes with flexible width. ax_kwargs Parameters for :meth:`figure.add_axes` for each column. ax_frames ``frame`` parameter for :func:`format_axes` for each column. row_titles One title per row. """ def __init__( self, nrow: int, axh_default: float, w_default: float, aspect: Sequence[Optional[float]] = (None, 1), ax_kwargs: Sequence[dict] = None, ax_frames: Sequence[bool] = None, row_titles: Sequence[Optional[str]] = None, title: FMTextArg = None, h: float = None, w: float = None, axh: float = None, dpi: float = None, show: bool = True, run: bool = None, **kwargs, ): w, h = resolve_plot_rect(w, h, dpi) self.w_fixed = w if axh and h: raise ValueError("h and axh can not be specified both at the same time") elif h: axh = h / nrow elif axh: h = nrow * axh else: axh = axh_default h = nrow * axh if w is None: w = w_default if ax_kwargs is None: ax_kwargs = [{}] * len(aspect) if ax_frames is None: ax_frames = [True] * len(aspect) BaseLayout.__init__(self, h, w, dpi, False, show, run, title, **kwargs) self.nax = nrow * len(aspect) self.axh = axh self.nrow = nrow self.ncol = len(aspect) self.share_axes = False self.row_titles = row_titles self.aspect = aspect self.n_flexible = self.aspect.count(None) self.ax_kwargs = ax_kwargs self.ax_frames = ax_frames # Compute axes outlines for given height and width h = self.h w = self.w text_buffer = 20 * POINT # buffers for legends left_buffer = text_buffer * (3 + (self.row_titles is not None)) bottom_buffer = text_buffer * 2 top_buffer = text_buffer * (1 + 2 * bool(self.title)) # rectangle base in inches axh = (h - bottom_buffer - top_buffer) / self.nrow axws = [None if a is None else a * axh for a in self.aspect] fixed = sum(axw for axw in axws if axw is not None) w_free = (w - fixed - left_buffer) / self.n_flexible widths = [w_free if axw is None else axw for axw in axws] lefts = (sum(widths[:i]) + left_buffer for i in range(len(widths))) bottoms = (i * axh + bottom_buffer for i in range(self.nrow - 1, -1, -1)) # convert to figure coords height = axh / h lefts_ = [l / w for l in lefts] widths_ = [w_ / w for w_ in widths] bottoms_ = [b / h for b in bottoms] # rectangles: (left, bottom, width, height) self._ax_rects = [[(l, bottom, w, height) for l, w in zip(lefts_, widths_)] for bottom in bottoms_] def _make_axes(self, figure): axes = [] for row, row_rects in enumerate(self._ax_rects): for rect, kwa, frame in zip(row_rects, self.ax_kwargs, self.ax_frames): ax = figure.add_axes(rect, autoscale_on=self.autoscale, **kwa) axes.append(ax) if self.row_titles and self.row_titles[row]: bottom, height = rect[1], rect[3] figure.text(0, bottom + height / 2, self.row_titles[row], ha='left', va='center', rotation='vertical') return axes def _configure_axes(self, axes): for ax, frame in zip(axes, cycle(self.ax_frames)): format_axes(ax, frame, True) # id axes for callbacks for i, ax in enumerate(axes): ax.id = i def subplots( nrows: int = 1, ncols: int = 1, axh: float = None, axw: float = None, h: float = None, w: float = None, left: float = None, right: float = None, wspace: float = None, width_ratios: Sequence[float] = None, bottom: float = None, top: float = None, hspace: float = None, height_ratios: Sequence[float] = None, **kwargs, ): """Specify :func:`matplotlib.pyplot.subplots` parameters in inches Parameters ---------- nrows Number of subplot rows. ncols Number of subplot columns. axh Height of each axes. axw Width of each axes. h Figure height. w Figure width. left Margin to the left of the axes. right Margin to the right of the axes. wspace Width of the margin between axes. width_ratios The relative widths of the columns (see :class:`matplotlib.gridspec.GridSpec`). bottom Margin below the axes. top Margin above the axes. hspace Height of the margin between axes. height_ratios The relative heights of the rows (see :class:`matplotlib.gridspec.GridSpec`). ** Other parameters for :func:`matplotlib.pyplot.subplots`. """ from matplotlib import pyplot margins = {'left': left, 'bottom': bottom, 'right': right, 'top': top, 'wspace': wspace, 'hspace': hspace} layout = Layout(nrows*ncols, 1, 2, False, None, h, w, axh, axw, nrows, ncols, None, margins) gridspec_kw = { 'left': layout.margins['left'] / layout.w, 'right': 1 - layout.margins['right'] / layout.w, 'wspace': layout.margins['wspace'] / layout.axw, 'width_ratios': width_ratios, 'bottom': layout.margins['bottom'] / layout.h, 'top': 1 - layout.margins['top'] / layout.h, 'hspace': layout.margins['hspace'] / layout.axh, 'height_ratios': height_ratios, } return pyplot.subplots(layout.nrow, layout.ncol, figsize=(layout.w, layout.h), gridspec_kw=gridspec_kw, **kwargs) class ColorBarMixin: """Colorbar toolbar button mixin Parameters ---------- param_func : func Function that returns color-bar parameters. """ def __init__( self, param_func: Callable = None, # function to get cmap, vmin, vmax data: Union[NDVar, Var, Number, str, 'PlotData'] = None, # to infer unit mappable: Any = None, # matplotlib mappable object ): self.__get_params = param_func self.__mappable = mappable if data is None: self.__scale = AxisScale(1) else: self.__scale = AxisScale(data) def _fill_toolbar(self, tb): from .._wxgui import wx, ID, Icon tb.AddTool(ID.PLOT_COLORBAR, "Plot Colorbar", Icon("plot/colorbar")) tb.Bind(wx.EVT_TOOL, self.__OnPlotColorBar, id=ID.PLOT_COLORBAR) def __OnPlotColorBar(self, event): return self.plot_colorbar() def plot_colorbar( self, label: Union[bool, str] = True, label_position: Literal['left', 'right', 'top', 'bottom'] = None, label_rotation: float = None, clipmin: float = None, clipmax: float = None, orientation: Literal['horizontal', 'vertical'] = 'horizontal', **kwargs, ): """Plot a colorbar corresponding to the displayed data Parameters ---------- label Label for the x-axis (default is based on the data). label_position Position of the axis label. Valid values depend on orientation. label_rotation Angle of the label in degrees (For horizontal colorbars, the default is 0; for vertical colorbars, the default is 0 for labels of 3 characters and shorter, and 90 for longer labels). clipmin Clip the color-bar below this value. clipmax Clip the color-bar above this value. orientation Orientation of the bar (default is horizontal). ... More parameters for :class:`plot.ColorBar`. Returns ------- colorbar : plot.ColorBar ColorBar plot object. """ # cf. matplorlib.colorbar.Colorbar transforming mappable to color-map from . import ColorBar if self.__mappable is not None: cmap = self.__mappable.cmap vmin = self.__mappable.norm vmax = None elif self.__get_params is not None: cmap, vmin, vmax = self.__get_params() else: raise RuntimeError(f"No colormap on {self}") return ColorBar(cmap, vmin, vmax, label, label_position, label_rotation, clipmin, clipmax, orientation, self.__scale, **kwargs) class ColorMapMixin(ColorBarMixin): """takes care of color-map and includes color-bar""" _can_set_vlim = True def __init__(self, epochs, cmap, vmax, vmin, contours, plots): ColorBarMixin.__init__(self, self.__get_cmap_params, epochs[0][0]) self.__plots = plots # can be empty list at __init__ self._cmaps = find_fig_cmaps(epochs, cmap) self._vlims = find_fig_vlims(epochs, vmax, vmin, self._cmaps) self._contours = find_fig_contours(epochs, self._vlims, contours) self._first_meas = epochs[0][0].info.get('meas') def __get_cmap_params(self): return (self._cmaps[self._first_meas],) + self._vlims[self._first_meas] def add_contour(self, level: float, color: Any = 'k', meas: str = None): """Add a contour line Parameters ---------- level : scalar The value at which to draw the contour. color : matplotlib color The color of the contour line. meas : str The measurement for which to add a contour line (default is the measurement plotted first). """ if meas is None: meas = self._first_meas for p in self.__plots: p.add_contour(meas, level, color) self.draw() def set_cmap(self, cmap, meas=None): """Change the colormap in the array plots Parameters ---------- cmap : str | colormap New colormap. meas : None | str Measurement to which to apply the colormap. With None, it is applied to all. """ if meas is None: meas = self._first_meas for p in self.__plots: p.set_cmap(cmap, meas) self._cmaps[meas] = cmap if isinstance(cmap, LocatedColormap): self.set_vlim(cmap.vmin, cmap.vmax, meas) else: self.draw() def set_vlim(self, v=None, vmax=None, meas=None): """Change the colormap limits If the limit is symmetric, use ``set_vlim(vlim)``; if it is not, use ``set_vlim(vmin, vmax)``. Parameters ---------- v : scalar If this is the only value specified it is interpreted as the upper end of the scale, and the lower end is determined based on the colormap to be ``-v`` or ``0``. If ``vmax`` is also specified, ``v`` specifies the lower end of the scale. vmax : scalar (optional) Upper end of the color scale. meas : str (optional) Measurement type to apply (default is the first one found). """ if meas is None: meas = self._first_meas elif meas not in self._cmaps: raise ValueError("meas=%r" % (meas,)) if vmax is None: vmin, vmax = fix_vlim_for_cmap(None, abs(v), self._cmaps[meas]) else: vmin = v for p in self.__plots: p.set_vlim(vmin, vmax, meas) self._vlims[meas] = vmin, vmax if self._can_set_ylim: self.set_ylim(vmin, vmax) else: self.draw() def get_vlim(self, meas=None): "Retrieve colormap value limits as ``(vmin, vmax)`` tuple" if meas is None: meas = self._first_meas return self._vlims[meas] class LegendMixin: __choices = ('invisible', 'separate window', 'draggable', 'upper right', 'upper left', 'lower left', 'lower right', 'right', 'center left', 'center right', 'lower center', 'upper center', 'center') __args = (False, 'fig', 'draggable', 1, 2, 3, 4, 5, 6, 7, 8, 9, 10) _has_frame = None def __init__( self, loc: LegendArg, handles: Dict[CellArg, Any], labels: Dict[CellArg, str] = None, ): """Legend toolbar menu mixin Parameters ---------- loc Matplotlib figure legend location argument or 'fig' to plot the legend in a separate figure. handles : dict {cell: handle} dictionary. labels : dict Dictionary with labels for cells. """ # whether to plot default legend if loc is not None: initial_loc = loc elif len(handles) > 1: initial_loc = 'upper right' else: initial_loc = False self.__handles = handles self.legend = None self.__labels = None self.__set_labels(labels) self.plot_legend(initial_loc) def __set_labels(self, labels: Dict[CellArg, str] = None): if labels is not None: self.__labels = {key: asfmtext(label) for key, label in labels.items()} def _fill_toolbar(self, tb): from .._wxgui import wx choices = [name.title() for name in self.__choices] self.__ctrl = wx.Choice(tb, choices=choices, name='Legend') tb.AddControl(self.__ctrl, "Legend") self.__ctrl.Bind(wx.EVT_CHOICE, self.__OnChoice, source=self.__ctrl) def __OnChoice(self, event): self.__plot(self.__args[event.GetSelection()]) def plot_legend( self, loc: LegendArg = 'fig', labels=None, **kwargs): """Plot the legend (or remove it from the figure). Parameters ---------- loc Where to plot the legend (see Notes; default 'fig'). labels : dict Dictionary with alternate labels for all cells. ... : Parameters for :class:`eelbrain.plot.Legend`. Returns ------- legend_figure : None | legend If loc=='fig' the Figure, otherwise None. Notes ----- legend content can be modified through the figure's ``legend_handles`` and ``legend_labels`` attributes. Possible values for the ``loc`` argument: ``False``: Make the current legend invisible ``'fig'``: Plot the legend in a new figure ``'draggable'``: The legend can be dragged to the desired position with the mouse pointer. str | int | (float, float): Matplotlib :meth:`~matplotlib.figure.Figure.legend` position argument. """ if loc in self.__choices: choice = self.__choices.index(loc) arg = self.__args[choice] elif loc is None: choice = 0 arg = False elif loc is True: choice = 3 arg = 'best' elif isinstance(loc, Sequence) and not isinstance(loc, str): choice = 0 arg = loc elif loc not in self.__args: raise ValueError(f"Invalid legend location: {loc!r}; use one of: {enumeration(map(repr, self.__choices), "or")}") else: choice = self.__args.index(loc) arg = loc if self._has_frame: self.__ctrl.SetSelection(choice) if arg is not False: return self.__plot(loc, labels, **kwargs) def save_legend(self, *args, **kwargs): """Save the legend as image file Parameters ---------- ... : Parameters for Matplotlib's figure.savefig() """ p = self.plot_legend(show=False) p.save(*args, **kwargs) p.close() def __plot(self, loc: LegendArg, labels: Dict[CellArg, str] = None, **kwargs): self.__set_labels(labels) if loc and self.__handles: if self.__labels is None: cells = list(self.__handles) labels = [cellname(cell) for cell in cells] elif isinstance(self.__labels, dict): cells = list(self.__labels.keys()) labels = list(self.__labels.values()) else: raise TypeError(f"{labels=}; needs to be dict") handles = [self.__handles[cell] for cell in cells] if loc == 'fig': return Legend(handles, labels, **kwargs) else: # take care of old legend if self.legend is not None and loc == 'draggable': self.legend.set_draggable(True) elif self.legend is not None: self.legend.remove() elif loc == 'draggable': self.legend = self.figure.legend(handles, labels, loc=1) self.legend.set_draggable(True) if loc != 'draggable': self.legend = self.figure.legend(handles, labels, loc=loc) self.draw() elif self.legend is not None: self.legend.remove() self.legend = None self.draw() elif not self.__handles: raise RuntimeError("No handles to produce legend.") class Legend(EelFigure): def __init__(self, handles, labels, **kwargs): layout = Layout(0, 1, 2, tight=False, **kwargs) EelFigure.__init__(self, None, layout) self.legend = self.figure.legend(handles, labels, loc=2) # resize figure to match legend if not self._layout.w_fixed and self._has_frame: self.draw() bb = self.legend.get_window_extent() w0, h0 = self._frame.GetSize() h = int(h0 + bb.x0 - bb.y0) w = int(bb.x0 + bb.x1) self._frame.SetSize((w, h)) self._show() class TimeController: # Link plots that have the TimeSlicer mixin def __init__( self, t: float = 0, fixate: bool = False, ): self._plots = [] # list of weakref to plots self.current_time = t self.fixate = fixate def add_plot(self, plot: 'TimeSlicer'): if plot._time_controller is None: t = plot._validate_time(self.current_time) plot._set_time(t, self.fixate) self._plots.append(weakref.ref(plot)) plot._time_controller = self elif plot._time_controller is not self: self.merge(plot._time_controller) def iter_plots(self): needs_cleaning = False for ref in self._plots: plot = ref() if plot is None: needs_cleaning = True else: yield plot if needs_cleaning: self._plots = [ref for ref in self._plots if ref() is not None] def merge(self, time_controller): "Merge another TimeController into self" for plot in time_controller.iter_plots(): plot._time_controller = None self.add_plot(plot) def set_time(self, t, fixate): if t == self.current_time and fixate == self.fixate: return for p in self.iter_plots(): t = p._validate_time(t) for p in self.iter_plots(): p._update_time_wrapper(t, fixate) self.current_time = t self.fixate = fixate def set_xlim(self, xmin, xmax): for p in self.iter_plots(): if isinstance(p, XAxisMixin): p._set_xlim(xmin, xmax, draw=True) class TimeSlicer: # Interface to link time axes of multiple plots. # update data in a child plot of time-slices _time_dim = None _current_time = None # needs to reflect what is currently displayed _initial_time = None # used by delayed initialization of time-controller _display_time_in_frame_title = False def __init__( self, time_dim: Union[UTS, Case] = None, time_fixed: bool = None, display_text: matplotlib.text.Text = None, initial_time: float = None, ): self._time_controller = None self._time_fixed = time_fixed if time_fixed is not None else (initial_time is not None) self.__display_text = display_text self._initial_time = initial_time if time_dim is not None: self._init_time_dim(time_dim) def _init_time_dim(self, time_dim: Union[UTS, Case]): if self._time_dim is not None: if time_dim == self._time_dim: return raise ValueError(f"An incompatible time dimension is already set on {self}\nold: {self._time_dim}\nnew: {time_dim}") self._time_dim = time_dim if isinstance(time_dim, UTS): if self._initial_time is None: self._initial_time = time_dim.tmin elif isinstance(time_dim, Case): if self._initial_time is None: self._initial_time = 0 else: raise TypeError(f'{time_dim=}') def _init_controller(self): # Only instantiated if more than one plots need to be linked tc = TimeController(self._initial_time, self._time_fixed) tc.add_plot(self) def link_time_axis(self, other): """Link the time axis of this figure with another figure""" if self._time_dim is None: raise NotImplementedError("Slice plot for dimension other than time") elif not isinstance(other, TimeSlicer): raise TypeError(f"{other.__class__.__name__} plot does not support linked time axes") elif other._time_dim is None: raise NotImplementedError("Slice plot for dimension other than time") elif other._time_controller: other._time_controller.add_plot(self) else: if not self._time_controller: self._init_controller() self._time_controller.add_plot(other) def _nudge_time(self, offset): if self._time_dim is None: return current_i = self._time_dim._array_index(self.get_time()) if offset > 0: new_i = min(self._time_dim.nsamples - 1, current_i + offset) else: new_i = max(0, current_i + offset) self._set_time(self._time_dim[new_i], True) def get_time(self): "Retrieve the current time" if self._current_time is None: return self._initial_time return self._current_time def play_movie(self, time_dilation=4.): """Cycle through the time axis See Also -------- .save_movie : Save a movie to disk for smoother playback """ t = self._time_dim[0] self.set_time(t) tmax = self._time_dim[-1] last_frame = time.time() time.sleep(0.05) while True: now = time.time() t += (now - last_frame) / time_dilation last_frame = now if t > tmax: break self.set_time(t) self.set_time(tmax) def set_time(self, time): """Set the time point to display Parameters ---------- time : scalar Time to display. """ self._set_time(time, True) def _set_time(self, t, fixate=False): "Called by the plot" if self._time_controller is None: self._update_time_wrapper(t, fixate) else: self._time_controller.set_time(t, fixate) def _update_time_wrapper(self, t, fixate): "Called by the TimeController" if t == self._current_time and fixate == self._time_fixed: return self._update_time(t, fixate) self._current_time = t self._time_fixed = fixate if self._display_time_in_frame_title and self._frame: self._frame.SetTitleSuffix(f' [{ms(t)} ms]') if self.__display_text is not None: self.__display_text.set_text(f'{ms(t)} ms') def _update_time(self, t, fixate): raise NotImplementedError def _validate_time(self, t): if self._time_dim is not None: if t < self._time_dim.tmin: return self._time_dim.tmin elif t > self._time_dim.tmax: return self._time_dim.tmax return t def _im_array(self): # for movies raise NotImplementedError class TimeSlicerEF(TimeSlicer): # TimeSlicer for Eelfigure _can_set_time = True def __init__( self, x_dimname: str, x_dim: Dimension, axes: Sequence[matplotlib.axes.Axes] = None, redraw: bool = True, display_text: matplotlib.text.Text = None, initial_time: float = None, ): if x_dimname != 'time': TimeSlicer.__init__(self, time_fixed=True, display_text=display_text) return TimeSlicer.__init__(self, x_dim, display_text=display_text, initial_time=initial_time) self.__axes = self.axes if axes is None else axes self.__time_lines = [] self.__redraw = redraw self.canvas.mpl_connect('button_press_event', self._on_click) self._register_key('.', self._on_nudge_time) self._register_key(',', self._on_nudge_time) def _on_click(self, event): if self._time_controller and event.inaxes in self.__axes: self._set_time(event.xdata, fixate=event.button == 1) def _on_motion_sub(self, event): if not self._time_fixed and event.inaxes in self.__axes: self._set_time(event.xdata) return set() def _on_nudge_time(self, event): self._nudge_time(1 if event.key == '.' else -1) def _update_time(self, t, fixate): # Implementation for a plot with time axes if fixate: redraw = True if self.__time_lines: xdata = (t, t) for line in self.__time_lines: line.set_xdata(xdata) else: for ax in self.__axes: self.__time_lines.append(ax.axvline(t, color='k')) else: redraw = bool(self.__time_lines) while self.__time_lines: self.__time_lines.pop().remove() if self.__redraw and redraw and self._frame is not None: self.canvas.redraw(self.__axes) def save_movie(self, filename=None, time_dilation=4., **kwargs): """Save the figure with moving time axis as movie Parameters ---------- filename : path-like Filename for the movie (omit to use a GUI). time_dilation : float Factor by which to stretch time (default 4). Time dilation is controlled through the frame-rate; if the ``fps`` keyword argument is specified, ``time_dilation`` is ignored. ... :func:`imageio.mimwrite` parmeters. """ import imageio if filename is None: filename = ui.ask_saveas("Save movie...", None, [('Movie (*.mov)', '*.mov')]) if not filename: return else: filename = os.path.expanduser(filename) if 'fps' not in kwargs: kwargs['fps'] = 1. / self._time_dim.tstep / time_dilation ims = [] for t in self._time_dim: self._set_time(t, True) im = self._im_array() ims.append(im) imageio.mimwrite(filename, ims, **kwargs) def _im_array(self): # private attr usage is official: https://matplotlib.org/gallery/misc/agg_buffer_to_array.html return np.array(self.figure.canvas.renderer._renderer) class TopoMapKey: def __init__(self, data_func): self.__topo_data = data_func self._register_key('t', self.__on_topo) self._register_key('T', self.__on_topo) def __on_topo(self, event): topo_data = self.__topo_data(event) if topo_data is None: return from ._topo import Topomap data, title, proj = topo_data if event.key == 't': Topomap(data, proj=proj, cmap=self._cmaps, vmax=self._vlims, contours=self._contours, title=title) else: Topomap(data, proj=proj, cmap=self._cmaps, vmax=self._vlims, contours=self._contours, title=title, axw=9, sensorlabels='name') class CategorialAxisMixin: def __init__(self, ax, axis, layout, label, model, ticks, labels, tick_delim, tick_pos, cells, origin=None): self.__ax = ax self.__axis = axis self.__cells = cells if axis == 'x': self.__axis_obj = ax.xaxis if layout.frame is not True: ax.spines['bottom'].set_visible(False) if origin is not None: ax.axhline(origin, color='k', linewidth=mpl.rcParams['axes.linewidth'], clip_on=False) elif axis == 'y': self.__axis_obj = ax.yaxis if layout.frame is not True: ax.spines['left'].set_visible(False) if origin is not None: ax.axvline(origin, color='k', linewidth=mpl.rcParams['axes.linewidth'], clip_on=False) else: raise ValueError(f"axis={axis!r}") # axis label if label is True: if model is not None and model.name: label = model.name.replace('_', ' ') else: label = False if label: self.__axis_obj.set_label_text(label) # ticks self.__axis_obj.set_ticks_position('none') if ticks: if isinstance(ticks, dict) or ticks is True: labels_ = find_labels(cells, labels, tick_delim) if isinstance(ticks, dict): labels_.update(ticks) tick_labels = [labels_[cell] for cell in cells] else: tick_labels = ticks self.__axis_obj.set_ticks(tick_pos) self.__axis_obj.set_ticklabels(tick_labels) elif ticks is False: self.__axis_obj.set_ticks(()) if axis == 'x' and self._has_frame and not self._layout.w_fixed: self._draw_hooks.append(self.__separate_categorial_labels) def __separate_categorial_labels(self): # make sure x axis labels don't overlap labels = self.__axis_obj.get_ticklabels() n = len(labels) if n > 1: bbs = [l.get_window_extent(self.figure.canvas.renderer) for l in labels] overlap = max(bbs[i].x1 - bbs[i + 1].x0 for i in range(n - 1)) extend = n * (overlap + 10) w, h = self._frame.GetSize() w += int(extend) self._frame.SetSize((w, h)) return True def mark_pair( self, cell_1: Union[float, CellArg], cell_2: Union[float, CellArg], y: float, dy: float = None, mark: Union[float, str] = None, color: Any = None, nudge: Union[bool, float] = None, **text_args, ): """Mark a pair of categories with a line and a label Parameters ---------- cell_1 Data-cell to be compared (can be specified as cell or as x-coordinate) cell_2 Second cell to be compared. y Level above which to plot the bar. dy Length of vertical ticks on each side of the bar (offsets the location of the bar itself to ``y + dy``; use negative values to flip orientation). mark Text label, or p-value to automatically determine the label and ``color``. color Color for bar and ``label``. nudge Nudge the edges of the bar inwards to allow multiple bars side-by-side on the same level of ``y``. ... All other parameters are used to plot the text label with :meth:`matplotlib.axes.Axes.text`. """ if isinstance(cell_1, (str, tuple)): x1 = self.__cells.index(cell_1) else: x1 = cell_1 if isinstance(cell_2, (str, tuple)): x2 = self.__cells.index(cell_2) else: x2 = cell_2 location = {'x': 'top', 'y': 'right'}[self.__axis] mark_difference(x1, x2, y, mark, dy, color, nudge, location, self.__ax, **text_args) class XAxisMixin: """Manage x-axis Parameters ---------- xmin : scalar Lower bound of the x axis. xmin : scalar Upper bound of the x axis. axes : list of Axes Axes that should be managed by the mixin. xlim : scalar | (scalar, scalar) Initial x-axis view limits as ``(left, right)`` tuple or as ``length`` scalar (default is the full x-axis in the data). Notes ----- Navigation: - ``←``: scroll left - ``→``: scroll right - ``home``: scroll to beginning - ``end``: scroll to end - ``f``: x-axis zoom in (reduce x axis range) - ``d``: x-axis zoom out (increase x axis range) """ _can_set_xlim = True def __init__(self, xmin, xmax, xlim=None, axes=None): self.__xmin = xmin self.__xmax = xmax self.__axes = axes or self.axes self.__vspans = [] self._register_key('f', self.__on_zoom_plus) self._register_key('d', self.__on_zoom_minus) self._register_key('j' if IS_WINDOWS else 'left', self.__on_left) self._register_key('l' if IS_WINDOWS else 'right', self.__on_right) self._register_key('home', self.__on_beginning) self._register_key('end', self.__on_end) if xlim is None: xlim = (self.__xmin, self.__xmax) elif np.isscalar(xlim): xlim = (self.__xmin, self.__xmin + xlim) self._set_xlim(*xlim) def _init_with_data( self, epochs: Sequence[Sequence[NDVar]], xdim: str, xlim: Union[float, Tuple[float, float]] = None, axes: List[matplotlib.axes.Axes] = None, im: bool = False, ): """Compute axis bounds from data Parameters ---------- epochs The data that is plotted (to determine axis range). xdim Dimension that is plotted on the x-axis. axes Axes that should be managed by the mixin. xlim Initial x-axis view limits as ``(left, right)`` tuple or as ``length`` scalar (default is the full x-axis in the data). im Plot displays an im, i.e. the axes limits need to extend beyond the dimension endpoints by half a step (default False). """ dims = (e.get_dim(xdim) for e in chain(*epochs)) if im: dim_extent = [dim._axis_im_extent() for dim in dims] else: dim_extent = [dim._axis_extent() for dim in dims] xmin = min(e[0] for e in dim_extent) xmax = max(e[1] for e in dim_extent) XAxisMixin.__init__(self, xmin, xmax, xlim, axes) def get_xlim(self): return self.__axes[0].get_xlim() def __animate(self, vmin, vmin_dst, vmax, vmax_dst): n_steps = int(0.1 // self._last_draw_time) if n_steps > 1: vmin_d = vmin_dst - vmin vmax_d = vmax_dst - vmax for i in range(1, n_steps): x = i / n_steps self.set_xlim(vmin + x * vmin_d, vmax + x * vmax_d) self.set_xlim(vmin_dst, vmax_dst) def __on_beginning(self, event): left, right = self.get_xlim() d = right - left self.set_xlim(self.__xmin, min(self.__xmax, self.__xmin + d)) def __on_end(self, event): left, right = self.get_xlim() d = right - left self.set_xlim(max(self.__xmin, self.__xmax - d), self.__xmax) def __on_zoom_plus(self, event): left, right = self.get_xlim() d = (right - left) / 4. self.__animate(left, left + d, right, right - d) def __on_zoom_minus(self, event): left, right = self.get_xlim() d = right - left new_left = max(self.__xmin, left - (d / 2.)) new_right = min(self.__xmax, new_left + 2 * d) self.__animate(left, new_left, right, new_right) def __on_left(self, event): left, right = self.get_xlim() d = right - left new_left = max(self.__xmin, left - d) self.__animate(left, new_left, right, new_left + d) def __on_right(self, event): left, right = self.get_xlim() d = right - left new_right = min(self.__xmax, right + d) self.__animate(left, new_right - d, right, new_right) def _set_xlim(self, left, right, draw=False): for ax in self.__axes: ax.set_xlim(left, right) if draw: self.draw() def add_vspans(self, intervals, axes=None, *args, **kwargs): """Draw vertical bars over axes Parameters ---------- intervals : sequence of (start, stop) tuples Start and stop positions on the x-axis. axes : int | list of int Which axes to mark (default is all axes). additonal arguments : Additional arguments for :func:`matplotlib.axvspan`. """ if axes is None: axes = self.__axes elif isinstance(axes, int): axes = (self.__axes[axes],) else: axes = [self.__axes[i] for i in axes] for ax in axes: for xmin, xmax in intervals: self.__vspans.append(ax.axvspan(xmin, xmax, *args, **kwargs)) self.draw() def set_xlim(self, left=None, right=None): """Set the x-axis limits for all axes""" if isinstance(self, TimeSlicer) and self._time_controller is not None: if left is None or right is None: ax_left, ax_right = self.__axes[0].get_xlim() if left is None: left = ax_left if right is None: right = ax_right self._time_controller.set_xlim(left, right) else: self._set_xlim(left, right, draw=True) class YLimMixin: """Manage y-axis Parameters ---------- plots : Sequence Plots to manage. Plots must have ``.ax`` attribute. Notes ----- Navigation: - ``↑``: scroll up - ``↓``: scroll down - ``r``: y-axis zoom in (reduce y-axis range) - ``c``: y-axis zoom out (increase y-axis range) """ # Keep Y-lim and V-lim separate. For EEG, one might want to invert the # y-axis without inverting the colormap # What should be the organizing principle for different vlims within # one figure? Use cases: # - 2 axes with different data # - (not implemented) one axis with two y-axes _can_set_ylim = True def __init__(self, plots): self.__plots = plots self._register_key('r', self.__on_zoom_in) self._register_key('c', self.__on_zoom_out) self._register_key('i' if IS_WINDOWS else 'up', self.__on_move_up) self._register_key('k' if IS_WINDOWS else 'down', self.__on_move_down) self._draw_hooks.append(self.__draw_hook) # disable because it changes y-limits # self._untight_draw_hooks.append(self.__untight_draw_hook) def __draw_hook(self): need_draw = False for p in self.__plots: # decimate overlapping ticklabels locs = p.ax.yaxis.get_ticklocs() we = tuple(l.get_window_extent(self.canvas.renderer) for l in p.ax.yaxis.get_ticklabels()) start = 0 step = 1 locs_list = list(locs) if 0 in locs else None while any(e1.ymin < e0.ymax for e0, e1 in intervals(we[start::step])): step += 1 if locs_list: start = locs_list.index(0) % step if step > 1: p.ax.yaxis.set_ticks(locs[start::step]) need_draw = True return need_draw def __untight_draw_hook(self): for p in self.__plots: # remove the top-most y tick-label if it is outside the figure extent = p.ax.yaxis.get_ticklabels()[-1].get_window_extent() if extent.height and extent.y1 > self.figure.get_window_extent().y1: p.ax.set_yticks(p.ax.get_yticks()[:-1]) def get_ylim(self): vmin = min(p.vmin for p in self.__plots) vmax = max(p.vmax for p in self.__plots) return vmin, vmax def set_ylim(self, bottom=None, top=None): """Set the y-axis limits Parameters ---------- bottom : scalar Lower y-axis limit. top : scalar Upper y-axis limit. """ if bottom is None and top is None: return for p in self.__plots: p.set_ylim(bottom, top) self.draw() def __animate(self, vmin, vmin_d, vmax, vmax_d): n_steps = int(0.1 // self._last_draw_time) if n_steps <= 1: self.set_ylim(vmin + vmin_d, vmax + vmax_d) else: for i in range(1, n_steps + 1): x = i / n_steps self.set_ylim(vmin + x * vmin_d, vmax + x * vmax_d) def __on_move_down(self, event): vmin, vmax = self.get_ylim() d = (vmax - vmin) * 0.1 self.__animate(vmin, -d, vmax, -d) def __on_move_up(self, event): vmin, vmax = self.get_ylim() d = (vmax - vmin) * 0.1 self.__animate(vmin, d, vmax, d) def __on_zoom_in(self, event): vmin, vmax = self.get_ylim() d = (vmax - vmin) * 0.05 self.__animate(vmin, d, vmax, -d) def __on_zoom_out(self, event): vmin, vmax = self.get_ylim() d = (vmax - vmin) * (1 / 22) self.__animate(vmin, -d, vmax, d)
# Author: Christian Brodbeck <christianbrodbeck@nyu.edu> """Framework for figures embedded in a GUI Implementation ============== Plotting is implemented hierarchically in 3 different types of functions/classes: top-level (public names) Top-level functions or classes have public names create an entire figure. Some classes also retain the figure and provide methods for manipulating it. _ax_ Functions beginning with _ax_ organize an axes object. They do not create their own axes object (this is provided by the top-level function), but change axes formatting such as labels and extent. _plt_ Functions beginning with _plt_ only plot data to a given axes object without explicitly changing aspects of the axes themselves. Top-level plotters can be called with nested lists of data-objects (NDVar instances). They create a separate axes for each list element. Axes themselves can have multiple layers (e.g., a difference map visualized through a colormap, and significance levels indicated by contours). Example: t-test --------------- For example, the default plot for testnd.ttest() results is the following list (assuming the test compares A and B): ``[A, B, [diff(A,B), p(A, B)]]`` where ``diff(...)`` is a difference map and ``p(...)`` is a map of p-values. The main plot function creates a separate axes object for each list element: - ``A`` - ``B`` - ``[diff(A,B), p(A, B)]`` Each of these element is then plotted with the corresponding _ax_ function. The _ax_ function calls _plt_ for each of its input elements. Thus, the functions executed are: #. plot([A, B, [diff(A,B), p(A, B)]]) #. ---> _ax_(A) #. ------> _plt_(A) #. ---> _ax_(B) #. ------> _plt_(B) #. ---> _ax_([diff(A,B), p(A, B)]) #. ------> _plt_(diff(A,B)) #. ------> _plt_(p(A, B)) Vision ------ Modularize organization Data organizers: Take data from input arguments and organize it into axes and layers Style mappers: Take data and input arguments and determine matplotlib parameters Figure components Manage styling and interaction for figure properties (XAxisMixin, TimeController, ...) """ from __future__ import annotations import __main__ from collections.abc import Iterable from collections import defaultdict from copy import copy from dataclasses import dataclass, replace from enum import Enum, auto from functools import cached_property, reduce from itertools import chain, cycle, repeat from logging import getLogger import math from numbers import Number import os import re import time from typing import Any, Callable, Dict, Iterator, List, Literal, Optional, Sequence, Tuple, Union import weakref import matplotlib as mpl import matplotlib.axes import matplotlib.font_manager import matplotlib.patches import matplotlib.text from matplotlib.colors import Colormap from matplotlib.figure import SubplotParams from matplotlib.ticker import FuncFormatter import numpy as np from .._celltable import Celltable from .._colorspaces import LocatedColormap, symmetric_cmaps, zerobased_cmaps, ALPHA_CMAPS from .._config import CONFIG from .._data_obj import Dimension, Dataset, Factor, Interaction, NDVar, Var, Case, UTS, NDVarArg, CategorialArg, IndexArg, CellArg, NDVarTypes, ascategorial, asndvar, assub, isnumeric, isdataobject, combine_cells, cellname from .._utils.notebooks import use_inline_backend from .._stats import testnd from .._utils import IS_WINDOWS, intervals, ui from .._ndvar import erode, resample from .._text import enumeration, ms from ..fmtxt import FMTextArg, Image, asfmtext, asfmtext_or_none from ..table import melt_ndvar from ._decorations import mark_difference from ._styles import Style, find_cell_styles from ._utils import adjust_hsv # constants POINT = 0.013888888888898 # defaults defaults = {'maxw': 16, 'maxh': 10} # Types CMapArg = Any ColorArg = Any LegendArg = Optional[Union[str, int, Tuple[float, float], bool]] class PlotType(Enum): GENERAL = auto() LEGACY = auto() LINE = auto() IMAGE = auto() CONTOUR = auto() def do_autorun(run=None): # http://stackoverflow.com/a/2356420/166700 if run is not None: return run elif CONFIG['autorun'] is None: return not hasattr(__main__, '__file__') else: return CONFIG['autorun'] def mpl_font_size(key: str) -> float: "Font size in inches" p = matplotlib.font_manager.FontProperties(size=mpl.rcParams[key]) return p.get_size() * POINT def inch_to_figure(figure: matplotlib.figure.Figure, x: float = 0, y: float = 0): "Transform (x, y) vector in inches to figure coordinates" coords = figure.dpi_scale_trans.transform((x, y)) return figure.transFigure.inverted().transform(coords) DISPLAY_UNIT = { 's': 'ms', 'V': 'µV', 'T': 'fT', 'sensor': int, } UNIT_FORMAT = { 'A': 1, 'Am': 1, 'V': 1, 'ms': 1e3, 'mV': 1e3, 'µV': 1e6, 'pT': 1e12, 'fT': 1e15, 'dSPM': 1, 'p': 1, 'T': 1, 'n': int, # %i format 'normalized': 1, int: int, } SCALE_FORMATTERS = { 1: None, 1e3: FuncFormatter(lambda x, pos: '%g' % (1e3 * x)), 1e6: FuncFormatter(lambda x, pos: '%g' % (1e6 * x)), 1e9: FuncFormatter(lambda x, pos: '%g' % (1e9 * x)), 1e12: FuncFormatter(lambda x, pos: '%g' % (1e12 * x)), 1e15: FuncFormatter(lambda x, pos: '%g' % (1e15 * x)), int: FuncFormatter(lambda x, pos: '%i' % round(x)), } DEFAULT_CMAPS = { 'B': 'xpolar', 'V': 'xpolar', 'p': 'sig', 'f': 'viridis', 'r': 'xpolar', 't': 'xpolar', } INITIAL_RC = mpl.rcParams.copy() del INITIAL_RC['backend'] def reset_rc(): "Reset matplotlib rc-parameters to state at Eelbrain initialization" mpl.rcParams.update(INITIAL_RC) class AxisScale: """Find matching number formatter and label for display unit (!= data unit) Parameters ---------- v Display unit or scale of the axis, or daat to infer these. See ``unit_format`` dict above for options. label If ``label is True``, try to infer a label from ``v``. """ def __init__( self, v: Union[NDVar, Var, Number, str, 'PlotData'], label: Union[bool, str, Sequence[str]] = True, ): if isinstance(v, str): data_unit = None meas = None unit = v scale = UNIT_FORMAT.get(v, 1) elif isinstance(v, Number): data_unit = None meas = None unit = None scale = v else: if isnumeric(v): meas = v.info.get('meas') data_unit = v.info.get('unit') elif isinstance(v, PlotData): meas = v.meas data_unit = v.unit else: raise TypeError(f"unit={v!r}") if data_unit in DISPLAY_UNIT: unit = DISPLAY_UNIT[data_unit] scale = UNIT_FORMAT[unit] if data_unit in UNIT_FORMAT: scale /= UNIT_FORMAT[data_unit] else: scale = 1 unit = data_unit self.data_unit = data_unit # None | str self.display_unit = unit # ScalarFormatter: disabled because it always used e notation in status bar # (needs separate instance because it adapts to data) # fmt = ScalarFormatter() if scale == 1 else scale_formatters[scale] self.formatter = SCALE_FORMATTERS[scale] # Matplotlib tick formatter if label is True: if meas and unit and meas not in unit: label = f'{meas} [{unit}]' elif unit: label = unit elif meas: label = meas elif isinstance(v, PlotData): label = v.default_y_label elif isnumeric(v): label = v.name else: label = None self.label = label def find_uts_hlines(ndvar): """Find horizontal lines for uts plots (based on contours) Parameters ---------- ndvar : NDVar Data to be plotted. Returns ------- h_lines : iterator Iterator over (y, kwa) tuples. """ contours = ndvar.info.get('contours', None) if contours: for level in sorted(contours): args = contours[level] if isinstance(args, dict): yield level, args.copy() else: yield level, {'color': args} def find_uts_ax_vlim( layers: Sequence[NDVar], vlims: Dict = (), ) -> (Optional[float], Optional[float]): """Find y axis limits for uts axes Parameters ---------- layers Data to be plotted. vlims Vmax and vmin values by (meas, cmap). Returns ------- bottom Lowest value on y axis. top Highest value on y axis. """ bottom = None top = None for ndvar in layers: meas = ndvar.info.get('meas') if meas in vlims: bottom_, top_ = vlims[meas] if bottom is None: bottom = bottom_ elif bottom_ != bottom: bottom = min(bottom, bottom_) if top is None: top = top_ elif top_ != top: top = max(top, top_) return bottom, top def find_fig_cmaps( epochs: Sequence[Sequence[NDVar]], cmap: Union[dict, CMapArg] = None, alpha: bool = False, ) -> Dict[str, CMapArg]: """Find cmap for every meas Parameters ---------- epochs All NDVars in the plot. cmap Use this instead of the default for the first ``meas`` (for user argument). alpha If possible, use cmaps with alpha. Returns ------- cmaps {meas: cmap} dict for all meas. """ if isinstance(cmap, dict): out = cmap.copy() cmap = None else: out = {} for ndvar in chain(*epochs): meas = ndvar.info.get('meas') if meas in out and out[meas]: pass elif cmap is not None: out[meas] = cmap cmap = None elif 'cmap' in ndvar.info: out[meas] = ndvar.info['cmap'] else: out[meas] = None for k in out.keys(): if out[k] is None: out[k] = DEFAULT_CMAPS.get(meas, 'xpolar') # replace with cmap with alpha if alpha and out[k] in ALPHA_CMAPS: out[k] = ALPHA_CMAPS[out[k]] return out def find_fig_contours(epochs, vlims, contours_arg): """Find contour arguments for every meas type Parameters ---------- epochs : list of list of NDVar Data to be plotted. vlims : dist Vlims dict (used to interpret numerical arguments) contours_arg : int | sequence | dict User argument. Can be an int (number of contours), a sequence (values at which to draw contours), a kwargs dict (must contain the "levels" key), or a {meas: kwargs} dictionary. Returns ------- contours : dict {meas: kwargs} mapping for contour plots. Notes ----- The NDVar's info dict contains default arguments that determine how the NDVar is plotted as base and as overlay. In case of insufficient information, defaults apply. On the other hand, defaults can be overridden by providing specific arguments to plotting functions. """ if isinstance(contours_arg, dict) and 'levels' not in contours_arg: out = contours_arg.copy() contours_arg = None else: out = {} for ndvars in epochs: for layer, ndvar in enumerate(ndvars): meas = ndvar.info.get('meas') if meas in out: continue if contours_arg is not None: param = contours_arg contours_arg = None else: if layer: # overlay kind = ndvar.info.get('overlay', ('contours',)) else: kind = ndvar.info.get('base', ()) if 'contours' in kind: param = ndvar.info.get('contours', None) if layer: param = ndvar.info.get('overlay_contours', param) else: param = ndvar.info.get('base_contours', param) if isinstance(param, dict) and 'levels' not in param: levels = sorted(param) colors = [param[v] for v in levels] param = {'levels': levels, 'colors': colors} else: param = None if param is None: out[meas] = None elif isinstance(param, dict): out[meas] = param elif isinstance(param, int): vmin, vmax = vlims[meas] out[meas] = {'levels': np.linspace(vmin, vmax, param), 'colors': 'k'} else: out[meas] = {'levels': tuple(param), 'colors': 'k'} return out def find_fig_vlims(plots, vmax=None, vmin=None, cmaps=None): """Find vmin and vmax parameters for every (meas, cmap) combination Parameters ---------- plots : nested list of NDVar Unpacked plot data. vmax : None | dict | scalar Dict: predetermined vlims (take precedence). Scalar: user-specified vmax parameter (used for for the first meas kind). vmin : None | scalar User-specified vmin parameter. If vmax is user-specified but vmin is None, -vmax is used. cmaps : dict If provided, vlims will be fixed to match symmetric or 0-based cmaps. Returns ------- vlims : dict Dictionary of im limits: {meas: (vmin, vmax)}. """ vlims = {} if isinstance(vmax, dict): vlims.update(vmax) ndvars = [v for v in chain.from_iterable(plots) if v.info.get('meas') not in vlims] else: ndvars = [*chain.from_iterable(plots)] if vmin is None and vmax is not None: if cmaps is None and any(v.min() < 0 for v in ndvars): vmin = -vmax else: vmin = 0 # apply user specified vlim if vmin is not None or vmax is not None: meas = ndvars[0].info.get('meas') if vmax is None: meas_ndvars = [v for v in ndvars if v.info.get('meas') == meas] for ndvar in meas_ndvars: _, vmax_ = find_vlim_args(ndvar) vmax = vmax_ if vmax is None else max(vmax, vmax_) vlims[meas] = (vmin, vmax) ndvars = [v for v in ndvars if v.info.get('meas') != meas] # for other meas, fill in data limits for ndvar in ndvars: meas = ndvar.info.get('meas') vmin, vmax = find_vlim_args(ndvar) if meas in vlims: vmin_, vmax_ = vlims[meas] vmin = vmin if vmin_ is None else min(vmin, vmin_) vmax = vmax if vmax_ is None else max(vmax, vmax_) if vmin == vmax: vmin -= 1 vmax += 1 vlims[meas] = (vmin, vmax) # fix vlims based on cmaps if cmaps is not None: for meas in vlims.keys(): vmin, vmax = vlims[meas] vlims[meas] = fix_vlim_for_cmap(vmin, vmax, cmaps[meas]) return vlims def find_vlim_args(ndvar, vmin=None, vmax=None): if vmax is None: vmax = ndvar.info.get('vmax', None) if vmin is None: vmin = ndvar.info.get('vmin', None) if vmax is None or vmin is None: xmax = np.nanmax(ndvar.x) if np.ma.isMaskedArray(xmax): xmax = xmax.data xmin = np.nanmin(ndvar.x) if np.ma.isMaskedArray(xmin): xmin = xmin.data abs_max = max(abs(xmax), abs(xmin)) or 1e-14 if np.isnan(abs_max): raise ValueError(f"Can't plot all NaN input") scale = math.floor(np.log10(abs_max)) if vmax is None: vmax = math.ceil(xmax * 10 ** -scale) * 10 ** scale if vmin is None: vmin = math.floor(xmin * 10 ** -scale) * 10 ** scale return vmin, vmax def fix_vlim_for_cmap(vmin, vmax, cmap): "Fix the vmin value to yield an appropriate range for the cmap" if isinstance(cmap, LocatedColormap): vmin, vmax = cmap.vmin, cmap.vmax is_symmetric = cmap.symmetric starts_at_zero = False else: if isinstance(cmap, Colormap): cmap = cmap.name is_symmetric = cmap in symmetric_cmaps starts_at_zero = cmap in zerobased_cmaps if is_symmetric: if vmax is None and vmin is None: pass elif vmin is None: vmax = abs(vmax) vmin = -vmax elif vmax is None: vmax = abs(vmin) vmin = -vmax else: vmax = max(abs(vmax), abs(vmin)) vmin = -vmax elif starts_at_zero: vmin = 0 return vmin, vmax def find_data_dims( ndvar: NDVar, dims: Union[int, Tuple[str, ...]], extra_dim: str = None, ) -> Tuple[Union[str, None], List[str]]: """Find dimensions in data. Raise a ValueError if the dimensions don't match, except when the ``case`` dimension is omitted in ``dims``. Parameters ---------- ndvar : NDVar NDVar instance to query. dims : int | tuple of str The requested dimensions. extra_dim : str Dimension that will be removed by other operation (e.g. ``xax``). Returns ------- agg : None | str Dimension to aggregate over. dims : list of str Dimension names with all instances of ``None`` replaced by a string. """ if isinstance(dims, int): if extra_dim: dims += 1 dimnames = list(ndvar.dimnames) if ndvar.ndim == dims: agg = None elif ndvar.ndim == dims + 1: for agg in dimnames: if agg != extra_dim: break dimnames.remove(agg) else: raise ValueError(f"y={ndvar} has wrong number of dimensions; {dims} or {dims + 1} required") else: required_dims = (extra_dim, *dims) if extra_dim else dims if ndvar.ndim == len(required_dims): agg = None dimnames = list(ndvar.get_dimnames(required_dims)) elif ndvar.ndim == len(required_dims) + 1: if any(d is None for d in required_dims): if ndvar.has_case and 'case' not in required_dims: agg = 'case' else: raise ValueError(f"y={ndvar} is ambiguous for required dimensions {required_dims}") else: agg = None dimnames = list(ndvar.get_dimnames((agg, *required_dims))) agg = dimnames.pop(0) else: raise ValueError(f"y={ndvar} has wrong dimensions; {required_dims} or one more required") if extra_dim: dimnames.remove(extra_dim) return agg, dimnames def find_labels( cells: Sequence[CellArg], labels_arg: Dict[CellArg: str] = None, delim: str = ' ', ) -> Dict[CellArg, str]: if not labels_arg: return {cell: cellname(cell, delim) for cell in cells} labels = {} for cell in cells: if cell in labels_arg: label = labels_arg[cell] elif isinstance(cell, str): label = cell elif isinstance(cell, tuple): label = cellname([labels_arg.get(item, item) for item in cell], delim) else: raise TypeError(f"{cell=}") labels[cell] = label return labels def brain_data( data: Union[NDVar, testnd.NDTest], ): # for GlassBrain and surfer brain if isinstance(data, testnd.NDDifferenceTest): return data.masked_difference() else: return asndvar(data) def butterfly_data( data: Union[NDVar, testnd.NDTest], hemi: str, resample_: int = None, colors: bool = False, return_vector_data: bool = False, ): """Data for plotting butterfly plot with brain Returns ------- hemis : list of str Hemispheres in the data. butterfly_daya : Data for Butterfly plot. brain_data : Data for brain plot. """ # find input type if isinstance(data, NDVar): y = data kind = 'ndvar' elif isinstance(data, testnd.NDDifferenceTest): y = data.masked_difference() kind = 'ndvar' else: raise TypeError(f"ndvar={data!r}") source = y.get_dim('source') # find samplingrate if resample_ is not None: raise NotImplementedError(f"resample_={resample_}") # find hemispheres to include if hemi is None: hemis = [] if source.lh_n: hemis.append('lh') if source.rh_n: hemis.append('rh') elif hemi in ('lh', 'rh'): hemis = [hemi] else: raise ValueError("hemi=%r" % (hemi,)) if kind == 'ndvar': if y.has_case: y = y.mean('case') if resample_: y = resample(y, resample_, window='hamming') if y.has_dim('space'): if return_vector_data: brain_data = y y = y.norm('space') else: y = y.norm('space') brain_data = y else: brain_data = y bfly_data = [y.sub(source=hemi, name=hemi.capitalize()) for hemi in hemis] elif kind == 'test': sig = data.p <= 0.05 y_magnitude = y.rms('time') # resample if resample_: y = resample(y, resample_, window='hamming') sig = resample(sig, resample_) > 0.5 brain_data = y.mask(~sig) # mask non_sig = erode(~sig, 'time') y_sig = y.mask(non_sig) y_ns = y.mask(sig) # line-styles from ._colors import Style if colors: lh_color = '#046AAD' rh_color = '#A60628' line_color_sig = {'lh': lh_color, 'rh': rh_color} line_color_ns = {'lh': adjust_hsv(lh_color, 0, -0.5, -0.), 'rh': adjust_hsv(rh_color, 0, -0.7, -0.)} else: color_sig = (0,) * 3 color_ns = (.7,) * 3 line_color_sig = {'lh': color_sig, 'rh': color_sig} line_color_ns = {'lh': color_ns, 'rh': color_ns} linestyle_ns = {'linewidth': 0.2, 'color': line_color_ns, 'alpha': 0.2} linestyle_sig = {'linewidth': 0.2, 'color': line_color_sig, 'alpha': 1.0} # layer-data axes = [] for hemi in hemis: # z-order y_mag = y_magnitude.sub(source=hemi) z_order = dict(zip(y_mag.source, -y_mag.x.argsort())) # data layers = [] for y, linestyle in ((y_ns, linestyle_ns), (y_sig, linestyle_sig)): kwargs = {'zorder': z_order, **linestyle} layers.append(DataLayer(y.sub(source=hemi), PlotType.LINE, kwargs)) axes.append(AxisData(layers)) bfly_data = PlotData(axes, ('time', 'source'), plot_names=hemis) else: raise RuntimeError(f"kind={kind}") return hemis, bfly_data, brain_data def pop_if_dict(kwargs, key): "Helper for artist-sepcific matplotlib kwargs" if key in kwargs and isinstance(kwargs[key], dict): return kwargs.pop(key) def set_dict_arg(key, arg, line_dim_obj, artists, legend_handles=None): "Helper for artist-sepcific matplotlib kwargs" set_attr_name = 'set_' + key for dim_index, value in arg.items(): index = line_dim_obj._array_index(dim_index) if isinstance(index, int): key_artists = [artists[index]] else: key_artists = artists[index] if not key_artists: continue for artist in key_artists: getattr(artist, set_attr_name)(value) if legend_handles is not None: for artist in key_artists: artist.set_label(dim_index) legend_handles[dim_index] = artist _remap_args = {'c': 'color'} def _dict_arg(arg: dict = None) -> dict: if arg is None: return {} elif any(k in arg for k in _remap_args): return {_remap_args.get(k, k): v for k, v in arg.items()} else: return arg @dataclass(eq=False) class Layer: y: NDVar plot_type: PlotType = PlotType.GENERAL def bin(self, bin_length, tstart, tstop): raise NotImplementedError def sub_time(self, time: float, data_only: bool = False): raise NotImplementedError def for_plot(self, plot_type: PlotType) -> Iterator['DataLayer']: raise NotImplementedError @dataclass(eq=False) class DataLayer(Layer): """Data for one subplot layer""" _plot_args: dict = None _plot_args_2: dict = None # alternate (contour plot of IMAGE layer) _bin_func: callable = np.mean def __post_init__(self): self._plot_args = _dict_arg(self._plot_args) if self.plot_type == PlotType.IMAGE: self._plot_args_2 = _dict_arg(self._plot_args_2) elif self._plot_args_2: raise TypeError(f"plot_args_2={self._plot_args_2!r} for {self.plot_type}") def plot_args(self, kwargs: dict) -> dict: # needs to be a copy? return {**_dict_arg(kwargs), **self._plot_args} def contour_plot_args(self, contours): out = {} # contours arg meas = self.y.info.get('meas') if meas in contours: if contours[meas] is not None: out.update(contours[meas]) # layer if self.plot_type == PlotType.IMAGE: out.update(self._plot_args_2) elif self.plot_type == PlotType.CONTOUR: out.update(self._plot_args) else: raise RuntimeError(f"layer of type {self.plot_type}") return out def im_plot_args(self, vlims: dict, cmaps: dict) -> dict: assert self.plot_type == PlotType.IMAGE meas = self.y.info.get('meas') if meas in cmaps: cmap = cmaps[meas] elif 'cmap' in self.y.info: cmap = self.y.info['cmap'] else: cmap = DEFAULT_CMAPS.get(meas, 'xpolar') if meas in vlims: vmin, vmax = vlims[meas] else: vmin, vmax = find_vlim_args(self.y) vmin, vmax = fix_vlim_for_cmap(vmin, vmax, cmap) return {'cmap': cmap, 'vmin': vmin, 'vmax': vmax, **self._plot_args} def for_plot(self, plot_type: PlotType) -> Iterator['DataLayer']: if self.plot_type == plot_type: yield self elif not np.ma.isMaskedArray(self.y.x): yield DataLayer(self.y, plot_type, self._plot_args) elif plot_type == PlotType.LEGACY: yield DataLayer(self.y.unmask(), plot_type, self._plot_args) elif self.plot_type != PlotType.GENERAL: raise RuntimeError(f"Invalid PlotData conversion: {self.plot_type} -> {plot_type}") elif plot_type == PlotType.LINE: un_mask = NDVar(~self.y.x.mask, self.y.dims) # kwargs = {} if self.y.has_dim('time'): un_mask = erode(un_mask, 'time') # if self.y.ndim == 2: # mag = self.y.rms('time') # z_dim = mag.dimnames[0] # kwargs['zorder'] = dict(zip(mag.get_dim(z_dim), -mag.x.argsort())) y_masked = self.y.unmask().mask(un_mask) args_main = {'alpha': 1., 'zorder': 1} args_masked = {'alpha': 0.4, 'color': (.7, .7, .7), 'zorder': 0} for y, args in ((self.y, args_main), (y_masked, args_masked)): yield DataLayer(y, plot_type, args) elif plot_type == PlotType.IMAGE: x = NDVar(self.y.x.data, self.y.dims, self.y.name, self.y.info) yield DataLayer(x, PlotType.IMAGE) x = NDVar(1. - self.y.x.mask, self.y.dims, self.y.name, {'meas': 'mask'}) yield DataLayer(x, PlotType.CONTOUR, {'levels': [0.5], 'colors': ['black']}, _bin_func=np.max) else: raise RuntimeError(f"plot_type={plot_type!r}") def sub_time(self, time: float, data_only: bool = False): y = self.y.sub(time=time) if data_only: return y else: return DataLayer(y, self.plot_type, self._plot_args, self._plot_args_2, self._bin_func) def bin(self, bin_length, tstart, tstop): y = self.y.bin(bin_length, tstart, tstop, self._bin_func) return replace(self, y=y) @dataclass(eq=False) class StatLayer(Layer): style: Style = None ct: Celltable = None cell: CellArg = None mask: NDVar = None # mask needs to be applied to stats mask_missing: bool = True def _apply_mask(self, y: np.ndarray) -> np.ndarray: if self.mask is None: return y if np.ma.isMaskedArray(y): y = y.data return NDVar(y, self.y.dims[1:]).mask(self.mask, missing=self.mask_missing).x def get_statistic(self, func: Callable = np.mean) -> np.ndarray: return self._apply_mask(self.ct._get_func(self.cell, func)) def get_dispersion(self, spec, pool) -> np.ndarray: return self._apply_mask(self.ct._get_dispersion(self.cell, spec, pool)) def for_plot(self, plot_type: PlotType) -> Iterator['DataLayer']: if self.plot_type == plot_type: yield self elif self.mask is None: yield replace(self, plot_type=plot_type) elif plot_type == PlotType.LINE: inverse_mask = ~self.mask if self.y.has_dim('time'): inverse_mask = erode(inverse_mask, 'time') yield replace(self, plot_type=plot_type, style=self.style.masked_style, mask=inverse_mask, mask_missing=False) yield replace(self, plot_type=plot_type) else: raise NotImplementedError @dataclass(eq=False) class AxisData: """Represent one axis (multiple layers)""" layers: List[Layer] title: str = None def __iter__(self): return iter(self.layers) @property def y0(self): for layer in self.layers: return layer.y raise IndexError("No data") def for_plot(self, plot_type: PlotType) -> 'AxisData': return replace(self, layers=[l for layer in self.layers for l in layer.for_plot(plot_type)]) def bin(self, bin_length, tstart, tstop): return replace(self, layers=[l.bin(bin_length, tstart, tstop) for l in self.layers]) def sub_time(self, time: float, data_only: bool = False): axis = [] for layer in self.layers: if time in layer.y.time: axis.append(layer.sub_time(time, data_only)) if data_only: return axis else: return replace(self, layers=axis) def x_arg(x: CategorialArg): if isinstance(x, str) and x.startswith('.'): return None, x else: return x, None def combine_x_args(x, xax): if x is None: return xax elif xax is None: return x elif not isinstance(xax, x.__class__): raise TypeError(f"x={x}, xax={xax}: x and xax must be of same type or None") elif isinstance(xax, str): return f"({x}) % ({xax})" else: return x % xax @dataclass(eq=False) class PlotData: """Organize nd-data for plotting Notes ----- Two-stage initialization: - Initially independent of plot type - Layers contain masked NDVars - Converted into specific plot-types with :meth:`.for_plot` methods. - Masks converted into layers Additional consideration for statistics-plots (UTSStat) - Need central tendency and dispersion - Dispersion is not derivable from layer data (within-subject SEM) - Ideally potential to be dynamic (switch between viewing all data and statistic) Implementation - DataLayer subclass that keeps reference to a CellTable? """ plot_data: List[AxisData] # Data for each axis dims: Sequence[str] # Dimensions assigned to the axes frame_title: str = "unnamed data" # Default window title plot_names: List[Union[str, None]] = None # Titles for the plots (all non-None axes) plot_used: List[bool] = None # List indicating which plot slots are used plot_type: PlotType = PlotType.GENERAL ct: Celltable = None x: Union[Factor, Interaction] = None xax: Union[Factor, Interaction] = None def __post_init__(self): self.n_plots = len(self.plot_data) if self.plot_used is None: self.plot_used = [True] * self.n_plots else: assert sum(self.plot_used) == self.n_plots if self.plot_names is None: self.plot_names = [] for layers in self.plot_data: for layer in layers: if layer.y.name: self.plot_names.append(layer.y.name) break else: self.plot_names.append(None) def __repr__(self): desc = [f'{self.n_plots} plots'] if not all(self.plot_used): desc.append(f'{len(self.plot_used) - self.n_plots} empty') desc.append(' x '.join(self.dims)) return f"<PlotData {self.frame_title!r}: {', '.join(desc)}>" def _cannot_skip_axes(self, parent): if not all(self.plot_used): raise NotImplementedError(f"y can not contain None for {parent.__class__.__name__} plot") def __iter__(self): return iter(self.plot_data) @classmethod def from_args( cls, y: Union[NDVarArg, Sequence[NDVarArg]], dims: Union[int, Tuple[Optional[str], ...]], xax: CategorialArg = None, ds: Dataset = None, sub: IndexArg = None, ): """Unpack the first argument to top-level NDVar plotting functions Parameters ---------- y the first argument. dims The dimensions needed for the plotting function. ``None`` to indicate arbitrary dimensions. xax A model to divide ``y`` into different axes. ``xax`` is currently applied on the first level, i.e., it assumes that ``y``'s first dimension is cases. ds Dataset containing data objects which are provided as :class:`str`. sub Index selecting a subset of cases. Notes ----- Ndvar plotting functions above 1-d UTS level should support the following API: - simple NDVar: summary ``plot(meg)`` - by dim: each case ``plot(meg, '.case')`` - NDVar and xax argument: summary for each ``plot(meg, subject) - nested list of layers (e.g., ttest results: [c1, c0, [c1-c0, p]]) """ if isinstance(y, cls): return y elif isinstance(y, AxisData): for layer in y.layers: dims = find_data_dims(layer.y, dims) return PlotData([y], dims) sub = assub(sub, ds) if hasattr(y, '_default_plot_obj'): ys = getattr(y, '_default_plot_obj')() else: ys = y if isinstance(ys, NDVarTypes): ys = (ys,) ax_names = None if xax is None: # y=[[y1], y2], xax=None axes = [] for ax in ys: if ax is None: axes.append(None) elif isinstance(ax, NDVarTypes): ax = asndvar(ax, sub, ds) agg, dims = find_data_dims(ax, dims) layer = aggregate(ax, agg) axes.append([layer]) else: layers = [] for layer in ax: layer = asndvar(layer, sub, ds) agg, dims = find_data_dims(layer, dims) layers.append(aggregate(layer, agg)) axes.append(layers) x_name = None # determine y names y_names = [] for layers in axes: if layers is None: continue for layer in layers: if layer.name and layer.name not in y_names: y_names.append(layer.name) elif all(ax is None or isinstance(ax, NDVarTypes) for ax in ys): ys = [asndvar(layer, sub, ds) for layer in ys] y_names = [layer.name for layer in ys] layers = [] if isinstance(xax, str) and xax.startswith('.'): # y=[y1, y2], xax='.dim' dimname, attr = re.match(r'\.(\w+)(?:\.(\w+))?$', xax).groups() xax_dim = indexes = dissolve_dim = None for layer in ys: dim = layer.get_dim(dimname) if xax_dim is None: xax_dim = dim if attr is None: indexes = dim dissolve_dim = dimname # dissolved by indexing # axis labels unit = f' {xax_dim._axis_unit}' if xax_dim._axis_unit else '' ax_names = [f'{v}{unit}' for v in xax_dim] else: f = getattr(dim, attr) if not isinstance(f, Factor): raise ValueError(f'xax={xax!r}') indexes = [f == cell for cell in f.cells] ax_names = f.cells elif dim != xax_dim: raise ValueError(f"y={y}, xax={xax!r}: dimension not equal on different y") agg, dims = find_data_dims(layer, dims, dissolve_dim) layers.append([aggregate(layer.sub(**{dimname: i}), agg) for i in indexes]) x_name = xax else: # y=[y1, y2], xax=categorial xax = ascategorial(xax, sub, ds) xax_indexes = [xax == cell for cell in xax.cells] for layer in ys: agg, dims = find_data_dims(layer, dims) layers.append([aggregate(layer.sub(index), agg) for index in xax_indexes]) x_name = xax.name ax_names = [cellname(cell) for cell in xax.cells] axes = list(zip(*layers)) else: raise TypeError(f"{y=}, {xax=}: y can't be nested list if xax is specified, use single list") if len(y_names) == 0: y_name = None elif len(y_names) == 1: y_name = y_names[0] else: y_name = ', '.join(y_names) use_axes = [ax is not None for ax in axes] axes = [AxisData([DataLayer(l) for l in ax]) for ax in axes if ax] title = frame_title(y_name, x_name) return cls(axes, dims, title, ax_names, use_axes) @classmethod def from_stats( cls, y: Union[NDVarArg, Sequence[NDVarArg]], x: CategorialArg = None, xax: CategorialArg = None, match: CategorialArg = None, sub: IndexArg = None, ds: Dataset = None, dims: Tuple[Union[str, None]] = None, colors: dict = None, mask: Union[NDVar, Dict[CellArg, NDVar]] = None, ): if isinstance(y, (tuple, list)): if xax is not None: raise TypeError(f"{y=}, {xax=}: xax cannot be specified with multiple y") axes_data = [cls.from_stats(yi, x, xax, match, sub, ds, dims, colors, mask) for yi in y] axes = list(chain.from_iterable(ax.plot_data for ax in axes_data)) return replace(axes_data[0], plot_data=axes, plot_used=None, plot_names=None) x, x_dim = x_arg(x) xax, xax_dim = x_arg(xax) if x_dim or xax_dim: if isinstance(y, NDVar): varname = Dataset.as_key(y.name) else: varname = y if x_dim: dim = x_dim[1:] ds = melt_ndvar(y, dim, ds=ds, varname=varname) y = varname x = combine_x_args(x, dim) if xax_dim: dim = xax_dim[1:] ds = melt_ndvar(y, dim, ds=ds, varname=varname) y = varname xax = combine_x_args(xax, dim) x_full = combine_x_args(x, xax) ct = Celltable(y, x_full, match, sub, ds=ds) # data dimensions agg, dims = find_data_dims(ct.y, dims, 'case') if agg: raise NotImplementedError # reconstruct x/xax if xax is None: ax_cells = [None] else: xax = ct._align(xax, ds=ds, coerce=ascategorial) ax_cells = xax.cells if x is not None: x = ct._align(x, ds=ds, coerce=ascategorial) title = frame_title(y, x, xax) # find styles styles = find_cell_styles(ct.cells, colors) # find masks if mask is None: masks = defaultdict(lambda: None) elif isinstance(mask, NDVar): masks = defaultdict(lambda: mask) elif isinstance(mask, dict): masks = defaultdict(lambda: None, **mask) else: raise TypeError(f"{mask=}") # assemble layers axes = [] for ax_cell in ax_cells: if x is None: cells = [ax_cell] elif ax_cell is None: cells = x.cells else: x_cells = x.cells cells = [combine_cells(x_cell, ax_cell) for x_cell in x_cells] cells = [cell for cell in cells if cell in ct.data] layers = [StatLayer(ct.data[cell], style=styles[cell], ct=ct, cell=cell, mask=masks[cell]) for cell in cells] axes.append(AxisData(layers, cellname(ax_cell))) return cls(axes, dims, title, ct=ct, x=x, xax=xax) @classmethod def empty(cls, plots: Union[int, List[bool]], dims: Sequence[str], title: str): """Empty PlotData object that can be filled by appending to layers Parameters ---------- plots : int | list of bool Number of plots, or list of booleans indicating for each plot whether its slot is used. dims : sequence of str Names of the dimensions. title : str Data description for the plot frame. """ if isinstance(plots, int): plots = [AxisData([]) for _ in range(plots)] else: plots = [AxisData([]) if p else None for p in plots] return cls(plots, dims, title) @property def y0(self): for ax in self.plot_data: for layer in ax: return layer.y raise IndexError("No data") @property def default_y_label(self): "Y-label in case meas and unit are uninformative" names = {l.y.name for ax in self.plot_data for l in ax} names.discard(None) if len(names) == 1: return names.pop() return None @property def meas(self): meass = {l.y.info.get('meas') for ax in self.plot_data for l in ax} meass.discard(None) if len(meass) == 1: return meass.pop() return None @property def unit(self): units = {l.y.info.get('unit') for ax in self.plot_data for l in ax} units.discard(None) if len(units) == 1: return units.pop() return None @cached_property def data(self): "For backwards compatibility with nested list of NDVar" data = self.for_plot(PlotType.LEGACY) return [[l.y for l in layers] for layers in data.plot_data] @cached_property def time_dim(self): "UTS dimension to expose for time slicer" time_dims = [l.y.get_dim('time') for ax in self.plot_data for l in ax.layers if l.y.has_dim('time')] if time_dims: return reduce(UTS._union, time_dims) def for_plot(self, plot_type: PlotType) -> 'PlotData': if self.plot_type == plot_type: return self plot_data = [ax.for_plot(plot_type) for ax in self.plot_data] return replace(self, plot_data=plot_data, plot_type=plot_type) def bin(self, bin_length, tstart, tstop): axes = [ax.bin(bin_length, tstart, tstop) for ax in self.plot_data] return PlotData(axes, self.dims, self.frame_title, self.plot_names, self.plot_used, self.plot_type) def sub_time(self, time: float, data_only: bool = False): axes = [ax.sub_time(time, data_only) for ax in self.plot_data] if data_only: return axes else: dims = [dim for dim in self.dims if dim != 'time'] return PlotData(axes, dims, self.frame_title, self.plot_names, self.plot_used, self.plot_type) def aggregate(y, agg): return y if agg is None else y.mean(agg) class FigureFrame: def __init__(self, figure): self.figure = figure self.canvas = self.figure.canvas self._background = None def Close(self): pass def SetStatusText(self, text): pass def Show(self): pass def redraw(self, axes=(), artists=()): "Adapted duplicate of mpl_canvas.FigureCanvasPanel" self.canvas.restore_region(self._background) for ax in axes: ax.draw_artist(ax) extent = ax.get_window_extent() self.canvas.blit(extent) for artist in artists: artist.axes.draw_artist(artist.axes) extent = artist.axes.get_window_extent() self.canvas.blit(extent) def store_canvas(self): self._background = self.canvas.copy_from_bbox(self.figure.bbox) class MatplotlibFrame(FigureFrame): "Cf. _wxgui.mpl_canvas" def __init__(self, **fig_kwargs): "Create self.figure and self.canvas attributes and return the figure" from matplotlib import pyplot figure = pyplot.figure(**fig_kwargs) FigureFrame.__init__(self, figure) self._plt = pyplot def Close(self): self._plt.close(self.figure) def Show(self): if mpl.get_backend() == 'WXAgg' and do_autorun(): self._plt.show() def frame_title(y, x=None, xax=None): """Generate frame title from common data structure Parameters ---------- y : data-obj | str Dependent variable. x : data-obj | str Predictor. xax : data-obj | str Grouping variable for axes. """ if isdataobject(y): y = y.name if isdataobject(x): x = x.name if isdataobject(xax): xax = xax.name if xax is None: if x is None: return "%s" % (y,) else: return "%s ~ %s" % (y, x) elif x is None: return "%s | %s" % (y, xax) else: return "%s ~ %s | %s" % (y, x, xax) class MatplotlibFigure: """Wrap a matplotlib figure for FMText""" def __init__(self, figure): self.figure = figure def _asfmtext( self, rasterize: bool = None, close_figures: bool = None, ): if rasterize is None: format = None elif rasterize: format = 'png' else: format = 'svg' return self.image(format=format, close=close_figures) def close(self): from matplotlib import pyplot pyplot.close(self.figure) def image(self, name: str = None, format: str = None, close: bool = None): """Create FMTXT Image from the figure Parameters ---------- name Name for the file (without extension; default is 'image'). format File format. For HTML, use ``svg`` for vector graphics and ``png`` for pixel graphics. The default is ``svg`` and can be changed with :func:`configure`). close Close the figure after writing to the ``image``. By default, this is ``True`` when in an inline context (Jupyter notebook), ``False`` otherwise). Returns ------- image : fmtxt.Image Image FMTXT object. """ if format is None: format = CONFIG['format'] image = Image(name, format) self.figure.savefig(image, format=format) if close or (close is None and use_inline_backend()): self.close() return image class EelFigure(MatplotlibFigure): """Parent class for Eelbrain figures. In order to subclass: - find desired figure properties and then use them to initialize the _EelFigure superclass; then use the :py:attr:`_EelFigure.figure` and :py:attr:`_EelFigure.canvas` attributes. - end the initialization by calling `_EelFigure._show()` - add the :py:meth:`_fill_toolbar` method """ _default_xlabel_ax = -1 _default_ylabel_ax = 0 _make_axes = True _can_set_time = False _can_set_vlim = False _can_set_ylim = False _can_set_xlim = False _has_frame = False def __init__(self, data_desc: Optional[str], layout: BaseLayout): """Parent class for Eelbrain figures. Parameters ---------- data_desc Data description for frame title. layout Layout that determines figure dimensions. """ name = self.__class__.__name__ desc = layout.name or data_desc self._title = f'{name}: {desc}' if desc else name # Use Eelbrain frame or pyplot if layout.user_axes: ax = layout.user_axes[0] frame = FigureFrame(ax.get_figure()) elif CONFIG['eelbrain'] and not use_inline_backend(): from .._wxgui import wx, get_app from .._wxgui.mpl_canvas import CanvasFrame get_app() pos = wx.DefaultPosition if layout.pos is None else layout.pos frame = CanvasFrame(title=self._title, eelfigure=self, pos=pos, **layout.fig_kwa()) self._has_frame = True else: frame = MatplotlibFrame(**layout.fig_kwa()) figure = frame.figure if layout.title: self._figtitle = figure.suptitle(layout.title) else: self._figtitle = None # make axes if self._make_axes: axes = layout.make_axes(figure) else: axes = [] # store attributes MatplotlibFigure.__init__(self, figure) self._frame = frame self.axes = axes self.canvas = frame.canvas self._layout = layout self._last_draw_time = 1. self.__callback_key_press = {} self.__callback_key_release = {} # containers for hooks self._draw_hooks = [] self._untight_draw_hooks = [] # options self._draw_crosshairs = False self._crosshair_lines = None self._crosshair_axes = None # add callbacks self.canvas.mpl_connect('motion_notify_event', self._on_motion) self.canvas.mpl_connect('axes_leave_event', self._on_leave_axes) self.canvas.mpl_connect('resize_event', self._on_resize) self.canvas.mpl_connect('key_press_event', self._on_key_press) self.canvas.mpl_connect('key_release_event', self._on_key_release) def __repr__(self): title = self._frame.GetTitle() if self._has_frame else self._title return f'<{title}>' def _ipython_display_(self): from IPython.display import display display(self.figure) def _set_axtitle( self, axtitle: Union[bool, str, Iterator[str]] = None, data: PlotData = None, axes: Union[List[matplotlib.axes.Axes], int] = None, names: Sequence[str] = None, **kwargs, ): """Set axes titles automatically Parameters ---------- axtitle Plot parameter. data Plotted data (if available). axes Axes for which to set title (default is self.axes). If an int, (n axes) the method does not set axes title but returns ``None`` or a tuple of titles. names Instead of using ``epochs`` name attributes, use these names. ... Matplotlib ``Axes.set_title()`` parameters. """ if axtitle is False or axtitle is None: return if axes is None: axes = self.axes naxes = axes if isinstance(axes, int) else len(axes) if axtitle is True and naxes == 1: return elif axtitle is True or isinstance(axtitle, str): if names is None: if data is None: raise RuntimeError(f"data=None and names=None with {axtitle=}") names = data.plot_names if axtitle is True: axtitle = names else: axtitle = [axtitle.format(name=n) if n else None for n in names] if isinstance(axes, int): return axtitle for title, ax in zip(axtitle, axes): if title is not None: ax.set_title(asfmtext(title), **kwargs) def _show(self, crosshair_axes=None): if self._layout.user_axes: return if self._layout.tight: self._tight() if crosshair_axes is None: self._crosshair_axes = self.axes else: self._crosshair_axes = crosshair_axes self.draw() # Allow hooks to modify figure after first draw need_redraw = any([func() for func in self._draw_hooks]) if not self._layout.tight: need_redraw = any([func() for func in self._untight_draw_hooks]) or need_redraw if need_redraw: self.draw() if CONFIG['show'] and self._layout.show: self._frame.Show() if self._has_frame and do_autorun(self._layout.run): from .._wxgui import run run() if self._has_frame and not self.canvas._background: self._frame.store_canvas() def _tight(self): "Default implementation based on matplotlib" try: self.figure.tight_layout() except ValueError as exception: getLogger('eelbrain').debug('tight-layout: %s', exception) if self._figtitle: trans = self.figure.transFigure.inverted() extent = self._figtitle.get_window_extent(self.figure.canvas.renderer) bbox = trans.transform(extent) t_bottom = bbox[0, 1] self.figure.subplots_adjust(top=1 - 2 * (1 - t_bottom)) def _on_key_press(self, event): if event.key in self.__callback_key_press: self.__callback_key_press[event.key](event) event.guiEvent.Skip(False) # Matplotlib Skip()s all events def _on_key_release(self, event): if event.key in self.__callback_key_release: self.__callback_key_release[event.key](event) event.guiEvent.Skip(False) def _on_leave_axes(self, event): "Update the status bar when the cursor leaves axes" if self._frame is None: return self._frame.SetStatusText(self._on_leave_axes_status_text(event)) if self._draw_crosshairs: self._remove_crosshairs(True) def _on_leave_axes_status_text(self, event): return '☺︎' def _on_motion(self, event): "Update the status bar for mouse movement" if self._frame is None: return redraw_axes = self._on_motion_sub(event) ax = event.inaxes # draw crosshairs if self._draw_crosshairs and ax in self._crosshair_axes: if self._crosshair_lines is None: self._crosshair_lines = tuple( (ax.axhline(event.ydata, color='k'), ax.axvline(event.xdata, color='k')) for ax in self._crosshair_axes) else: for hline, vline in self._crosshair_lines: hline.set_ydata([event.ydata, event.ydata]) vline.set_xdata([event.xdata, event.xdata]) redraw_axes.update(self._crosshair_axes) # update status bar self._frame.SetStatusText(self._on_motion_status_text(event)) # redraw self.canvas.redraw(redraw_axes) @staticmethod def _on_motion_status_text(event): ax = event.inaxes if ax: return ('x = %s, y = %s' % ( ax.xaxis.get_major_formatter().format_data_short(event.xdata), ax.yaxis.get_major_formatter().format_data_short(event.ydata))) return '' def _on_motion_sub(self, event): "Subclass action on mouse motion, return set of axes to redraw" return set() def _on_resize(self, event): if self._layout.tight: self._tight() def _register_key(self, key, press=None, release=None): if press: if key in self.__callback_key_press: raise RuntimeError("Attempting to assign key press %r twice" % key) self.__callback_key_press[key] = press if release: if key in self.__callback_key_release: raise RuntimeError("Attempting to assign key release %r twice" % key) self.__callback_key_release[key] = release def _remove_crosshairs(self, draw=False): if self._crosshair_lines is not None: for hline, vline in self._crosshair_lines: hline.remove() vline.remove() self._crosshair_lines = None if draw: self.canvas.redraw(self._crosshair_axes) def _fill_toolbar(self, tb): """ Add toolbar tools Subclasses should add their toolbar items in this function which is called by ``CanvasFrame.FillToolBar()``. """ pass def close(self): "Close the figure." self._frame.Close() def _get_axes(self, axes): "Iterate over axes corresponding to ``axes`` parameter" if axes is None: return self.axes elif isinstance(axes, int): return self.axes[axes], else: return (self.axes[i] for i in axes) def _configure_axis( self, axis: str, # 'x' | 'y' ticklabels: Union[str, int, Sequence[int]], # where to show tick-labels params: Iterable, # (formatter, locator, label) for each Axes axes: List[matplotlib.axes.Axes] = None, # axes which to format ): if axes is None: axes = self.axes # find axes with tick-labels nax = len(axes) if isinstance(ticklabels, bool): show_ticklabels = [ticklabels] * nax elif isinstance(ticklabels, str): if ticklabels == 'bottom': if all(isinstance(ax, matplotlib.axes.SubplotBase) for ax in axes): subplotspecs = [ax.get_subplotspec() for ax in axes] bottom = min([spec.rowspan.stop for spec in subplotspecs]) show_ticklabels = [spec.rowspan.stop == bottom for spec in subplotspecs] else: first = len(axes) - min(self._layout.ncol, nax) show_ticklabels = [i >= first for i in range(len(axes))] elif ticklabels == 'left': if all(isinstance(ax, matplotlib.axes.SubplotBase) for ax in axes): subplotspecs = [ax.get_subplotspec() for ax in axes] left = min([spec.colspan.start for spec in subplotspecs]) show_ticklabels = [spec.colspan.start == left for spec in subplotspecs] else: ncol = self._layout.ncol or nax show_ticklabels = [i % ncol == 0 for i in range(len(axes))] elif ticklabels == 'all': show_ticklabels = [True] * nax elif ticklabels == 'none': show_ticklabels = [False] * nax else: raise ValueError(f"ticklabels={ticklabels!r}") else: show_ticklabels = [False] * nax if isinstance(ticklabels, int): show_ticklabels[ticklabels] = True else: for i in ticklabels: show_ticklabels[i] = True # parameter for hiding tick-labels if axis == 'y': tick_params = {'labelleft': False} else: tick_params = {'labelbottom': False} # format ticks labels = [] for ax, (formatter, locator, label_), show_ticklabels_ in zip(axes, params, show_ticklabels): axis_ = ax.yaxis if axis == 'y' else ax.xaxis if locator: axis_.set_major_locator(locator) if formatter: axis_.set_major_formatter(formatter) if not show_ticklabels_: ax.tick_params(**tick_params) labels.append(label_) # set labels if any(labels): if len(set(labels)) == 1: # default positioning if axis == 'y': self.set_ylabel(labels[0]) else: self.set_xlabel(labels[0]) else: for ax, label in zip(axes, labels): if label: if axis == 'y': ax.set_ylabel(label) else: ax.set_xlabel(label) def _configure_axis_data( self, axis: str, # 'x' | 'y' data: NDVar, # data for default label label: Union[bool, str], # override label ticklabels: Union[str, int, Sequence[int]] = True, # where to show tick-labels axes: List[matplotlib.axes.Axes] = None, # axes which to format ): "Configure an axis based on data" scale = AxisScale(data, label) formatters = repeat(scale.formatter) if not isinstance(scale.label, str) and isinstance(scale.label, Iterable): labels = chain(scale.label, repeat(None)) else: labels = repeat(scale.label) params = zip(formatters, repeat(None), labels) self._configure_axis(axis, ticklabels, params, axes) def _configure_axis_dim( self, axis: str, # 'x' | 'y' dim: Union[str, Dimension], # The dimension assigned to the axis label: Union[bool, str], # axis labale ticklabels: Union[str, int, Sequence[int]], # where to show tick-labels axes: List[matplotlib.axes.Axes] = None, # axes which to format scalar: bool = True, data: List = None, ): "Configure an axis based on a dimension" # Dimension objects if isinstance(dim, str): dims = [layers[0].get_dim(dim) for layers in data] else: dims = repeat(dim) params = (dim._axis_format(scalar, label) for dim in dims) self._configure_axis(axis, ticklabels, params, axes) def draw(self): "(Re-)draw the figure (after making manual changes)." if self._frame is None: return t0 = time.time() self._frame.canvas.draw() self._last_draw_time = time.time() - t0 def draw_crosshairs(self, enable=True): """Draw crosshairs under the cursor Parameters ---------- enable : bool Enable drawing crosshairs (default True, set to False to disable). """ self._draw_crosshairs = enable if not enable: self._remove_crosshairs(True) def draw_outline(self, color='k', **kwargs): """Draw the outline of the figure Mainly for fine-tuning the figure layout in Jupyter, which crops the display area based on figure elements rather than actual figure size. """ kwargs.setdefault('fc', 'none') artist = matplotlib.patches.Rectangle((0, 0), 1, 1, ec=color, **kwargs) self.figure.add_artist(artist) def save(self, *args, **kwargs): "Short-cut for Matplotlib's :meth:`~matplotlib.figure.Figure.savefig()`" self.figure.savefig(*args, **kwargs) def add_hline(self, y, axes=None, *args, **kwargs): """Draw a horizontal line on one or more axes Parameters ---------- y : scalar Level at which to draw the line. axes : int | list of int Which axes to mark (default is all axes). ... :meth:`matplotlib.axes.Axes.axhline` parameters. Notes ----- See Matplotlib's :meth:`matplotlib.axes.Axes.axhline` for more arguments. """ for ax in self._get_axes(axes): ax.axhline(y, *args, **kwargs) self.draw() def add_hspan(self, bottom, top, axes=None, *args, **kwargs): """Draw a horizontal bar on one or more axes Parameters ---------- bottom : scalar Bottom end of the horizontal bar. top : scalar Top end of the horizontal bar. axes : int | list of int Which axes to mark (default is all axes). ... :meth:`matplotlib.axes.Axes.axvspan` parameters. Notes ----- See Matplotlib's :meth:`matplotlib.axes.Axes.axhspan` for more arguments. """ for ax in self._get_axes(axes): ax.axhspan(bottom, top, *args, **kwargs) self.draw() def add_vline(self, x, axes=None, *args, **kwargs): """Draw a vertical line on one or more axes Parameters ---------- x : scalar Value at which to place the vertical line. axes : int | list of int Which axes to mark (default is all axes). ... :meth:`matplotlib.axes.Axes.axvspan` parameters. Notes ----- See Matplotlib's :meth:`matplotlib.axes.Axes.axvline` for more arguments. """ for ax in self._get_axes(axes): ax.axvline(x, *args, **kwargs) self.draw() def add_vspan(self, xmin, xmax, axes=None, *args, **kwargs): """Draw a vertical bar on one or more axes Parameters ---------- xmin : scalar Start value on the x-axis. xmax : scalar Last value on the x-axis. axes : int | list of int Which axes to mark (default is all axes). ... :meth:`matplotlib.axes.Axes.axvspan` parameters. Notes ----- See Matplotlib's :meth:`matplotlib.axes.Axes.axvspan` for more arguments. """ for ax in self._get_axes(axes): ax.axvspan(xmin, xmax, *args, **kwargs) self.draw() def set_name(self, name): """Set the figure window title""" plot_name = self.__class__.__name__ self._frame.SetTitle(f'{plot_name}: {name}' if name else plot_name) def set_xtick_rotation(self, rotation): """Rotate every x-axis tick-label by an angle (counterclockwise, in degrees) Parameters ---------- rotation : scalar Counterclockwise rotation angle, in degrees. """ for ax in self.axes: for t in ax.get_xticklabels(): t.set_rotation(rotation) self.draw() def set_xlabel(self, label: str, ax: int = None): """Set the label for the x-axis Parameters ---------- label X-axis label. ax Axis on which to set the label (default is usually the last axis). """ if ax is None: ax = self._default_xlabel_ax self.axes[ax].set_xlabel(label) def set_ylabel(self, label: str, ax: int = None): """Set the label for the y-axis Parameters ---------- label Y-axis label. ax Axis on which to set the label (default is usually the first axis). """ if ax is None: ax = self._default_ylabel_ax self.axes[ax].set_ylabel(label) def format_axes( ax: mpl.axes.Axes, frame: Union[bool, str], yaxis: bool, ): if frame == 't': ax.tick_params(direction='inout', bottom=False, top=True, left=False, right=True, labelbottom=True, labeltop=False, labelleft=True, labelright=False) ax.spines['right'].set_position('zero') ax.spines['left'].set_visible(False) ax.spines['top'].set_position('zero') ax.spines['bottom'].set_visible(False) elif frame == 'none': for spine in ax.spines.values(): spine.set_visible(False) elif frame == 'off': ax.axis('off') elif not frame: ax.yaxis.set_ticks_position('left') ax.spines['right'].set_visible(False) ax.xaxis.set_ticks_position('bottom') ax.spines['top'].set_visible(False) if not yaxis: ax.yaxis.set_ticks(()) ax.spines['left'].set_visible(False) class BaseLayout: def __init__( self, h: float, w: float, dpi: float, tight: bool, show: bool, run: bool, title: FMTextArg = None, autoscale: bool = False, name: str = None, right_of: Union[EelFigure, int] = None, below: Union[EelFigure, int] = None, axes: Union[matplotlib.axes.Axes, List[matplotlib.axes.Axes]] = None, ): self.h = h self.w = w self.dpi = dpi or mpl.rcParams['figure.dpi'] self.tight = tight self.show = show self.run = run self.autoscale = autoscale self.title = asfmtext_or_none(title) self.name = asfmtext_or_none(name) or title if isinstance(axes, matplotlib.axes.Axes): axes = [axes] elif axes is not None: axes = list(axes) self.user_axes = axes x = y = None if hasattr(right_of, '_frame'): rect = right_of._frame.GetRect() x = rect.GetRight() + 1 if below is None: y = rect.GetTop() elif isinstance(right_of, int): x = right_of elif right_of is not None: raise TypeError(f"{right_of=}") if hasattr(below, '_frame'): rect = below._frame.GetRect() y = rect.GetBottom() + 1 if x is None: x = rect.GetLeft() elif isinstance(below, int): y = below elif below is not None: raise TypeError(f"{below=}") if x is None and y is None: self.pos = None else: if x is None: x = -1 if y is None: y = -1 self.pos = (x, y) def fig_kwa(self): out = {'figsize': (self.w, self.h), 'dpi': self.dpi} if CONFIG['figure_background'] is not False: out['facecolor'] = CONFIG['figure_background'] return out def make_axes(self, figure): if self.user_axes: axes = self.user_axes else: axes = self._make_axes(figure) self._configure_axes(axes) return axes def _make_axes(self, figure): raise NotImplementedError def _configure_axes(self, axes): raise NotImplementedError def resolve_plot_rect(w, h, dpi): # infer figure dimensions from screen size w_applies = w is not None and w <= 0 h_applies = h is not None and h <= 0 if w_applies or h_applies: from .._wxgui import wx, get_app get_app() effective_dpi = dpi or mpl.rcParams['figure.dpi'] display_w, display_h = wx.GetDisplaySize() if h_applies: effective_display_h = display_h - 50 h = effective_display_h / effective_dpi + h if w_applies: w = display_w / effective_dpi + w return w, h class LayoutDim: "Helper function to determine figure spacing" _properties = ('total', 'ax', 'first', 'last', 'space') _equations = dict( total='first + n_ax * ax + (n_ax - 1) * space + last', ax='(total - first - last - (n_ax - 1) * space) / n_ax', first='total - n_ax * ax - (n_ax - 1) * space - last', last='total - first - n_ax * ax - (n_ax - 1) * space', space='(total - first - n_ax * ax - last) / (n_ax - 1)', ) def __init__(self, n_ax, total, ax, first, space, last, ax_default, first_default, space_default, last_default): if space is None and n_ax == 1: space = 0. values = {'total': total, 'first': first, 'space': space, 'last': last, 'ax': ax, 'n_ax': n_ax} defaults = {'first': first_default, 'space': space_default, 'last': last_default, 'ax': ax_default} for i, p in enumerate(self._properties): if values[p] is None: for p2 in self._properties[i + 1:]: if values[p2] is None: values[p2] = defaults[p2] values[p] = eval(self._equations[p], values) break self.total = values['total'] self.ax = values['ax'] self.first = values['first'] self.space = values['space'] self.last = values['last'] class Layout(BaseLayout): """Layout for figures with several axes of the same size""" _default_margins = {'left': 0.4, 'bottom': 0.5, 'right': 0.05, 'top': 0.05, 'wspace': 0.1, 'hspace': 0.1} def __init__( self, nax: Union[int, List[bool]], ax_aspect: float, # width / height axh_default: float, tight: bool = True, title: str = None, h: float = None, w: float = None, axh: float = None, axw: float = None, nrow: int = None, ncol: int = None, dpi: float = None, margins: Dict[str, float] = None, show: bool = True, run: bool = None, frame: Union[bool, str] = True, yaxis=True, share_axes: bool = False, **kwargs): """Create a grid of axes based on variable parameters. Parameters ---------- nax Number of axes required. If provided as a list, axes are only added for items where ``item`` is True. ax_aspect Width / height aspect of the axes. axh_default The default axes height if it can not be determined from the other parameters. tight Rescale axes so that the space in the figure is used optimally (default True). title : str Figure title. h Height of the figure. w Width of the figure. axh Height of the axes. axw Width of the axes. nrow Set a limit to the number of rows (default is no limit). ncol Set a limit to the number of columns (defaut is no limit). If neither nrow or ncol is specified, a square layout is preferred. dpi DPI for the figure (default is to use matplotlib rc parameters). margins Absolute subplot parameters (in inches). Implies ``tight=False``. If ``margins`` is specified, ``axw`` and ``axh`` are interpreted exclusive of the margins, i.e., ``axh=2, margins={'top': .5}`` for a plot with one axes will result in a total height of 2.5. show Show the figure in the GUI (default True). Use False for creating figures and saving them without displaying them on the screen. run Run the Eelbrain GUI app (default is True for interactive plotting and False in scripts). frame : bool | 't' | 'none' Draw frame around axes: - True: all four spines - False: only spines with ticks - 't': spines at x=0 and y=0 - 'none': no spines at all """ if h and axh: if h < axh: raise ValueError("h < axh") if w and axw: if w < axw: raise ValueError("w < axw") w, h = resolve_plot_rect(w, h, dpi) self.h_fixed = h self.w_fixed = w if w is not None else axw self._margins_arg = margins if margins is True: use_margins = True tight = False margins = self._default_margins.copy() elif margins is not None: use_margins = True tight = False margins = dict(margins) invalid = set(margins).difference(self._default_margins) if invalid: raise ValueError(f"{margins=}: Unknown keys {invalid}") else: margins = {k: 0 for k in self._default_margins} use_margins = False h_is_implicit = h is None w_is_implicit = w is None if nax is None: axes = None elif isinstance(nax, int): axes = list(range(nax)) elif isinstance(nax, (list, tuple)): axes = [i for i, ax in enumerate(nax) if ax] nax = len(nax) else: raise TypeError("nax=%r" % (nax,)) trim = None if not nax: if w is None: if h is None: h = axh_default w = ax_aspect * h elif h is None: h = w / ax_aspect elif nax == 1: ncol = ncol or 1 nrow = nrow or 1 elif nrow is None and ncol is None: if w and axw: trim = 'row' ncol = math.floor(w / axw) elif h and axh: trim = 'col' nrow = math.floor(h / axh) elif w: trim = 'row' if axh: ncol = round(w / (axh * ax_aspect)) else: ncol = round(w / (axh_default * ax_aspect)) ncol = max(1, min(nax, ncol)) elif h: trim = 'col' if axw: nrow = round(h / (axw / ax_aspect)) else: nrow = round(h / axh_default) nrow = max(1, min(nax, nrow)) elif axh or axw: trim = 'row' if not axh: axh = axw / ax_aspect nrow = min(nax, math.floor(defaults['maxh'] / axh)) else: trim = 'row' # default: minimum number of columns (max number of rows) hspace = margins.get('hspace', 0) maxh = defaults['maxh'] - margins.get('top', 0) - margins.get('bottom', 0) + hspace axh_with_space = axh_default + hspace nrow = min(nax, math.floor(maxh / axh_with_space)) ncol = math.ceil(nax / nrow) # test width wspace = margins.get('wspace', 0) maxw = defaults['maxw'] - margins.get('left', 0) - margins.get('right', 0) + wspace axw_with_space = axh_default * ax_aspect + wspace if ncol * axw_with_space > maxw: # nrow/ncol proportional to (maxh / axh) / (maxw / axw) ratio = (maxh / axh_with_space) / (maxw / axw_with_space) # nax = ncol * (ncol * ratio) # ncol = sqrt(nax / ratio) ncol = math.floor(math.sqrt(nax / ratio)) nrow = math.ceil(nax / ncol) axh = (maxh - nrow * hspace) / nrow axw = axh * ax_aspect if nax: if nrow is None: nrow = math.ceil(nax / ncol) elif ncol is None: ncol = math.ceil(nax / nrow) if trim == 'row': if (nrow * ncol) - nax >= ncol: nrow -= 1 elif trim == 'col': if (nrow * ncol) - nax >= nrow: nrow -= 1 if axw: axh_default = axw / ax_aspect elif w: axh_default = w / ncol / ax_aspect h_dim = LayoutDim(nrow, h, axh, margins.get('top'), margins.get('hspace'), margins.get('bottom'), axh_default, self._default_margins['top'], self._default_margins['hspace'], self._default_margins['bottom']) w_dim = LayoutDim(ncol, w, axw, margins.get('left'), margins.get('wspace'), margins.get('right'), h_dim.ax * ax_aspect, self._default_margins['left'], self._default_margins['wspace'], self._default_margins['right']) h = h_dim.total w = w_dim.total axh = h_dim.ax axw = w_dim.ax margins = { 'top': h_dim.first, 'bottom': h_dim.last, 'hspace': h_dim.space, 'left': w_dim.first, 'right': w_dim.last, 'wspace': w_dim.space} h_is_implicit = w_is_implicit = False if h_is_implicit: hspace = 0 if nrow is None else margins['hspace'] * (nrow - 1) h += margins['bottom'] + hspace + margins['top'] if w_is_implicit: wspace = 0 if ncol is None else margins['wspace'] * (ncol - 1) w += margins['left'] + wspace + margins['right'] BaseLayout.__init__(self, h, w, dpi, tight, show, run, title, **kwargs) self.nax = nax self.axes = axes self.axh = axh self.axw = axw self.nrow = nrow self.ncol = ncol self.frame = frame self.yaxis = yaxis self.share_axes = share_axes self.margins = margins if use_margins else None def __repr__(self): kwargs = self.fig_kwa() if 'subplotpars' in kwargs: pars = kwargs['subplotpars'] attrs = ((k, getattr(pars, k)) for k in ('left', 'right', 'bottom', 'top', 'wspace', 'hspace')) desc = ', '.join(f'{k}={v}' for k, v in attrs if v is not None) kwargs['subplotpars'] = f"<{desc}>" args = ', '.join(f'{k}={v}' for k, v in kwargs.items()) return f'<Layout: {args}>' def fig_kwa(self): out = BaseLayout.fig_kwa(self) if self.margins: # absolute subplot parameters out['subplotpars'] = SubplotParams( self.margins['left'] / self.w, self.margins['bottom'] / self.h, 1 - self.margins['right'] / self.w, 1 - self.margins['top'] / self.h, # space expressed as a fraction of the average axis height/width self.margins['wspace'] / self.axw, self.margins['hspace'] / self.axh) return out def _make_axes(self, figure): if not self.nax: return [] axes = [] kwargs = {} for i in self.axes: ax = figure.add_subplot(self.nrow, self.ncol, i + 1, autoscale_on=self.autoscale, **kwargs) axes.append(ax) if self.share_axes: kwargs.update(sharex=ax, sharey=ax) return axes def _configure_axes(self, axes): for ax in axes: format_axes(ax, self.frame, self.yaxis) return axes class ImLayout(Layout): """Layout subclass for axes without space Make sure to specify the ``margins`` parameter for absolute spacing """ def __init__( self, nax: Union[int, List[bool]], ax_aspect: float, # width / height axh_default: float, margins: dict = None, default_margins: dict = None, title: str = None, axtitle: Union[bool, Sequence[str]] = False, # for default spacing **kwargs, ): if axtitle is True: has_axtitle = (len(nax) if isinstance(nax, list) else nax) > 1 else: has_axtitle = True if isinstance(axtitle, np.ndarray) else bool(axtitle) title_space = 1.5 * mpl_font_size('figure.titlesize') if title else 0 axtitle_space = 1.5 * mpl_font_size('axes.titlesize') if has_axtitle else 0 margins_ = { 'left': 0, 'wspace': 0, 'right': 0, 'top': axtitle_space + title_space, 'hspace': axtitle_space, 'bottom': 0, } if default_margins: margins_.update(default_margins) if margins: margins_.update(margins) Layout.__init__(self, nax, ax_aspect, axh_default, title=title, margins=margins_, **kwargs) def _make_axes(self, figure): axes = [] for i in self.axes: ax = figure.add_subplot(self.nrow, self.ncol, i + 1, autoscale_on=self.autoscale) axes.append(ax) return axes def _configure_axes(self, axes): for ax in axes: ax.axis('off') class VariableAspectLayout(BaseLayout): """Layout with a fixed number of columns that differ in spacing Axes are originally created to fill the whole rectangle allotted to them. Developed for TopoButterfly plot: one variable aspect butterfly plot, and one square topomap plot. Parameters ---------- nrow Number of rows. axh_default Default row height. w_default Default figure width. aspect Axes aspect ratio (w/h) for each column; None for axes with flexible width. ax_kwargs Parameters for :meth:`figure.add_axes` for each column. ax_frames ``frame`` parameter for :func:`format_axes` for each column. row_titles One title per row. """ def __init__( self, nrow: int, axh_default: float, w_default: float, aspect: Sequence[Optional[float]] = (None, 1), ax_kwargs: Sequence[dict] = None, ax_frames: Sequence[bool] = None, row_titles: Sequence[Optional[str]] = None, title: FMTextArg = None, h: float = None, w: float = None, axh: float = None, dpi: float = None, show: bool = True, run: bool = None, **kwargs, ): w, h = resolve_plot_rect(w, h, dpi) self.w_fixed = w if axh and h: raise ValueError("h and axh can not be specified both at the same time") elif h: axh = h / nrow elif axh: h = nrow * axh else: axh = axh_default h = nrow * axh if w is None: w = w_default if ax_kwargs is None: ax_kwargs = [{}] * len(aspect) if ax_frames is None: ax_frames = [True] * len(aspect) BaseLayout.__init__(self, h, w, dpi, False, show, run, title, **kwargs) self.nax = nrow * len(aspect) self.axh = axh self.nrow = nrow self.ncol = len(aspect) self.share_axes = False self.row_titles = row_titles self.aspect = aspect self.n_flexible = self.aspect.count(None) self.ax_kwargs = ax_kwargs self.ax_frames = ax_frames # Compute axes outlines for given height and width h = self.h w = self.w text_buffer = 20 * POINT # buffers for legends left_buffer = text_buffer * (3 + (self.row_titles is not None)) bottom_buffer = text_buffer * 2 top_buffer = text_buffer * (1 + 2 * bool(self.title)) # rectangle base in inches axh = (h - bottom_buffer - top_buffer) / self.nrow axws = [None if a is None else a * axh for a in self.aspect] fixed = sum(axw for axw in axws if axw is not None) w_free = (w - fixed - left_buffer) / self.n_flexible widths = [w_free if axw is None else axw for axw in axws] lefts = (sum(widths[:i]) + left_buffer for i in range(len(widths))) bottoms = (i * axh + bottom_buffer for i in range(self.nrow - 1, -1, -1)) # convert to figure coords height = axh / h lefts_ = [l / w for l in lefts] widths_ = [w_ / w for w_ in widths] bottoms_ = [b / h for b in bottoms] # rectangles: (left, bottom, width, height) self._ax_rects = [[(l, bottom, w, height) for l, w in zip(lefts_, widths_)] for bottom in bottoms_] def _make_axes(self, figure): axes = [] for row, row_rects in enumerate(self._ax_rects): for rect, kwa, frame in zip(row_rects, self.ax_kwargs, self.ax_frames): ax = figure.add_axes(rect, autoscale_on=self.autoscale, **kwa) axes.append(ax) if self.row_titles and self.row_titles[row]: bottom, height = rect[1], rect[3] figure.text(0, bottom + height / 2, self.row_titles[row], ha='left', va='center', rotation='vertical') return axes def _configure_axes(self, axes): for ax, frame in zip(axes, cycle(self.ax_frames)): format_axes(ax, frame, True) # id axes for callbacks for i, ax in enumerate(axes): ax.id = i def subplots( nrows: int = 1, ncols: int = 1, axh: float = None, axw: float = None, h: float = None, w: float = None, left: float = None, right: float = None, wspace: float = None, width_ratios: Sequence[float] = None, bottom: float = None, top: float = None, hspace: float = None, height_ratios: Sequence[float] = None, **kwargs, ): """Specify :func:`matplotlib.pyplot.subplots` parameters in inches Parameters ---------- nrows Number of subplot rows. ncols Number of subplot columns. axh Height of each axes. axw Width of each axes. h Figure height. w Figure width. left Margin to the left of the axes. right Margin to the right of the axes. wspace Width of the margin between axes. width_ratios The relative widths of the columns (see :class:`matplotlib.gridspec.GridSpec`). bottom Margin below the axes. top Margin above the axes. hspace Height of the margin between axes. height_ratios The relative heights of the rows (see :class:`matplotlib.gridspec.GridSpec`). ** Other parameters for :func:`matplotlib.pyplot.subplots`. """ from matplotlib import pyplot margins = {'left': left, 'bottom': bottom, 'right': right, 'top': top, 'wspace': wspace, 'hspace': hspace} layout = Layout(nrows*ncols, 1, 2, False, None, h, w, axh, axw, nrows, ncols, None, margins) gridspec_kw = { 'left': layout.margins['left'] / layout.w, 'right': 1 - layout.margins['right'] / layout.w, 'wspace': layout.margins['wspace'] / layout.axw, 'width_ratios': width_ratios, 'bottom': layout.margins['bottom'] / layout.h, 'top': 1 - layout.margins['top'] / layout.h, 'hspace': layout.margins['hspace'] / layout.axh, 'height_ratios': height_ratios, } return pyplot.subplots(layout.nrow, layout.ncol, figsize=(layout.w, layout.h), gridspec_kw=gridspec_kw, **kwargs) class ColorBarMixin: """Colorbar toolbar button mixin Parameters ---------- param_func : func Function that returns color-bar parameters. """ def __init__( self, param_func: Callable = None, # function to get cmap, vmin, vmax data: Union[NDVar, Var, Number, str, 'PlotData'] = None, # to infer unit mappable: Any = None, # matplotlib mappable object ): self.__get_params = param_func self.__mappable = mappable if data is None: self.__scale = AxisScale(1) else: self.__scale = AxisScale(data) def _fill_toolbar(self, tb): from .._wxgui import wx, ID, Icon tb.AddTool(ID.PLOT_COLORBAR, "Plot Colorbar", Icon("plot/colorbar")) tb.Bind(wx.EVT_TOOL, self.__OnPlotColorBar, id=ID.PLOT_COLORBAR) def __OnPlotColorBar(self, event): return self.plot_colorbar() def plot_colorbar( self, label: Union[bool, str] = True, label_position: Literal['left', 'right', 'top', 'bottom'] = None, label_rotation: float = None, clipmin: float = None, clipmax: float = None, orientation: Literal['horizontal', 'vertical'] = 'horizontal', **kwargs, ): """Plot a colorbar corresponding to the displayed data Parameters ---------- label Label for the x-axis (default is based on the data). label_position Position of the axis label. Valid values depend on orientation. label_rotation Angle of the label in degrees (For horizontal colorbars, the default is 0; for vertical colorbars, the default is 0 for labels of 3 characters and shorter, and 90 for longer labels). clipmin Clip the color-bar below this value. clipmax Clip the color-bar above this value. orientation Orientation of the bar (default is horizontal). ... More parameters for :class:`plot.ColorBar`. Returns ------- colorbar : plot.ColorBar ColorBar plot object. """ # cf. matplorlib.colorbar.Colorbar transforming mappable to color-map from . import ColorBar if self.__mappable is not None: cmap = self.__mappable.cmap vmin = self.__mappable.norm vmax = None elif self.__get_params is not None: cmap, vmin, vmax = self.__get_params() else: raise RuntimeError(f"No colormap on {self}") return ColorBar(cmap, vmin, vmax, label, label_position, label_rotation, clipmin, clipmax, orientation, self.__scale, **kwargs) class ColorMapMixin(ColorBarMixin): """takes care of color-map and includes color-bar""" _can_set_vlim = True def __init__(self, epochs, cmap, vmax, vmin, contours, plots): ColorBarMixin.__init__(self, self.__get_cmap_params, epochs[0][0]) self.__plots = plots # can be empty list at __init__ self._cmaps = find_fig_cmaps(epochs, cmap) self._vlims = find_fig_vlims(epochs, vmax, vmin, self._cmaps) self._contours = find_fig_contours(epochs, self._vlims, contours) self._first_meas = epochs[0][0].info.get('meas') def __get_cmap_params(self): return (self._cmaps[self._first_meas],) + self._vlims[self._first_meas] def add_contour(self, level: float, color: Any = 'k', meas: str = None): """Add a contour line Parameters ---------- level : scalar The value at which to draw the contour. color : matplotlib color The color of the contour line. meas : str The measurement for which to add a contour line (default is the measurement plotted first). """ if meas is None: meas = self._first_meas for p in self.__plots: p.add_contour(meas, level, color) self.draw() def set_cmap(self, cmap, meas=None): """Change the colormap in the array plots Parameters ---------- cmap : str | colormap New colormap. meas : None | str Measurement to which to apply the colormap. With None, it is applied to all. """ if meas is None: meas = self._first_meas for p in self.__plots: p.set_cmap(cmap, meas) self._cmaps[meas] = cmap if isinstance(cmap, LocatedColormap): self.set_vlim(cmap.vmin, cmap.vmax, meas) else: self.draw() def set_vlim(self, v=None, vmax=None, meas=None): """Change the colormap limits If the limit is symmetric, use ``set_vlim(vlim)``; if it is not, use ``set_vlim(vmin, vmax)``. Parameters ---------- v : scalar If this is the only value specified it is interpreted as the upper end of the scale, and the lower end is determined based on the colormap to be ``-v`` or ``0``. If ``vmax`` is also specified, ``v`` specifies the lower end of the scale. vmax : scalar (optional) Upper end of the color scale. meas : str (optional) Measurement type to apply (default is the first one found). """ if meas is None: meas = self._first_meas elif meas not in self._cmaps: raise ValueError("meas=%r" % (meas,)) if vmax is None: vmin, vmax = fix_vlim_for_cmap(None, abs(v), self._cmaps[meas]) else: vmin = v for p in self.__plots: p.set_vlim(vmin, vmax, meas) self._vlims[meas] = vmin, vmax if self._can_set_ylim: self.set_ylim(vmin, vmax) else: self.draw() def get_vlim(self, meas=None): "Retrieve colormap value limits as ``(vmin, vmax)`` tuple" if meas is None: meas = self._first_meas return self._vlims[meas] class LegendMixin: __choices = ('invisible', 'separate window', 'draggable', 'upper right', 'upper left', 'lower left', 'lower right', 'right', 'center left', 'center right', 'lower center', 'upper center', 'center') __args = (False, 'fig', 'draggable', 1, 2, 3, 4, 5, 6, 7, 8, 9, 10) _has_frame = None def __init__( self, loc: LegendArg, handles: Dict[CellArg, Any], labels: Dict[CellArg, str] = None, ): """Legend toolbar menu mixin Parameters ---------- loc Matplotlib figure legend location argument or 'fig' to plot the legend in a separate figure. handles : dict {cell: handle} dictionary. labels : dict Dictionary with labels for cells. """ # whether to plot default legend if loc is not None: initial_loc = loc elif len(handles) > 1: initial_loc = 'upper right' else: initial_loc = False self.__handles = handles self.legend = None self.__labels = None self.__set_labels(labels) self.plot_legend(initial_loc) def __set_labels(self, labels: Dict[CellArg, str] = None): if labels is not None: self.__labels = {key: asfmtext(label) for key, label in labels.items()} def _fill_toolbar(self, tb): from .._wxgui import wx choices = [name.title() for name in self.__choices] self.__ctrl = wx.Choice(tb, choices=choices, name='Legend') tb.AddControl(self.__ctrl, "Legend") self.__ctrl.Bind(wx.EVT_CHOICE, self.__OnChoice, source=self.__ctrl) def __OnChoice(self, event): self.__plot(self.__args[event.GetSelection()]) def plot_legend( self, loc: LegendArg = 'fig', labels=None, **kwargs): """Plot the legend (or remove it from the figure). Parameters ---------- loc Where to plot the legend (see Notes; default 'fig'). labels : dict Dictionary with alternate labels for all cells. ... : Parameters for :class:`eelbrain.plot.Legend`. Returns ------- legend_figure : None | legend If loc=='fig' the Figure, otherwise None. Notes ----- legend content can be modified through the figure's ``legend_handles`` and ``legend_labels`` attributes. Possible values for the ``loc`` argument: ``False``: Make the current legend invisible ``'fig'``: Plot the legend in a new figure ``'draggable'``: The legend can be dragged to the desired position with the mouse pointer. str | int | (float, float): Matplotlib :meth:`~matplotlib.figure.Figure.legend` position argument. """ if loc in self.__choices: choice = self.__choices.index(loc) arg = self.__args[choice] elif loc is None: choice = 0 arg = False elif loc is True: choice = 3 arg = 'best' elif isinstance(loc, Sequence) and not isinstance(loc, str): choice = 0 arg = loc elif loc not in self.__args: raise ValueError(f"Invalid legend location: {loc!r}; use one of: {enumeration(map(repr, self.__choices), 'or')}") else: choice = self.__args.index(loc) arg = loc if self._has_frame: self.__ctrl.SetSelection(choice) if arg is not False: return self.__plot(loc, labels, **kwargs) def save_legend(self, *args, **kwargs): """Save the legend as image file Parameters ---------- ... : Parameters for Matplotlib's figure.savefig() """ p = self.plot_legend(show=False) p.save(*args, **kwargs) p.close() def __plot(self, loc: LegendArg, labels: Dict[CellArg, str] = None, **kwargs): self.__set_labels(labels) if loc and self.__handles: if self.__labels is None: cells = list(self.__handles) labels = [cellname(cell) for cell in cells] elif isinstance(self.__labels, dict): cells = list(self.__labels.keys()) labels = list(self.__labels.values()) else: raise TypeError(f"{labels=}; needs to be dict") handles = [self.__handles[cell] for cell in cells] if loc == 'fig': return Legend(handles, labels, **kwargs) else: # take care of old legend if self.legend is not None and loc == 'draggable': self.legend.set_draggable(True) elif self.legend is not None: self.legend.remove() elif loc == 'draggable': self.legend = self.figure.legend(handles, labels, loc=1) self.legend.set_draggable(True) if loc != 'draggable': self.legend = self.figure.legend(handles, labels, loc=loc) self.draw() elif self.legend is not None: self.legend.remove() self.legend = None self.draw() elif not self.__handles: raise RuntimeError("No handles to produce legend.") class Legend(EelFigure): def __init__(self, handles, labels, **kwargs): layout = Layout(0, 1, 2, tight=False, **kwargs) EelFigure.__init__(self, None, layout) self.legend = self.figure.legend(handles, labels, loc=2) # resize figure to match legend if not self._layout.w_fixed and self._has_frame: self.draw() bb = self.legend.get_window_extent() w0, h0 = self._frame.GetSize() h = int(h0 + bb.x0 - bb.y0) w = int(bb.x0 + bb.x1) self._frame.SetSize((w, h)) self._show() class TimeController: # Link plots that have the TimeSlicer mixin def __init__( self, t: float = 0, fixate: bool = False, ): self._plots = [] # list of weakref to plots self.current_time = t self.fixate = fixate def add_plot(self, plot: 'TimeSlicer'): if plot._time_controller is None: t = plot._validate_time(self.current_time) plot._set_time(t, self.fixate) self._plots.append(weakref.ref(plot)) plot._time_controller = self elif plot._time_controller is not self: self.merge(plot._time_controller) def iter_plots(self): needs_cleaning = False for ref in self._plots: plot = ref() if plot is None: needs_cleaning = True else: yield plot if needs_cleaning: self._plots = [ref for ref in self._plots if ref() is not None] def merge(self, time_controller): "Merge another TimeController into self" for plot in time_controller.iter_plots(): plot._time_controller = None self.add_plot(plot) def set_time(self, t, fixate): if t == self.current_time and fixate == self.fixate: return for p in self.iter_plots(): t = p._validate_time(t) for p in self.iter_plots(): p._update_time_wrapper(t, fixate) self.current_time = t self.fixate = fixate def set_xlim(self, xmin, xmax): for p in self.iter_plots(): if isinstance(p, XAxisMixin): p._set_xlim(xmin, xmax, draw=True) class TimeSlicer: # Interface to link time axes of multiple plots. # update data in a child plot of time-slices _time_dim = None _current_time = None # needs to reflect what is currently displayed _initial_time = None # used by delayed initialization of time-controller _display_time_in_frame_title = False def __init__( self, time_dim: Union[UTS, Case] = None, time_fixed: bool = None, display_text: matplotlib.text.Text = None, initial_time: float = None, ): self._time_controller = None self._time_fixed = time_fixed if time_fixed is not None else (initial_time is not None) self.__display_text = display_text self._initial_time = initial_time if time_dim is not None: self._init_time_dim(time_dim) def _init_time_dim(self, time_dim: Union[UTS, Case]): if self._time_dim is not None: if time_dim == self._time_dim: return raise ValueError(f"An incompatible time dimension is already set on {self}\nold: {self._time_dim}\nnew: {time_dim}") self._time_dim = time_dim if isinstance(time_dim, UTS): if self._initial_time is None: self._initial_time = time_dim.tmin elif isinstance(time_dim, Case): if self._initial_time is None: self._initial_time = 0 else: raise TypeError(f'{time_dim=}') def _init_controller(self): # Only instantiated if more than one plots need to be linked tc = TimeController(self._initial_time, self._time_fixed) tc.add_plot(self) def link_time_axis(self, other): """Link the time axis of this figure with another figure""" if self._time_dim is None: raise NotImplementedError("Slice plot for dimension other than time") elif not isinstance(other, TimeSlicer): raise TypeError(f"{other.__class__.__name__} plot does not support linked time axes") elif other._time_dim is None: raise NotImplementedError("Slice plot for dimension other than time") elif other._time_controller: other._time_controller.add_plot(self) else: if not self._time_controller: self._init_controller() self._time_controller.add_plot(other) def _nudge_time(self, offset): if self._time_dim is None: return current_i = self._time_dim._array_index(self.get_time()) if offset > 0: new_i = min(self._time_dim.nsamples - 1, current_i + offset) else: new_i = max(0, current_i + offset) self._set_time(self._time_dim[new_i], True) def get_time(self): "Retrieve the current time" if self._current_time is None: return self._initial_time return self._current_time def play_movie(self, time_dilation=4.): """Cycle through the time axis See Also -------- .save_movie : Save a movie to disk for smoother playback """ t = self._time_dim[0] self.set_time(t) tmax = self._time_dim[-1] last_frame = time.time() time.sleep(0.05) while True: now = time.time() t += (now - last_frame) / time_dilation last_frame = now if t > tmax: break self.set_time(t) self.set_time(tmax) def set_time(self, time): """Set the time point to display Parameters ---------- time : scalar Time to display. """ self._set_time(time, True) def _set_time(self, t, fixate=False): "Called by the plot" if self._time_controller is None: self._update_time_wrapper(t, fixate) else: self._time_controller.set_time(t, fixate) def _update_time_wrapper(self, t, fixate): "Called by the TimeController" if t == self._current_time and fixate == self._time_fixed: return self._update_time(t, fixate) self._current_time = t self._time_fixed = fixate if self._display_time_in_frame_title and self._frame: self._frame.SetTitleSuffix(f' [{ms(t)} ms]') if self.__display_text is not None: self.__display_text.set_text(f'{ms(t)} ms') def _update_time(self, t, fixate): raise NotImplementedError def _validate_time(self, t): if self._time_dim is not None: if t < self._time_dim.tmin: return self._time_dim.tmin elif t > self._time_dim.tmax: return self._time_dim.tmax return t def _im_array(self): # for movies raise NotImplementedError class TimeSlicerEF(TimeSlicer): # TimeSlicer for Eelfigure _can_set_time = True def __init__( self, x_dimname: str, x_dim: Dimension, axes: Sequence[matplotlib.axes.Axes] = None, redraw: bool = True, display_text: matplotlib.text.Text = None, initial_time: float = None, ): if x_dimname != 'time': TimeSlicer.__init__(self, time_fixed=True, display_text=display_text) return TimeSlicer.__init__(self, x_dim, display_text=display_text, initial_time=initial_time) self.__axes = self.axes if axes is None else axes self.__time_lines = [] self.__redraw = redraw self.canvas.mpl_connect('button_press_event', self._on_click) self._register_key('.', self._on_nudge_time) self._register_key(',', self._on_nudge_time) def _on_click(self, event): if self._time_controller and event.inaxes in self.__axes: self._set_time(event.xdata, fixate=event.button == 1) def _on_motion_sub(self, event): if not self._time_fixed and event.inaxes in self.__axes: self._set_time(event.xdata) return set() def _on_nudge_time(self, event): self._nudge_time(1 if event.key == '.' else -1) def _update_time(self, t, fixate): # Implementation for a plot with time axes if fixate: redraw = True if self.__time_lines: xdata = (t, t) for line in self.__time_lines: line.set_xdata(xdata) else: for ax in self.__axes: self.__time_lines.append(ax.axvline(t, color='k')) else: redraw = bool(self.__time_lines) while self.__time_lines: self.__time_lines.pop().remove() if self.__redraw and redraw and self._frame is not None: self.canvas.redraw(self.__axes) def save_movie(self, filename=None, time_dilation=4., **kwargs): """Save the figure with moving time axis as movie Parameters ---------- filename : path-like Filename for the movie (omit to use a GUI). time_dilation : float Factor by which to stretch time (default 4). Time dilation is controlled through the frame-rate; if the ``fps`` keyword argument is specified, ``time_dilation`` is ignored. ... :func:`imageio.mimwrite` parmeters. """ import imageio if filename is None: filename = ui.ask_saveas("Save movie...", None, [('Movie (*.mov)', '*.mov')]) if not filename: return else: filename = os.path.expanduser(filename) if 'fps' not in kwargs: kwargs['fps'] = 1. / self._time_dim.tstep / time_dilation ims = [] for t in self._time_dim: self._set_time(t, True) im = self._im_array() ims.append(im) imageio.mimwrite(filename, ims, **kwargs) def _im_array(self): # private attr usage is official: https://matplotlib.org/gallery/misc/agg_buffer_to_array.html return np.array(self.figure.canvas.renderer._renderer) class TopoMapKey: def __init__(self, data_func): self.__topo_data = data_func self._register_key('t', self.__on_topo) self._register_key('T', self.__on_topo) def __on_topo(self, event): topo_data = self.__topo_data(event) if topo_data is None: return from ._topo import Topomap data, title, proj = topo_data if event.key == 't': Topomap(data, proj=proj, cmap=self._cmaps, vmax=self._vlims, contours=self._contours, title=title) else: Topomap(data, proj=proj, cmap=self._cmaps, vmax=self._vlims, contours=self._contours, title=title, axw=9, sensorlabels='name') class CategorialAxisMixin: def __init__(self, ax, axis, layout, label, model, ticks, labels, tick_delim, tick_pos, cells, origin=None): self.__ax = ax self.__axis = axis self.__cells = cells if axis == 'x': self.__axis_obj = ax.xaxis if layout.frame is not True: ax.spines['bottom'].set_visible(False) if origin is not None: ax.axhline(origin, color='k', linewidth=mpl.rcParams['axes.linewidth'], clip_on=False) elif axis == 'y': self.__axis_obj = ax.yaxis if layout.frame is not True: ax.spines['left'].set_visible(False) if origin is not None: ax.axvline(origin, color='k', linewidth=mpl.rcParams['axes.linewidth'], clip_on=False) else: raise ValueError(f"axis={axis!r}") # axis label if label is True: if model is not None and model.name: label = model.name.replace('_', ' ') else: label = False if label: self.__axis_obj.set_label_text(label) # ticks self.__axis_obj.set_ticks_position('none') if ticks: if isinstance(ticks, dict) or ticks is True: labels_ = find_labels(cells, labels, tick_delim) if isinstance(ticks, dict): labels_.update(ticks) tick_labels = [labels_[cell] for cell in cells] else: tick_labels = ticks self.__axis_obj.set_ticks(tick_pos) self.__axis_obj.set_ticklabels(tick_labels) elif ticks is False: self.__axis_obj.set_ticks(()) if axis == 'x' and self._has_frame and not self._layout.w_fixed: self._draw_hooks.append(self.__separate_categorial_labels) def __separate_categorial_labels(self): # make sure x axis labels don't overlap labels = self.__axis_obj.get_ticklabels() n = len(labels) if n > 1: bbs = [l.get_window_extent(self.figure.canvas.renderer) for l in labels] overlap = max(bbs[i].x1 - bbs[i + 1].x0 for i in range(n - 1)) extend = n * (overlap + 10) w, h = self._frame.GetSize() w += int(extend) self._frame.SetSize((w, h)) return True def mark_pair( self, cell_1: Union[float, CellArg], cell_2: Union[float, CellArg], y: float, dy: float = None, mark: Union[float, str] = None, color: Any = None, nudge: Union[bool, float] = None, **text_args, ): """Mark a pair of categories with a line and a label Parameters ---------- cell_1 Data-cell to be compared (can be specified as cell or as x-coordinate) cell_2 Second cell to be compared. y Level above which to plot the bar. dy Length of vertical ticks on each side of the bar (offsets the location of the bar itself to ``y + dy``; use negative values to flip orientation). mark Text label, or p-value to automatically determine the label and ``color``. color Color for bar and ``label``. nudge Nudge the edges of the bar inwards to allow multiple bars side-by-side on the same level of ``y``. ... All other parameters are used to plot the text label with :meth:`matplotlib.axes.Axes.text`. """ if isinstance(cell_1, (str, tuple)): x1 = self.__cells.index(cell_1) else: x1 = cell_1 if isinstance(cell_2, (str, tuple)): x2 = self.__cells.index(cell_2) else: x2 = cell_2 location = {'x': 'top', 'y': 'right'}[self.__axis] mark_difference(x1, x2, y, mark, dy, color, nudge, location, self.__ax, **text_args) class XAxisMixin: """Manage x-axis Parameters ---------- xmin : scalar Lower bound of the x axis. xmin : scalar Upper bound of the x axis. axes : list of Axes Axes that should be managed by the mixin. xlim : scalar | (scalar, scalar) Initial x-axis view limits as ``(left, right)`` tuple or as ``length`` scalar (default is the full x-axis in the data). Notes ----- Navigation: - ``←``: scroll left - ``→``: scroll right - ``home``: scroll to beginning - ``end``: scroll to end - ``f``: x-axis zoom in (reduce x axis range) - ``d``: x-axis zoom out (increase x axis range) """ _can_set_xlim = True def __init__(self, xmin, xmax, xlim=None, axes=None): self.__xmin = xmin self.__xmax = xmax self.__axes = axes or self.axes self.__vspans = [] self._register_key('f', self.__on_zoom_plus) self._register_key('d', self.__on_zoom_minus) self._register_key('j' if IS_WINDOWS else 'left', self.__on_left) self._register_key('l' if IS_WINDOWS else 'right', self.__on_right) self._register_key('home', self.__on_beginning) self._register_key('end', self.__on_end) if xlim is None: xlim = (self.__xmin, self.__xmax) elif np.isscalar(xlim): xlim = (self.__xmin, self.__xmin + xlim) self._set_xlim(*xlim) def _init_with_data( self, epochs: Sequence[Sequence[NDVar]], xdim: str, xlim: Union[float, Tuple[float, float]] = None, axes: List[matplotlib.axes.Axes] = None, im: bool = False, ): """Compute axis bounds from data Parameters ---------- epochs The data that is plotted (to determine axis range). xdim Dimension that is plotted on the x-axis. axes Axes that should be managed by the mixin. xlim Initial x-axis view limits as ``(left, right)`` tuple or as ``length`` scalar (default is the full x-axis in the data). im Plot displays an im, i.e. the axes limits need to extend beyond the dimension endpoints by half a step (default False). """ dims = (e.get_dim(xdim) for e in chain(*epochs)) if im: dim_extent = [dim._axis_im_extent() for dim in dims] else: dim_extent = [dim._axis_extent() for dim in dims] xmin = min(e[0] for e in dim_extent) xmax = max(e[1] for e in dim_extent) XAxisMixin.__init__(self, xmin, xmax, xlim, axes) def get_xlim(self): return self.__axes[0].get_xlim() def __animate(self, vmin, vmin_dst, vmax, vmax_dst): n_steps = int(0.1 // self._last_draw_time) if n_steps > 1: vmin_d = vmin_dst - vmin vmax_d = vmax_dst - vmax for i in range(1, n_steps): x = i / n_steps self.set_xlim(vmin + x * vmin_d, vmax + x * vmax_d) self.set_xlim(vmin_dst, vmax_dst) def __on_beginning(self, event): left, right = self.get_xlim() d = right - left self.set_xlim(self.__xmin, min(self.__xmax, self.__xmin + d)) def __on_end(self, event): left, right = self.get_xlim() d = right - left self.set_xlim(max(self.__xmin, self.__xmax - d), self.__xmax) def __on_zoom_plus(self, event): left, right = self.get_xlim() d = (right - left) / 4. self.__animate(left, left + d, right, right - d) def __on_zoom_minus(self, event): left, right = self.get_xlim() d = right - left new_left = max(self.__xmin, left - (d / 2.)) new_right = min(self.__xmax, new_left + 2 * d) self.__animate(left, new_left, right, new_right) def __on_left(self, event): left, right = self.get_xlim() d = right - left new_left = max(self.__xmin, left - d) self.__animate(left, new_left, right, new_left + d) def __on_right(self, event): left, right = self.get_xlim() d = right - left new_right = min(self.__xmax, right + d) self.__animate(left, new_right - d, right, new_right) def _set_xlim(self, left, right, draw=False): for ax in self.__axes: ax.set_xlim(left, right) if draw: self.draw() def add_vspans(self, intervals, axes=None, *args, **kwargs): """Draw vertical bars over axes Parameters ---------- intervals : sequence of (start, stop) tuples Start and stop positions on the x-axis. axes : int | list of int Which axes to mark (default is all axes). additonal arguments : Additional arguments for :func:`matplotlib.axvspan`. """ if axes is None: axes = self.__axes elif isinstance(axes, int): axes = (self.__axes[axes],) else: axes = [self.__axes[i] for i in axes] for ax in axes: for xmin, xmax in intervals: self.__vspans.append(ax.axvspan(xmin, xmax, *args, **kwargs)) self.draw() def set_xlim(self, left=None, right=None): """Set the x-axis limits for all axes""" if isinstance(self, TimeSlicer) and self._time_controller is not None: if left is None or right is None: ax_left, ax_right = self.__axes[0].get_xlim() if left is None: left = ax_left if right is None: right = ax_right self._time_controller.set_xlim(left, right) else: self._set_xlim(left, right, draw=True) class YLimMixin: """Manage y-axis Parameters ---------- plots : Sequence Plots to manage. Plots must have ``.ax`` attribute. Notes ----- Navigation: - ``↑``: scroll up - ``↓``: scroll down - ``r``: y-axis zoom in (reduce y-axis range) - ``c``: y-axis zoom out (increase y-axis range) """ # Keep Y-lim and V-lim separate. For EEG, one might want to invert the # y-axis without inverting the colormap # What should be the organizing principle for different vlims within # one figure? Use cases: # - 2 axes with different data # - (not implemented) one axis with two y-axes _can_set_ylim = True def __init__(self, plots): self.__plots = plots self._register_key('r', self.__on_zoom_in) self._register_key('c', self.__on_zoom_out) self._register_key('i' if IS_WINDOWS else 'up', self.__on_move_up) self._register_key('k' if IS_WINDOWS else 'down', self.__on_move_down) self._draw_hooks.append(self.__draw_hook) # disable because it changes y-limits # self._untight_draw_hooks.append(self.__untight_draw_hook) def __draw_hook(self): need_draw = False for p in self.__plots: # decimate overlapping ticklabels locs = p.ax.yaxis.get_ticklocs() we = tuple(l.get_window_extent(self.canvas.renderer) for l in p.ax.yaxis.get_ticklabels()) start = 0 step = 1 locs_list = list(locs) if 0 in locs else None while any(e1.ymin < e0.ymax for e0, e1 in intervals(we[start::step])): step += 1 if locs_list: start = locs_list.index(0) % step if step > 1: p.ax.yaxis.set_ticks(locs[start::step]) need_draw = True return need_draw def __untight_draw_hook(self): for p in self.__plots: # remove the top-most y tick-label if it is outside the figure extent = p.ax.yaxis.get_ticklabels()[-1].get_window_extent() if extent.height and extent.y1 > self.figure.get_window_extent().y1: p.ax.set_yticks(p.ax.get_yticks()[:-1]) def get_ylim(self): vmin = min(p.vmin for p in self.__plots) vmax = max(p.vmax for p in self.__plots) return vmin, vmax def set_ylim(self, bottom=None, top=None): """Set the y-axis limits Parameters ---------- bottom : scalar Lower y-axis limit. top : scalar Upper y-axis limit. """ if bottom is None and top is None: return for p in self.__plots: p.set_ylim(bottom, top) self.draw() def __animate(self, vmin, vmin_d, vmax, vmax_d): n_steps = int(0.1 // self._last_draw_time) if n_steps <= 1: self.set_ylim(vmin + vmin_d, vmax + vmax_d) else: for i in range(1, n_steps + 1): x = i / n_steps self.set_ylim(vmin + x * vmin_d, vmax + x * vmax_d) def __on_move_down(self, event): vmin, vmax = self.get_ylim() d = (vmax - vmin) * 0.1 self.__animate(vmin, -d, vmax, -d) def __on_move_up(self, event): vmin, vmax = self.get_ylim() d = (vmax - vmin) * 0.1 self.__animate(vmin, d, vmax, d) def __on_zoom_in(self, event): vmin, vmax = self.get_ylim() d = (vmax - vmin) * 0.05 self.__animate(vmin, d, vmax, -d) def __on_zoom_out(self, event): vmin, vmax = self.get_ylim() d = (vmax - vmin) * (1 / 22) self.__animate(vmin, -d, vmax, d)
import logging import torch from os import path as osp from basicsr.data import create_dataloader, create_dataset from basicsr.models import create_model from basicsr.train import parse_options from basicsr.utils import (get_env_info, get_root_logger, get_time_str, make_exp_dirs) from basicsr.utils.options import dict2str import cv2 import numpy as np import torch from basicsr.models.base_model import BaseModel from basicsr.models.sr_model import SRModel img = cv2.imread('my_images/input/interpolate_0000.png') #img2 = np.expand_dims(img, 0) img2 = np.rollaxis(img, 2, 0) img3 = torch.from_numpy(img2) basis_opt = { 'num_gpu': 0, 'is_train': False } basis_model = BaseModel(basis_opt) sr_opt = {i: j for i, j in basis_opt.items()} sr_opt['dist'] = False sr_opt['network_g'] = { 'type': 'EDSR', 'num_in_ch': 3, 'num_out_ch': 3, 'num_feat': 256, 'num_block': 32, 'upscale': 2, 'res_scale': 0.1, 'img_range': 255., 'rgb_mean': [0.4488, 0.4371, 0.4040] } sr_opt['path'] = { 'pretrain_network_g': 'experiments/pretrained_models/EDSR/EDSR_Lx2_f256b32_DIV2K_official-be38e77d.pth', 'strict_load_g': True } sr_model = SRModel(sr_opt) sr_model.net_g(img3) sr_result = sr_model.net_g(img3) sr_img = sr_result.detach().numpy()[0,:] sr_img = np.rollaxis(sr_img, 0, 3) cv2.imwrite('my_images/sr.png', sr_img) def main(): # parse options, set distributed setting, set ramdom seed opt = parse_options(is_train=False) torch.backends.cudnn.benchmark = True # torch.backends.cudnn.deterministic = True # mkdir and initialize loggers make_exp_dirs(opt) log_file = osp.join(opt['path']['log'], f"test_{opt["name"]}_{get_time_str()}.log") logger = get_root_logger( logger_name='basicsr', log_level=logging.INFO, log_file=log_file) logger.info(get_env_info()) logger.info(dict2str(opt)) # create test dataset and dataloader test_loaders = [] for phase, dataset_opt in sorted(opt['datasets'].items()): test_set = create_dataset(dataset_opt) test_loader = create_dataloader( test_set, dataset_opt, num_gpu=opt['num_gpu'], dist=opt['dist'], sampler=None, seed=opt['manual_seed']) logger.info( f"Number of test images in {dataset_opt["name"]}: {len(test_set)}") test_loaders.append(test_loader) # create model model = create_model(opt) for test_loader in test_loaders: test_set_name = test_loader.dataset.opt['name'] logger.info(f'Testing {test_set_name}...') model.validation( test_loader, current_iter=opt['name'], tb_logger=None, save_img=opt['val']['save_img']) if __name__ == '__main__': main()
import logging import torch from os import path as osp from basicsr.data import create_dataloader, create_dataset from basicsr.models import create_model from basicsr.train import parse_options from basicsr.utils import (get_env_info, get_root_logger, get_time_str, make_exp_dirs) from basicsr.utils.options import dict2str import cv2 import numpy as np import torch from basicsr.models.base_model import BaseModel from basicsr.models.sr_model import SRModel img = cv2.imread('my_images/input/interpolate_0000.png') #img2 = np.expand_dims(img, 0) img2 = np.rollaxis(img, 2, 0) img3 = torch.from_numpy(img2) basis_opt = { 'num_gpu': 0, 'is_train': False } basis_model = BaseModel(basis_opt) sr_opt = {i: j for i, j in basis_opt.items()} sr_opt['dist'] = False sr_opt['network_g'] = { 'type': 'EDSR', 'num_in_ch': 3, 'num_out_ch': 3, 'num_feat': 256, 'num_block': 32, 'upscale': 2, 'res_scale': 0.1, 'img_range': 255., 'rgb_mean': [0.4488, 0.4371, 0.4040] } sr_opt['path'] = { 'pretrain_network_g': 'experiments/pretrained_models/EDSR/EDSR_Lx2_f256b32_DIV2K_official-be38e77d.pth', 'strict_load_g': True } sr_model = SRModel(sr_opt) sr_model.net_g(img3) sr_result = sr_model.net_g(img3) sr_img = sr_result.detach().numpy()[0,:] sr_img = np.rollaxis(sr_img, 0, 3) cv2.imwrite('my_images/sr.png', sr_img) def main(): # parse options, set distributed setting, set ramdom seed opt = parse_options(is_train=False) torch.backends.cudnn.benchmark = True # torch.backends.cudnn.deterministic = True # mkdir and initialize loggers make_exp_dirs(opt) log_file = osp.join(opt['path']['log'], f"test_{opt['name']}_{get_time_str()}.log") logger = get_root_logger( logger_name='basicsr', log_level=logging.INFO, log_file=log_file) logger.info(get_env_info()) logger.info(dict2str(opt)) # create test dataset and dataloader test_loaders = [] for phase, dataset_opt in sorted(opt['datasets'].items()): test_set = create_dataset(dataset_opt) test_loader = create_dataloader( test_set, dataset_opt, num_gpu=opt['num_gpu'], dist=opt['dist'], sampler=None, seed=opt['manual_seed']) logger.info( f"Number of test images in {dataset_opt['name']}: {len(test_set)}") test_loaders.append(test_loader) # create model model = create_model(opt) for test_loader in test_loaders: test_set_name = test_loader.dataset.opt['name'] logger.info(f'Testing {test_set_name}...') model.validation( test_loader, current_iter=opt['name'], tb_logger=None, save_img=opt['val']['save_img']) if __name__ == '__main__': main()
import sys import click from ecrtools.lib.ecr import Ecr from ecrtools.lib.utils import convert_bytes @click.command() @click.argument('repo') @click.argument('image', default='', type=str, required=False) @click.option('-c', '--count', type=int, default=None, help='Number of images to list.') @click.option('-u', '--units', default='MB', type=click.Choice(['B', 'MB', 'GB']), help='Size units.') @click.option('-w', '--exact-match', is_flag=True, help='Exact match.') @click.pass_obj def images(ctx, repo, image, count, units, exact_match): '''List images in a repo''' ecr = Ecr(ctx['ecr'], repo) if image == '': images = ecr.get_all_repo_images() else: image_ids = ecr.get_image_ids(image, exact_match) if not image_ids: sys.exit('No images found.') images = ecr.get_images(image_ids) images = sorted(images, reverse=True, key=lambda k: k['imagePushedAt']) if not images: sys.exit('No images found.') total_size = 0 total_untagged = 0 size_pad = calculate_size_pad(images, units) for i in images[: count]: try: tags = ', '.join(i['imageTags']) except KeyError: tags = '<untagged>' total_untagged += 1 total_size += i['imageSizeInBytes'] size = convert_bytes(i['imageSizeInBytes'], units) click.echo(f'{i['imagePushedAt']} {size['value']:{size_pad}.1f}' f'{size['units']} {tags}') total_size = convert_bytes(total_size, 'GB') click.echo(f'\nimages: {len(images[:count])}' f' untagged: {total_untagged}' f' total size: {total_size['value']:.1f}{total_size['units']}') def calculate_size_pad(images, units): s = max([str(convert_bytes(i['imageSizeInBytes'], units)['value']) for i in images], key=len) s = '{:.1f}'.format(float(s)) return len(f'{str(s)}')
import sys import click from ecrtools.lib.ecr import Ecr from ecrtools.lib.utils import convert_bytes @click.command() @click.argument('repo') @click.argument('image', default='', type=str, required=False) @click.option('-c', '--count', type=int, default=None, help='Number of images to list.') @click.option('-u', '--units', default='MB', type=click.Choice(['B', 'MB', 'GB']), help='Size units.') @click.option('-w', '--exact-match', is_flag=True, help='Exact match.') @click.pass_obj def images(ctx, repo, image, count, units, exact_match): '''List images in a repo''' ecr = Ecr(ctx['ecr'], repo) if image == '': images = ecr.get_all_repo_images() else: image_ids = ecr.get_image_ids(image, exact_match) if not image_ids: sys.exit('No images found.') images = ecr.get_images(image_ids) images = sorted(images, reverse=True, key=lambda k: k['imagePushedAt']) if not images: sys.exit('No images found.') total_size = 0 total_untagged = 0 size_pad = calculate_size_pad(images, units) for i in images[: count]: try: tags = ', '.join(i['imageTags']) except KeyError: tags = '<untagged>' total_untagged += 1 total_size += i['imageSizeInBytes'] size = convert_bytes(i['imageSizeInBytes'], units) click.echo(f'{i["imagePushedAt"]} {size["value"]:{size_pad}.1f}' f'{size["units"]} {tags}') total_size = convert_bytes(total_size, 'GB') click.echo(f'\nimages: {len(images[:count])}' f' untagged: {total_untagged}' f' total size: {total_size["value"]:.1f}{total_size["units"]}') def calculate_size_pad(images, units): s = max([str(convert_bytes(i['imageSizeInBytes'], units)['value']) for i in images], key=len) s = '{:.1f}'.format(float(s)) return len(f'{str(s)}')
# -*- coding: utf-8 -*- ################################################################################ # Form generated from reading UI file 'project changed.ui' # # Created by: Qt User Interface Compiler version 5.15.2 # # WARNING! All changes made in this file will be lost when recompiling UI file! ################################################################################ # ? CHANGED Actions: from original UI file # ? import list, copy functions, connect button <-> functions # ? delete / comment table widget row # ? update LabelPicture.setGeometry (1500, 900) # ? LabelPictureSize # ? update frame.setGeometry # ? self.LabelPicture.mousePressEvent = self.getPos # DRAWING POLYGON # ? self.ButtonEdit.setFont(QFont(u"Arial", 18)) ############################################################################### from PySide2.QtCore import * from PySide2.QtGui import * from PySide2.QtWidgets import * from PySide2 import QtCore, QtGui from PySide2.QtMultimedia import QSound import os import xml.etree.ElementTree as ET # DRAWING POLYGON import numpy as np import cv2 from shapely.geometry import Point, Polygon LabelPictureSize = (1500, 900) ButtonHeight = 40 ClickedDetectSize = 10 class Ui_MainWindow(object): def setupUi(self, MainWindow): if not MainWindow.objectName(): MainWindow.setObjectName(u"MainWindow") MainWindow.resize(1031, 882) font = QFont() font.setFamily(u"Arial") font.setPointSize(12) MainWindow.setFont(font) self.actionOpen = QAction(MainWindow) self.actionOpen.setObjectName(u"actionOpen") self.actionSave = QAction(MainWindow) self.actionSave.setObjectName(u"actionSave") self.centralwidget = QWidget(MainWindow) self.centralwidget.setObjectName(u"centralwidget") self.LabelPicture = QLabel(self.centralwidget) self.LabelPicture.setObjectName(u"LabelPicture") self.LabelPicture.setGeometry(QRect(20, 20, *LabelPictureSize)) self.LabelPicture.mousePressEvent = self.getPos # DRAWING POLYGON self.LabelPicture.mouseMoveEvent = self.mouseMove self.LabelPicture.mouseReleaseEvent = self.mouseRelease self.LabelPicture.setMouseTracking(True) # self.LabelPicture.setScaledContents(True) self.frame = QFrame(self.centralwidget) self.frame.setObjectName(u"frame") self.frame.setGeometry(QRect(1550, 30, 350, 1000)) self.frame.setFrameShape(QFrame.StyledPanel) self.frame.setFrameShadow(QFrame.Raised) self.groupBox_2 = QGroupBox(self.frame) self.groupBox_2.setObjectName(u"groupBox_2") self.groupBox_2.setGeometry(QRect(10, 10, 300, 60)) font_14 = QFont() font_14.setPointSize(14) self.groupBox_2.setFont(font_14) self.label = QLabel(self.groupBox_2) self.label.setObjectName(u"label") self.label.setGeometry(QRect(20, 30, 70, 20)) self.LabelPictureName = QLabel(self.groupBox_2) self.LabelPictureName.setObjectName(u"LabelPictureName") self.LabelPictureName.setGeometry(QRect(100, 30, 180, 20)) self.tableWidget = QTableWidget(self.frame) if (self.tableWidget.columnCount() < 2): self.tableWidget.setColumnCount(2) __qtablewidgetitem = QTableWidgetItem() self.tableWidget.setHorizontalHeaderItem(0, __qtablewidgetitem) __qtablewidgetitem1 = QTableWidgetItem() self.tableWidget.setHorizontalHeaderItem(1, __qtablewidgetitem1) self.tableWidget.setObjectName(u"tableWidget") self.tableWidget.setGeometry(QRect(10, 90, 300, 300)) self.tableWidget.selectionModel().selectionChanged.connect(self.TableSelectionChange) font_Arial18 = QFont() font_Arial18.setFamily(u"Arial") font_Arial18.setPointSize(18) self.groupBox = QGroupBox(self.frame) self.groupBox.setObjectName(u"groupBox") self.groupBox.setGeometry(QRect(40, 500, 240, 300)) # x, y, x_len, y_len self.groupBox.setFont(font_Arial18) # ADD region self.ButtonAddRegion = QPushButton(self.groupBox) self.ButtonAddRegion.setObjectName(u"ButtonAddRegion") self.ButtonAddRegion.setGeometry(QRect(20, 40+(ButtonHeight+10)*0, 200, ButtonHeight)) self.ButtonAddRegion.setFont(font_Arial18) # Edit self.ButtonEdit = QPushButton(self.groupBox) self.ButtonEdit.setObjectName(u"ButtonEdit") self.ButtonEdit.setGeometry(QRect(20, 40+(ButtonHeight+10)*1, 200, ButtonHeight)) self.ButtonEdit.setFont(font_Arial18) # Remove Polygon self.ButtonRemove = QPushButton(self.groupBox) self.ButtonRemove.setObjectName(u"ButtonRemove") self.ButtonRemove.setGeometry(QRect(20, 40+(ButtonHeight+10)*2, 200, ButtonHeight)) self.ButtonRemove.setFont(font_Arial18) # Camera / Pause self.ButtonCamera = QPushButton(self.groupBox) self.ButtonCamera.setObjectName(u"ButtonCamera") self.ButtonCamera.setGeometry(QRect(20, 40+(ButtonHeight+10)*3, 200, ButtonHeight)) self.ButtonCamera.setFont(font_Arial18) # Transformation self.ButtonTransformation = QPushButton(self.groupBox) self.ButtonTransformation.setObjectName(u"ButtonTransformation") self.ButtonTransformation.setGeometry(QRect(20, 40+(ButtonHeight+10)*4, 200, ButtonHeight)) self.ButtonTransformation.setFont(font_Arial18) MainWindow.setCentralWidget(self.centralwidget) self.menubar = QMenuBar(MainWindow) self.menubar.setObjectName(u"menubar") self.menubar.setGeometry(QRect(0, 0, 1031, 21)) self.menuFile = QMenu(self.menubar) self.menuFile.setObjectName(u"menuFile") MainWindow.setMenuBar(self.menubar) self.statusbar = QStatusBar(MainWindow) self.statusbar.setObjectName(u"statusbar") MainWindow.setStatusBar(self.statusbar) self.menubar.addAction(self.menuFile.menuAction()) self.menuFile.addAction(self.actionOpen) self.menuFile.addAction(self.actionSave) self.retranslateUi(MainWindow) QMetaObject.connectSlotsByName(MainWindow) ##### CONNECT funcs & BUTTONs self.actionOpen.triggered.connect(self.BrowseFiles) self.actionSave.triggered.connect(self.SaveFile) self.ButtonAddRegion.clicked.connect(self.AddRegion) self.ButtonEdit.clicked.connect(self.EditPolygon) self.ButtonRemove.clicked.connect(self.DelPolygon) self.ButtonCamera.clicked.connect(self.CameraMode) self.ButtonTransformation.clicked.connect(self.ToTrans) ##### STATUS self.status = None # status: {'edit' | 'add_poly' | 'del_poly' | 'trans' | None} self.map_Button_to_status = { self.ButtonEdit: 'edit', self.ButtonAddRegion: 'add_poly', self.ButtonRemove: 'del_poly', self.ButtonTransformation: 'trans' } # for mouseMoveEvent, status=='edit' and (False -> highlight dots, True -> change self.attribute) self.moving_dot = None self.pixHeight = None # to check whether a image is read self.tracking = False self.semi_color = [ # QtGui.QColor(255, 0, 0, 100), QtGui.QColor(0, 0, 255, 100), QtGui.QColor(0, 255, 0, 100), QtGui.QColor(255, 255, 0, 100), QtGui.QColor(0, 0, 0, 100), QtGui.QColor(255, 128, 0, 100), QtGui.QColor(0, 255, 255, 100), QtGui.QColor(255, 0, 255, 100), QtGui.QColor(128, 128, 128, 100) ] # setupUi def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(QCoreApplication.translate("MainWindow", u"MainWindow", None)) self.actionOpen.setText(QCoreApplication.translate("MainWindow", u"Open", None)) #if QT_CONFIG(shortcut) self.actionOpen.setShortcut(QCoreApplication.translate("MainWindow", u"Ctrl+O", None)) #endif // QT_CONFIG(shortcut) self.actionSave.setText(QCoreApplication.translate("MainWindow", u"Save", None)) #if QT_CONFIG(shortcut) self.actionSave.setShortcut(QCoreApplication.translate("MainWindow", u"Ctrl+S", None)) #endif // QT_CONFIG(shortcut) self.LabelPicture.setText(QCoreApplication.translate("MainWindow", u"Picture Place", None)) self.groupBox_2.setTitle(QCoreApplication.translate("MainWindow", u"Info", None)) self.label.setText(QCoreApplication.translate("MainWindow", u"Picture:", None)) self.LabelPictureName.setText(QCoreApplication.translate("MainWindow", u"picturename.jpg", None)) ___qtablewidgetitem = self.tableWidget.horizontalHeaderItem(0) ___qtablewidgetitem.setText(QCoreApplication.translate("MainWindow", u"Name", None)); ___qtablewidgetitem1 = self.tableWidget.horizontalHeaderItem(1) ___qtablewidgetitem1.setText(QCoreApplication.translate("MainWindow", u"Attribute", None)); self.groupBox.setTitle(QCoreApplication.translate("MainWindow", u"Functions", None)) self.ButtonAddRegion.setText(QCoreApplication.translate("MainWindow", u"ADD region", None)) #if QT_CONFIG(shortcut) self.ButtonAddRegion.setShortcut(QCoreApplication.translate("MainWindow", u"Ctrl+N", None)) #endif // QT_CONFIG(shortcut) self.ButtonEdit.setText(QCoreApplication.translate("MainWindow", u"Edit", None)) self.ButtonCamera.setText(QCoreApplication.translate("MainWindow", u"Camera / Pause", None)) self.ButtonTransformation.setText(QCoreApplication.translate("MainWindow", u"Transformation", None)) #remove polygon self.ButtonRemove.setText(QCoreApplication.translate("MainWindow", u"Remove Polygon", None)) self.menuFile.setTitle(QCoreApplication.translate("MainWindow", u"File", None)) # retranslateUi # connect to --> self.actionOpen def BrowseFiles(self): if self.status is not None: self.ShowErrorToStatusbar(f'[ERROR] Try to open file when Button(s) are still active: [{self.status}]') return filename = QFileDialog.getOpenFileName(self.centralwidget, 'Open file', os.getcwd(), 'Image files (*.jpg *.png)') # filename: (filepath: str, image type(same as I write): str) # ? Find Picutre if not filename[0]: self.ShowErrorToStatusbar('[ERROR] No picture file select') return print(filename[0]) self.full_pic_path = filename[0] self.LabelPictureName.setText(self.full_pic_path.split('/')[-1]) self.RemoveAllRows() pixmap = QPixmap(self.full_pic_path) pixmap = pixmap.scaled(*LabelPictureSize, Qt.KeepAspectRatio) # SCALING METHOD # 300: 最大寬度, 1000: 最大高度 -> LabelPictureSize print('Pixmap W, H:', pixmap.width(), pixmap.height()) # 顯示出的實際圖片大小 self.LabelPicture.setPixmap(pixmap) self.pixHeight = self.LabelPicture.pixmap().height() # DRAWING POLYGON self.for_delete = pixmap self.image = cv2.imread(self.full_pic_path) self.resize = self.image.shape[1] / pixmap.width() self.attribute = [] self.color_index = [] self.matrix_pix_to_cm = None print(self.image.shape[:2]) # Find XML file self.full_xml_path = self.full_pic_path.rsplit('.')[0] + '.xml' if os.path.isfile(self.full_xml_path): # load data print(f'Find corresponding .xml file for {self.full_pic_path}') self.OpenXmlFile() def OpenXmlFile(self): tree = ET.parse(self.full_xml_path) root = tree.getroot() # fetch data from xml to table for obj in root.iter('object'): # get data name = obj.find('name').text attribute = obj.find('attribute').text print(f'get obj name: {name}') row = self.tableWidget.rowCount() self.tableWidget.setRowCount(row + 1) # Build empty row __qtablewidgetitem0 = QTableWidgetItem() self.tableWidget.setVerticalHeaderItem(row, __qtablewidgetitem0) __qtablewidgetitem1 = QTableWidgetItem(name) self.tableWidget.setItem(row, 0, __qtablewidgetitem1) __qtablewidgetitem2 = QTableWidgetItem(attribute) self.tableWidget.setItem(row, 1, __qtablewidgetitem2) # DRAW POLYGON polygon_pos_list = [] polygon = obj.find('polygon') for pt in polygon.iter('pt'): x = float(pt.find('x').text) / self.resize y = float(pt.find('y').text) / self.resize polygon_pos_list += [[x, y]] # print(f'get points: (x, y) = ({x}, {y})') self.attribute.append(polygon_pos_list) # DRAW POLYGON FUNCTION(polygon_pos_list) for i in range(len(self.attribute)): self.polygon(self.attribute[i], 2, None) self.for_tracking_pixmap = QPixmap(self.LabelPicture.pixmap()) def RemoveAllRows(self): for i in range(self.tableWidget.rowCount()-1, -1, -1): self.tableWidget.removeRow(i) # connect to --> ButtonAddRegion def AddRegion(self): if self.pixHeight is None: # don't read a file self.ShowErrorToStatusbar(f'[ERROR] not read a picture yet but clicked [Add Polygon]') return if self.status is None: self.set_status(self.ButtonAddRegion, True) self.fun() # DRAWING POLYGON # AfterPolygon() should be CALL by the last operation in drawing polygon else: self.ShowErrorToStatusbar(f'[ERROR] try to set status [add_poly] on while status [{self.status}] on') def AfterPolygon(self): name, okPressed = QInputDialog.getText(self.centralwidget, "Get Name", "Your name:", QLineEdit.Normal, "") if okPressed and name != '': print(name) attr, okPressed = QInputDialog.getText(self.centralwidget, "Get Attr", "Your attribute:", QLineEdit.Normal, "") if okPressed and attr != '': print(attr) self.add_row((name, attr)) def add_row(self, content=None): row = self.tableWidget.rowCount() # print(f'add row: {row}') self.tableWidget.setRowCount(row + 1) # Build empty row __qtablewidgetitem3 = QTableWidgetItem() self.tableWidget.setVerticalHeaderItem(row, __qtablewidgetitem3) if content is not None: __qtablewidgetitem4 = QTableWidgetItem(content[0]) self.tableWidget.setItem(row, 0, __qtablewidgetitem4) __qtablewidgetitem5 = QTableWidgetItem(content[1]) self.tableWidget.setItem(row, 1, __qtablewidgetitem5) else: __qtablewidgetitem4 = QTableWidgetItem(u"edit...") # __qtablewidgetitem4.setText(QCoreApplication.translate("MainWindow", u"edit..", None)); self.tableWidget.setItem(row, 0, __qtablewidgetitem4) __qtablewidgetitem5 = QTableWidgetItem(u"edit...") # __qtablewidgetitem5.setText(QCoreApplication.translate("MainWindow", u"edit...", None)); self.tableWidget.setItem(row, 1, __qtablewidgetitem5) # edit content method # ___qtablewidgetitem2 = self.tableWidget.item(0, 0) # ___qtablewidgetitem2.setText(QCoreApplication.translate("MainWindow", u"1231321", None)); # ___qtablewidgetitem3 = self.tableWidget.item(0, 1) # ___qtablewidgetitem3.setText(QCoreApplication.translate("MainWindow", u"1231321333333", None)); # tableWidget (de)select event def TableSelectionChange(self, selected, deselected): if self.status not in [None, 'del_poly']: return if self.tableWidget.rowCount() == 0: return if self.status == None: deselected_row = [ind.row() for ind in deselected.indexes()] # deselect if deselected_row: self.ReDraw(update_for_tracking_pixmap=False) # if self.selected_row is not None and self.selected_row in deselected_row: # self.selected_row = None # self.ReDraw(update_for_tracking_pixmap=False) # select if len(selected.indexes()) > 0: selected_row = selected.indexes()[0].row() self.ReDraw(update_for_tracking_pixmap=False) self.polygon(self.attribute[selected_row], 3, self.color_index[selected_row]) elif self.status == 'del_poly': if len(selected.indexes()) > 0: self.TryDeletePolygon(selected.indexes()[0].row()) # print(f'+{self.selected_row} - {deselected_row}') # connect to --> self.actionSave def SaveFile(self): if self.pixHeight is None: # don't read a file self.ShowErrorToStatusbar(f'[ERROR] not read a picture yet but clicked [File > Save]') return if self.status is not None: self.ShowErrorToStatusbar(f'[ERROR] Try to save file when Button(s) are still active: [{self.status}]') return # save data to pic_name.xml root = ET.Element('annotation') filename = ET.SubElement(root, 'filename') filename.text = self.full_pic_path.split('/')[-1] for i in range(self.tableWidget.rowCount()): object = ET.SubElement(root, 'object') name = ET.SubElement(object, 'name') name.text = self.tableWidget.item(i, 0).text() attribute = ET.SubElement(object, 'attribute') attribute.text = self.tableWidget.item(i, 1).text() polygon = ET.SubElement(object, 'polygon') # print('Attr:', self.attribute) for pos_x, pos_y in self.attribute[i]: # 第 i 個 row (polygon) pt = ET.SubElement(polygon, 'pt') x = ET.SubElement(pt, 'x') x.text = str(pos_x * self.resize) y = ET.SubElement(pt, 'y') y.text = str(pos_y * self.resize) tree = ET.ElementTree(root) tree.write(self.full_xml_path, encoding="utf-8") print(f'save data to: [{self.full_xml_path}]') if self.matrix_pix_to_cm is not None: np.save(self.full_pic_path.rsplit('.')[0] + '.npy', self.matrix_pix_to_cm) print(f'save transfrom matrix to: [{self.full_pic_path.rsplit('.')[0] + '.npy'}]') # connect to --> self.ButtonEdit def EditPolygon(self): if self.pixHeight is None: # don't read a file self.ShowErrorToStatusbar(f'[ERROR] not read a picture yet but clicked [Edit]') return if self.status == 'edit': self.set_status(self.ButtonEdit, False) elif self.status is None: self.set_status(self.ButtonEdit, True) else: self.ShowErrorToStatusbar(f'[ERROR] try to set status [edit] on while status [{self.status}] on') # connect to --> self.ButtonCamera def CameraMode(self): pass # connect to --> self.ButtonTransformation def ToTrans(self): if self.pixHeight is None: # don't read a file self.ShowErrorToStatusbar(f'[ERROR] not read a picture yet but clicked [Transformation]') return if self.status == 'trans': return elif self.status is not None and self.status != 'edit': # 唯一可以跳過去 trans 的狀態就是 'edit' self.ShowErrorToStatusbar(f'[ERROR] try to set status [trans] on while status [{self.status}] on') return status_edit = self.status # None or 'edit' idx = -1 for i in range(self.tableWidget.rowCount()): if self.tableWidget.item(i, 0).text() == 'TRANS': idx = i break if idx == -1: # not found self.ShowErrorToStatusbar('[ERROR] polygon with name [TRANS] not found') return # status is None AND found a polygon self.set_status(self.ButtonTransformation, True) # position text parser attr_text = self.tableWidget.item(idx, 1).text() attr = [e.strip('[](){} ') for e in attr_text.split(',')] # 先用 ',' 作分隔,再去除左右邊的括弧空格 '[](){} ' src = np.array(self.attribute[i], np.float32) * self.resize src = src.reshape(-1, 2) attr = np.float32(attr).reshape((4, 2)) # calculate the matrix for real world, we will not use it! # self.SaveFile() self.matrix_pix_to_cm = cv2.getPerspectiveTransform(src, attr) # calculte the ratio of pixel/cm ratio = 0 for i in range(0, 3): ratio = ratio + self.size(src[i][0], src[i+1][0], src[i][1], src[i+1][1], attr[i][0], attr[i+1][0], attr[i][1], attr[i+1][1]) ratio = ratio + self.size(src[0][0], src[3][0], src[0][1], src[3][1], attr[0][0], attr[3][0], attr[0][1], attr[3][1]) ratio /= 4 # compute matrix for pixel to pixel attr = attr * ratio # change cm to pixel in the image matrix = cv2.getPerspectiveTransform(src, attr) ww = self.image.shape[1] hh = self.image.shape[0] width, height, shift_x, shift_y = self.shift(src, matrix) # move the selected region to the center, and avoid some part of image be cut off for i in range(0, 4): attr[i][0] = attr[i][0] - shift_x + 100 attr[i][1] = attr[i][1] - shift_y + 100 matrix = cv2.getPerspectiveTransform(src, attr) result = cv2.warpPerspective( self.image, matrix, (int(width), int(height)), cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT, borderValue=(0, 0, 0) ) # show the result fx = 1200 / int(width) fy = 800 / int(height) f = min(fx, fy) print(int(width)*f, int(height)*f) resized = cv2.resize(result, None, fx=f, fy=f, interpolation=cv2.INTER_AREA) attr *= f p = attr.astype(int) cv2.line(resized, tuple(p[0]), tuple(p[1]), (255, 0, 0), 3) cv2.line(resized, tuple(p[1]), tuple(p[2]), (255, 0, 0), 3) cv2.line(resized, tuple(p[2]), tuple(p[3]), (255, 0, 0), 3) cv2.line(resized, tuple(p[3]), tuple(p[0]), (255, 0, 0), 3) cv2.imshow('transform', resized) cv2.moveWindow('transform', 200, 200) cv2.waitKey(0) self.set_status(self.ButtonTransformation, False) if status_edit == 'edit': self.set_status(self.ButtonEdit, True) # connect to --> self.ButtonRemove def DelPolygon(self): if self.pixHeight is None: # don't read a file self.ShowErrorToStatusbar(f'[ERROR] not read a picture yet but clicked [Remove]') return if self.status == 'del_poly': self.set_status(self.ButtonRemove, False) elif self.status is None: self.set_status(self.ButtonRemove, True) else: self.ShowErrorToStatusbar(f'[ERROR] try to set status [del_poly] on while status [{self.status}] on') def TryDeletePolygon(self, idx): ''' Highlight polygon idx MessageBox to double check ''' # TODO Highlight polygon i self.polygon(self.attribute[idx], 3, self.color_index[idx]) reply = QMessageBox.question(self.centralwidget, "刪除", "刪除這個多邊形?", QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) if reply == QMessageBox.Yes: # print('reply Yes') del self.attribute[idx] del self.color_index[idx] self.tableWidget.removeRow(idx) # Remove table[idx] # self.ReDraw(update_for_tracking_pixmap=True) # set_status 裡面就會做一次了 self.set_status(self.ButtonRemove, False) elif reply == QMessageBox.No: # 把全部都重畫 self.ReDraw(update_for_tracking_pixmap=False) def set_status(self, button, onoff): # ! daugerous, direct change status no matter what status is if onoff: self.status = self.map_Button_to_status[button] button.setStyleSheet('QPushButton {background-color: cyan;}') else: self.status = None button.setStyleSheet('QPushButton {background-color: None;}') # 換狀態順便重畫一次 self.tableWidget.clearSelection() # ! REDRAW self.ReDraw(update_for_tracking_pixmap=True) # self.LabelPicture.setPixmap(self.for_delete) # for i, poly in enumerate(self.attribute): # self.polygon(poly, 1, self.color_index[i]) def ShowErrorToStatusbar(self, text): print(text) self.statusbar.showMessage(text, 3000) # ---------------------------------------------------------------- DRAWING POLYGON # mouseMoveEvent def mouseMove(self, event): if not self.LabelPicture.pixmap(): return # map pixel on LabelPicture to pixel on image file x = event.pos().x() # real x point on the image y = event.pos().y() - 450 + self.pixHeight / 2 # self.attribute: [polygons], polygon: [points], point: [x, y] if self.status == 'edit': if self.moving_dot: # plot after editing i, j = self.moving_dot self.attribute[i][j][0] = x self.attribute[i][j][1] = y # ! REDRAW self.LabelPicture.setPixmap(self.for_editing_pixmap) self.polygon(self.attribute[i], 1, self.color_index[i]) # polygon() will copy another pixmap # self.ReDraw(update_for_tracking_pixmap=True) # for i, poly in enumerate(self.attribute): # self.polygon(poly, 1, self.color_index[i]) else: # plot before editing # ! REDRAW self.ReDraw(update_for_tracking_pixmap=False) # self.LabelPicture.setPixmap(self.for_delete) # for i, poly in enumerate(self.attribute): # self.polygon(poly, 1, self.color_index[i]) for i, poly in enumerate(self.attribute): for j, point in enumerate(poly): p_x, p_y = point if abs(p_x-x) < ClickedDetectSize and abs(p_y-y) < ClickedDetectSize: # highlight this point: self.attribute[i][j] self.draw_point(p_x, p_y, ClickedDetectSize) elif self.status == 'add_poly': if self.tracking: self.pos_x = event.pos().x() self.pos_y = event.pos().y() - 450 + self.pixHeight/2 self.Draw() else: pass # mousePressEvent def mouseRelease(self, event): # self.pos_x, self.pos_y = event.pos().x(), event.pos().y() - 450 + pixHeight/2 if self.status == 'edit': self.LabelPicture.setMouseTracking(True) self.ReDraw(update_for_tracking_pixmap=True) self.moving_dot = None # mousePressEvent def getPos(self, event): if self.pixHeight is None: self.ShowErrorToStatusbar(f'[ERROR] not read a picture yet but clicked [Label region]') return # real pixmap height x = event.pos().x() # real x point on the image y = event.pos().y() - 450 + self.pixHeight / 2 if self.status == 'add_poly': if len(self.tmp) == 0: self.start_x = x self.start_y = y self.tracking = True # 第二個點不能點回第一個點 if len(self.tmp)==2 and \ abs(x-self.start_x) < ClickedDetectSize and\ abs(y-self.start_y) < ClickedDetectSize: self.tmp = [] self.tmp.append([x, y]) self.PreviousPair = (x, y) # 刪掉不小心點兩下的點 if len(self.tmp) >=2 and \ abs(x-self.tmp[-2][0]) < 3 and\ abs(y-self.tmp[-2][1]) < 3: del self.tmp[-1] # 一定要三個點以上才能組成多邊形 if len(self.tmp) > 2 and \ abs(x-self.start_x) < ClickedDetectSize and\ abs(y-self.start_y) < ClickedDetectSize: self.tracking = False del self.tmp[-1] print(self.tmp) self.attribute.append(self.tmp) self.ReDraw(update_for_tracking_pixmap=True) self.AfterPolygon() # add name and attribute on the table self.set_status(self.ButtonAddRegion, False) # LabelPic 的座標(1500, 900) # print(f'original x: {event.pos().x()}, y: {event.pos().y()}') # print(f' Move to ({event.pos().x()}, {(event.pos().y() - 450 + pixHeight/2)})') # print(f' Pix On Pic ({x}, {y})') # OK # choose which polygon has to be deleted -> after DelPolygon(self) elif self.status == 'del_poly': p = Point(x, y) idx = -1 for i in range(len(self.attribute)): if p.within(Polygon(self.attribute[i])) == True: idx = i break if idx != -1: self.TryDeletePolygon(idx) elif self.status == 'edit': for i, poly in enumerate(self.attribute): for j, point in enumerate(poly): p_x, p_y = point if abs(p_x-x) < ClickedDetectSize and abs(p_y-y) < ClickedDetectSize: # highlight this point: self.attribute[i][j] # self.draw(p_x, p_y, 20 / self.resize) self.moving_dot = (i, j) self.ReDraw(False, except_row=i) # update_for_tracking_pixmap not important here # print(f'Edit polygon [{i}]') break elif self.status == None: # Highlight corresponding table row p = Point(x, y) idx = -1 for i in range(len(self.attribute)): if p.within(Polygon(self.attribute[i])) == True: idx = i break if idx != -1: self.tableWidget.selectRow(idx) else: self.selected_row = None self.tableWidget.clearSelection() # ! REDRAW self.ReDraw(update_for_tracking_pixmap=False) # self.LabelPicture.setPixmap(self.for_delete) # for i, poly in enumerate(self.attribute): # self.polygon(poly, 1, self.color_index[i]) # ---------------------------------------------------------------- def draw_point(self, x, y, pen_size=5): pixmap = QPixmap(self.LabelPicture.pixmap()) qp = QPainter(pixmap) pen = QPen(Qt.black, pen_size) qp.setPen(pen) qp.drawPoint(x, y) qp.end() self.LabelPicture.setPixmap(pixmap) def polygon(self, tmp, load, idx): p = [] for qpoint in tmp: x = qpoint[0] y = qpoint[1] p.append(QtCore.QPoint(x, y)) pixmap = QtGui.QPixmap(self.LabelPicture.pixmap()) qp = QtGui.QPainter(pixmap) pen = QtGui.QPen(Qt.black, 3) qp.setPen(pen) # for new polygon if load == 0: qp.setBrush(self.semi_color[self.index]) # for delete polygon elif load == 1: qp.setBrush(self.semi_color[idx]) # for load old polygon elif load == 2: c = np.random.randint(len(self.semi_color)) # [0, 7] qp.setBrush(self.semi_color[c]) self.color_index.append(c) # for highlight the polygon elif load == 3: # qp.setBrush(self.semi_color[idx].darker(int=1000000)) qp.setBrush(QtGui.QColor(255, 0, 0, 200)) qp.drawPolygon(p) qp.end() self.LabelPicture.setPixmap(pixmap) def fun(self): self.number = 0 self.tmp = [] # random choose a color self.index = np.random.randint(len(self.semi_color)) # [0, 7] self.color_index.append(self.index) self.for_tracking_pixmap = QtGui.QPixmap(self.LabelPicture.pixmap()) # ---- for transfrom ---- def distance(self, a1, a2, a3, a4): # sqrt(x*x + y*y) length = round(np.linalg.norm([a1-a2, a3-a4])) return length def size(self, a1, a2, a3, a4, b1, b2, b3, b4): return self.distance(a1, a2, a3, a4)/self.distance(b1, b2, b3, b4) def cal_point(self, x, y, m): dst_x = (m[0][0]*x+m[0][1]*y+m[0][2])/(m[2][0]*x+m[2][1]*y+m[2][2]) dst_y = (m[1][0]*x+m[1][1]*y+m[1][2])/(m[2][0]*x+m[2][1]*y+m[2][2]) return dst_x, dst_y def shift(self, pts, m): p1_x, p1_y = self.cal_point(pts[0][0], pts[0][1], m) p2_x, p2_y = self.cal_point(pts[1][0], pts[1][1], m) p3_x, p3_y = self.cal_point(pts[2][0], pts[2][1], m) p4_x, p4_y = self.cal_point(pts[3][0], pts[3][1], m) x = [p1_x, p2_x, p3_x, p4_x] y = [p1_y, p2_y, p3_y, p4_y] shift_x = min(x) shift_y = min(y) width = max(x) - min(x) + 200 height = max(y) - min(y) + 200 return width, height, shift_x, shift_y # ---- for transfrom ---- def Draw(self): # for mouseMove, 'add_poly', tracing # self.empty_pixmap = QPixmap(self.for_tracking_pixmap) # self.LabelPicture.setPixmap(self.empty_pixmap) # pixmap = QPixmap(self.LabelPicture.pixmap()) pixmap = QPixmap(self.for_tracking_pixmap) painter = QPainter(pixmap) painter.setPen(QPen(Qt.black, 2, Qt.SolidLine)) if self.PreviousPair: painter.drawLine(*self.PreviousPair, self.pos_x, self.pos_y) # Draw Dots if len(self.tmp) >= 1: prev = self.tmp[0] if abs(self.pos_x-prev[0]) < ClickedDetectSize and \ abs(self.pos_y-prev[1]) < ClickedDetectSize: painter.setPen(QPen(Qt.black, ClickedDetectSize)) painter.drawPoint(prev[0], prev[1]) painter.setPen(QPen(Qt.black, 5)) for pair in self.tmp: painter.drawPoint(*pair) # Draw old lines if len(self.tmp) >= 2: painter.setPen(QPen(Qt.black, 2)) previous_pair = self.tmp[0] for pair in self.tmp[1: ]: painter.drawLine(*previous_pair, *pair) previous_pair = pair painter.end() self.LabelPicture.setPixmap(pixmap) def ReDraw(self, update_for_tracking_pixmap, except_row=None): # except_row == None -> for tracking pixmap if except_row is None: if update_for_tracking_pixmap: self.LabelPicture.setPixmap(self.for_delete) for i, poly in enumerate(self.attribute): self.polygon(poly, 1, self.color_index[i]) self.for_tracking_pixmap = QPixmap(self.LabelPicture.pixmap()) else: self.LabelPicture.setPixmap(self.for_tracking_pixmap) # except_row != None -> for editing pixmap else: self.LabelPicture.setPixmap(self.for_delete) for i, poly in enumerate(self.attribute): if i == except_row: continue self.polygon(poly, 1, self.color_index[i]) self.for_editing_pixmap = QPixmap(self.LabelPicture.pixmap()) # 取得需要的 pixmap 之後,再把圖畫完整( 避免剛點下去的瞬間少一個多邊形 ) self.polygon(self.attribute[except_row], 1, self.color_index[except_row])
# -*- coding: utf-8 -*- ################################################################################ # Form generated from reading UI file 'project changed.ui' # # Created by: Qt User Interface Compiler version 5.15.2 # # WARNING! All changes made in this file will be lost when recompiling UI file! ################################################################################ # ? CHANGED Actions: from original UI file # ? import list, copy functions, connect button <-> functions # ? delete / comment table widget row # ? update LabelPicture.setGeometry (1500, 900) # ? LabelPictureSize # ? update frame.setGeometry # ? self.LabelPicture.mousePressEvent = self.getPos # DRAWING POLYGON # ? self.ButtonEdit.setFont(QFont(u"Arial", 18)) ############################################################################### from PySide2.QtCore import * from PySide2.QtGui import * from PySide2.QtWidgets import * from PySide2 import QtCore, QtGui from PySide2.QtMultimedia import QSound import os import xml.etree.ElementTree as ET # DRAWING POLYGON import numpy as np import cv2 from shapely.geometry import Point, Polygon LabelPictureSize = (1500, 900) ButtonHeight = 40 ClickedDetectSize = 10 class Ui_MainWindow(object): def setupUi(self, MainWindow): if not MainWindow.objectName(): MainWindow.setObjectName(u"MainWindow") MainWindow.resize(1031, 882) font = QFont() font.setFamily(u"Arial") font.setPointSize(12) MainWindow.setFont(font) self.actionOpen = QAction(MainWindow) self.actionOpen.setObjectName(u"actionOpen") self.actionSave = QAction(MainWindow) self.actionSave.setObjectName(u"actionSave") self.centralwidget = QWidget(MainWindow) self.centralwidget.setObjectName(u"centralwidget") self.LabelPicture = QLabel(self.centralwidget) self.LabelPicture.setObjectName(u"LabelPicture") self.LabelPicture.setGeometry(QRect(20, 20, *LabelPictureSize)) self.LabelPicture.mousePressEvent = self.getPos # DRAWING POLYGON self.LabelPicture.mouseMoveEvent = self.mouseMove self.LabelPicture.mouseReleaseEvent = self.mouseRelease self.LabelPicture.setMouseTracking(True) # self.LabelPicture.setScaledContents(True) self.frame = QFrame(self.centralwidget) self.frame.setObjectName(u"frame") self.frame.setGeometry(QRect(1550, 30, 350, 1000)) self.frame.setFrameShape(QFrame.StyledPanel) self.frame.setFrameShadow(QFrame.Raised) self.groupBox_2 = QGroupBox(self.frame) self.groupBox_2.setObjectName(u"groupBox_2") self.groupBox_2.setGeometry(QRect(10, 10, 300, 60)) font_14 = QFont() font_14.setPointSize(14) self.groupBox_2.setFont(font_14) self.label = QLabel(self.groupBox_2) self.label.setObjectName(u"label") self.label.setGeometry(QRect(20, 30, 70, 20)) self.LabelPictureName = QLabel(self.groupBox_2) self.LabelPictureName.setObjectName(u"LabelPictureName") self.LabelPictureName.setGeometry(QRect(100, 30, 180, 20)) self.tableWidget = QTableWidget(self.frame) if (self.tableWidget.columnCount() < 2): self.tableWidget.setColumnCount(2) __qtablewidgetitem = QTableWidgetItem() self.tableWidget.setHorizontalHeaderItem(0, __qtablewidgetitem) __qtablewidgetitem1 = QTableWidgetItem() self.tableWidget.setHorizontalHeaderItem(1, __qtablewidgetitem1) self.tableWidget.setObjectName(u"tableWidget") self.tableWidget.setGeometry(QRect(10, 90, 300, 300)) self.tableWidget.selectionModel().selectionChanged.connect(self.TableSelectionChange) font_Arial18 = QFont() font_Arial18.setFamily(u"Arial") font_Arial18.setPointSize(18) self.groupBox = QGroupBox(self.frame) self.groupBox.setObjectName(u"groupBox") self.groupBox.setGeometry(QRect(40, 500, 240, 300)) # x, y, x_len, y_len self.groupBox.setFont(font_Arial18) # ADD region self.ButtonAddRegion = QPushButton(self.groupBox) self.ButtonAddRegion.setObjectName(u"ButtonAddRegion") self.ButtonAddRegion.setGeometry(QRect(20, 40+(ButtonHeight+10)*0, 200, ButtonHeight)) self.ButtonAddRegion.setFont(font_Arial18) # Edit self.ButtonEdit = QPushButton(self.groupBox) self.ButtonEdit.setObjectName(u"ButtonEdit") self.ButtonEdit.setGeometry(QRect(20, 40+(ButtonHeight+10)*1, 200, ButtonHeight)) self.ButtonEdit.setFont(font_Arial18) # Remove Polygon self.ButtonRemove = QPushButton(self.groupBox) self.ButtonRemove.setObjectName(u"ButtonRemove") self.ButtonRemove.setGeometry(QRect(20, 40+(ButtonHeight+10)*2, 200, ButtonHeight)) self.ButtonRemove.setFont(font_Arial18) # Camera / Pause self.ButtonCamera = QPushButton(self.groupBox) self.ButtonCamera.setObjectName(u"ButtonCamera") self.ButtonCamera.setGeometry(QRect(20, 40+(ButtonHeight+10)*3, 200, ButtonHeight)) self.ButtonCamera.setFont(font_Arial18) # Transformation self.ButtonTransformation = QPushButton(self.groupBox) self.ButtonTransformation.setObjectName(u"ButtonTransformation") self.ButtonTransformation.setGeometry(QRect(20, 40+(ButtonHeight+10)*4, 200, ButtonHeight)) self.ButtonTransformation.setFont(font_Arial18) MainWindow.setCentralWidget(self.centralwidget) self.menubar = QMenuBar(MainWindow) self.menubar.setObjectName(u"menubar") self.menubar.setGeometry(QRect(0, 0, 1031, 21)) self.menuFile = QMenu(self.menubar) self.menuFile.setObjectName(u"menuFile") MainWindow.setMenuBar(self.menubar) self.statusbar = QStatusBar(MainWindow) self.statusbar.setObjectName(u"statusbar") MainWindow.setStatusBar(self.statusbar) self.menubar.addAction(self.menuFile.menuAction()) self.menuFile.addAction(self.actionOpen) self.menuFile.addAction(self.actionSave) self.retranslateUi(MainWindow) QMetaObject.connectSlotsByName(MainWindow) ##### CONNECT funcs & BUTTONs self.actionOpen.triggered.connect(self.BrowseFiles) self.actionSave.triggered.connect(self.SaveFile) self.ButtonAddRegion.clicked.connect(self.AddRegion) self.ButtonEdit.clicked.connect(self.EditPolygon) self.ButtonRemove.clicked.connect(self.DelPolygon) self.ButtonCamera.clicked.connect(self.CameraMode) self.ButtonTransformation.clicked.connect(self.ToTrans) ##### STATUS self.status = None # status: {'edit' | 'add_poly' | 'del_poly' | 'trans' | None} self.map_Button_to_status = { self.ButtonEdit: 'edit', self.ButtonAddRegion: 'add_poly', self.ButtonRemove: 'del_poly', self.ButtonTransformation: 'trans' } # for mouseMoveEvent, status=='edit' and (False -> highlight dots, True -> change self.attribute) self.moving_dot = None self.pixHeight = None # to check whether a image is read self.tracking = False self.semi_color = [ # QtGui.QColor(255, 0, 0, 100), QtGui.QColor(0, 0, 255, 100), QtGui.QColor(0, 255, 0, 100), QtGui.QColor(255, 255, 0, 100), QtGui.QColor(0, 0, 0, 100), QtGui.QColor(255, 128, 0, 100), QtGui.QColor(0, 255, 255, 100), QtGui.QColor(255, 0, 255, 100), QtGui.QColor(128, 128, 128, 100) ] # setupUi def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(QCoreApplication.translate("MainWindow", u"MainWindow", None)) self.actionOpen.setText(QCoreApplication.translate("MainWindow", u"Open", None)) #if QT_CONFIG(shortcut) self.actionOpen.setShortcut(QCoreApplication.translate("MainWindow", u"Ctrl+O", None)) #endif // QT_CONFIG(shortcut) self.actionSave.setText(QCoreApplication.translate("MainWindow", u"Save", None)) #if QT_CONFIG(shortcut) self.actionSave.setShortcut(QCoreApplication.translate("MainWindow", u"Ctrl+S", None)) #endif // QT_CONFIG(shortcut) self.LabelPicture.setText(QCoreApplication.translate("MainWindow", u"Picture Place", None)) self.groupBox_2.setTitle(QCoreApplication.translate("MainWindow", u"Info", None)) self.label.setText(QCoreApplication.translate("MainWindow", u"Picture:", None)) self.LabelPictureName.setText(QCoreApplication.translate("MainWindow", u"picturename.jpg", None)) ___qtablewidgetitem = self.tableWidget.horizontalHeaderItem(0) ___qtablewidgetitem.setText(QCoreApplication.translate("MainWindow", u"Name", None)); ___qtablewidgetitem1 = self.tableWidget.horizontalHeaderItem(1) ___qtablewidgetitem1.setText(QCoreApplication.translate("MainWindow", u"Attribute", None)); self.groupBox.setTitle(QCoreApplication.translate("MainWindow", u"Functions", None)) self.ButtonAddRegion.setText(QCoreApplication.translate("MainWindow", u"ADD region", None)) #if QT_CONFIG(shortcut) self.ButtonAddRegion.setShortcut(QCoreApplication.translate("MainWindow", u"Ctrl+N", None)) #endif // QT_CONFIG(shortcut) self.ButtonEdit.setText(QCoreApplication.translate("MainWindow", u"Edit", None)) self.ButtonCamera.setText(QCoreApplication.translate("MainWindow", u"Camera / Pause", None)) self.ButtonTransformation.setText(QCoreApplication.translate("MainWindow", u"Transformation", None)) #remove polygon self.ButtonRemove.setText(QCoreApplication.translate("MainWindow", u"Remove Polygon", None)) self.menuFile.setTitle(QCoreApplication.translate("MainWindow", u"File", None)) # retranslateUi # connect to --> self.actionOpen def BrowseFiles(self): if self.status is not None: self.ShowErrorToStatusbar(f'[ERROR] Try to open file when Button(s) are still active: [{self.status}]') return filename = QFileDialog.getOpenFileName(self.centralwidget, 'Open file', os.getcwd(), 'Image files (*.jpg *.png)') # filename: (filepath: str, image type(same as I write): str) # ? Find Picutre if not filename[0]: self.ShowErrorToStatusbar('[ERROR] No picture file select') return print(filename[0]) self.full_pic_path = filename[0] self.LabelPictureName.setText(self.full_pic_path.split('/')[-1]) self.RemoveAllRows() pixmap = QPixmap(self.full_pic_path) pixmap = pixmap.scaled(*LabelPictureSize, Qt.KeepAspectRatio) # SCALING METHOD # 300: 最大寬度, 1000: 最大高度 -> LabelPictureSize print('Pixmap W, H:', pixmap.width(), pixmap.height()) # 顯示出的實際圖片大小 self.LabelPicture.setPixmap(pixmap) self.pixHeight = self.LabelPicture.pixmap().height() # DRAWING POLYGON self.for_delete = pixmap self.image = cv2.imread(self.full_pic_path) self.resize = self.image.shape[1] / pixmap.width() self.attribute = [] self.color_index = [] self.matrix_pix_to_cm = None print(self.image.shape[:2]) # Find XML file self.full_xml_path = self.full_pic_path.rsplit('.')[0] + '.xml' if os.path.isfile(self.full_xml_path): # load data print(f'Find corresponding .xml file for {self.full_pic_path}') self.OpenXmlFile() def OpenXmlFile(self): tree = ET.parse(self.full_xml_path) root = tree.getroot() # fetch data from xml to table for obj in root.iter('object'): # get data name = obj.find('name').text attribute = obj.find('attribute').text print(f'get obj name: {name}') row = self.tableWidget.rowCount() self.tableWidget.setRowCount(row + 1) # Build empty row __qtablewidgetitem0 = QTableWidgetItem() self.tableWidget.setVerticalHeaderItem(row, __qtablewidgetitem0) __qtablewidgetitem1 = QTableWidgetItem(name) self.tableWidget.setItem(row, 0, __qtablewidgetitem1) __qtablewidgetitem2 = QTableWidgetItem(attribute) self.tableWidget.setItem(row, 1, __qtablewidgetitem2) # DRAW POLYGON polygon_pos_list = [] polygon = obj.find('polygon') for pt in polygon.iter('pt'): x = float(pt.find('x').text) / self.resize y = float(pt.find('y').text) / self.resize polygon_pos_list += [[x, y]] # print(f'get points: (x, y) = ({x}, {y})') self.attribute.append(polygon_pos_list) # DRAW POLYGON FUNCTION(polygon_pos_list) for i in range(len(self.attribute)): self.polygon(self.attribute[i], 2, None) self.for_tracking_pixmap = QPixmap(self.LabelPicture.pixmap()) def RemoveAllRows(self): for i in range(self.tableWidget.rowCount()-1, -1, -1): self.tableWidget.removeRow(i) # connect to --> ButtonAddRegion def AddRegion(self): if self.pixHeight is None: # don't read a file self.ShowErrorToStatusbar(f'[ERROR] not read a picture yet but clicked [Add Polygon]') return if self.status is None: self.set_status(self.ButtonAddRegion, True) self.fun() # DRAWING POLYGON # AfterPolygon() should be CALL by the last operation in drawing polygon else: self.ShowErrorToStatusbar(f'[ERROR] try to set status [add_poly] on while status [{self.status}] on') def AfterPolygon(self): name, okPressed = QInputDialog.getText(self.centralwidget, "Get Name", "Your name:", QLineEdit.Normal, "") if okPressed and name != '': print(name) attr, okPressed = QInputDialog.getText(self.centralwidget, "Get Attr", "Your attribute:", QLineEdit.Normal, "") if okPressed and attr != '': print(attr) self.add_row((name, attr)) def add_row(self, content=None): row = self.tableWidget.rowCount() # print(f'add row: {row}') self.tableWidget.setRowCount(row + 1) # Build empty row __qtablewidgetitem3 = QTableWidgetItem() self.tableWidget.setVerticalHeaderItem(row, __qtablewidgetitem3) if content is not None: __qtablewidgetitem4 = QTableWidgetItem(content[0]) self.tableWidget.setItem(row, 0, __qtablewidgetitem4) __qtablewidgetitem5 = QTableWidgetItem(content[1]) self.tableWidget.setItem(row, 1, __qtablewidgetitem5) else: __qtablewidgetitem4 = QTableWidgetItem(u"edit...") # __qtablewidgetitem4.setText(QCoreApplication.translate("MainWindow", u"edit..", None)); self.tableWidget.setItem(row, 0, __qtablewidgetitem4) __qtablewidgetitem5 = QTableWidgetItem(u"edit...") # __qtablewidgetitem5.setText(QCoreApplication.translate("MainWindow", u"edit...", None)); self.tableWidget.setItem(row, 1, __qtablewidgetitem5) # edit content method # ___qtablewidgetitem2 = self.tableWidget.item(0, 0) # ___qtablewidgetitem2.setText(QCoreApplication.translate("MainWindow", u"1231321", None)); # ___qtablewidgetitem3 = self.tableWidget.item(0, 1) # ___qtablewidgetitem3.setText(QCoreApplication.translate("MainWindow", u"1231321333333", None)); # tableWidget (de)select event def TableSelectionChange(self, selected, deselected): if self.status not in [None, 'del_poly']: return if self.tableWidget.rowCount() == 0: return if self.status == None: deselected_row = [ind.row() for ind in deselected.indexes()] # deselect if deselected_row: self.ReDraw(update_for_tracking_pixmap=False) # if self.selected_row is not None and self.selected_row in deselected_row: # self.selected_row = None # self.ReDraw(update_for_tracking_pixmap=False) # select if len(selected.indexes()) > 0: selected_row = selected.indexes()[0].row() self.ReDraw(update_for_tracking_pixmap=False) self.polygon(self.attribute[selected_row], 3, self.color_index[selected_row]) elif self.status == 'del_poly': if len(selected.indexes()) > 0: self.TryDeletePolygon(selected.indexes()[0].row()) # print(f'+{self.selected_row} - {deselected_row}') # connect to --> self.actionSave def SaveFile(self): if self.pixHeight is None: # don't read a file self.ShowErrorToStatusbar(f'[ERROR] not read a picture yet but clicked [File > Save]') return if self.status is not None: self.ShowErrorToStatusbar(f'[ERROR] Try to save file when Button(s) are still active: [{self.status}]') return # save data to pic_name.xml root = ET.Element('annotation') filename = ET.SubElement(root, 'filename') filename.text = self.full_pic_path.split('/')[-1] for i in range(self.tableWidget.rowCount()): object = ET.SubElement(root, 'object') name = ET.SubElement(object, 'name') name.text = self.tableWidget.item(i, 0).text() attribute = ET.SubElement(object, 'attribute') attribute.text = self.tableWidget.item(i, 1).text() polygon = ET.SubElement(object, 'polygon') # print('Attr:', self.attribute) for pos_x, pos_y in self.attribute[i]: # 第 i 個 row (polygon) pt = ET.SubElement(polygon, 'pt') x = ET.SubElement(pt, 'x') x.text = str(pos_x * self.resize) y = ET.SubElement(pt, 'y') y.text = str(pos_y * self.resize) tree = ET.ElementTree(root) tree.write(self.full_xml_path, encoding="utf-8") print(f'save data to: [{self.full_xml_path}]') if self.matrix_pix_to_cm is not None: np.save(self.full_pic_path.rsplit('.')[0] + '.npy', self.matrix_pix_to_cm) print(f'save transfrom matrix to: [{self.full_pic_path.rsplit(".")[0] + ".npy"}]') # connect to --> self.ButtonEdit def EditPolygon(self): if self.pixHeight is None: # don't read a file self.ShowErrorToStatusbar(f'[ERROR] not read a picture yet but clicked [Edit]') return if self.status == 'edit': self.set_status(self.ButtonEdit, False) elif self.status is None: self.set_status(self.ButtonEdit, True) else: self.ShowErrorToStatusbar(f'[ERROR] try to set status [edit] on while status [{self.status}] on') # connect to --> self.ButtonCamera def CameraMode(self): pass # connect to --> self.ButtonTransformation def ToTrans(self): if self.pixHeight is None: # don't read a file self.ShowErrorToStatusbar(f'[ERROR] not read a picture yet but clicked [Transformation]') return if self.status == 'trans': return elif self.status is not None and self.status != 'edit': # 唯一可以跳過去 trans 的狀態就是 'edit' self.ShowErrorToStatusbar(f'[ERROR] try to set status [trans] on while status [{self.status}] on') return status_edit = self.status # None or 'edit' idx = -1 for i in range(self.tableWidget.rowCount()): if self.tableWidget.item(i, 0).text() == 'TRANS': idx = i break if idx == -1: # not found self.ShowErrorToStatusbar('[ERROR] polygon with name [TRANS] not found') return # status is None AND found a polygon self.set_status(self.ButtonTransformation, True) # position text parser attr_text = self.tableWidget.item(idx, 1).text() attr = [e.strip('[](){} ') for e in attr_text.split(',')] # 先用 ',' 作分隔,再去除左右邊的括弧空格 '[](){} ' src = np.array(self.attribute[i], np.float32) * self.resize src = src.reshape(-1, 2) attr = np.float32(attr).reshape((4, 2)) # calculate the matrix for real world, we will not use it! # self.SaveFile() self.matrix_pix_to_cm = cv2.getPerspectiveTransform(src, attr) # calculte the ratio of pixel/cm ratio = 0 for i in range(0, 3): ratio = ratio + self.size(src[i][0], src[i+1][0], src[i][1], src[i+1][1], attr[i][0], attr[i+1][0], attr[i][1], attr[i+1][1]) ratio = ratio + self.size(src[0][0], src[3][0], src[0][1], src[3][1], attr[0][0], attr[3][0], attr[0][1], attr[3][1]) ratio /= 4 # compute matrix for pixel to pixel attr = attr * ratio # change cm to pixel in the image matrix = cv2.getPerspectiveTransform(src, attr) ww = self.image.shape[1] hh = self.image.shape[0] width, height, shift_x, shift_y = self.shift(src, matrix) # move the selected region to the center, and avoid some part of image be cut off for i in range(0, 4): attr[i][0] = attr[i][0] - shift_x + 100 attr[i][1] = attr[i][1] - shift_y + 100 matrix = cv2.getPerspectiveTransform(src, attr) result = cv2.warpPerspective( self.image, matrix, (int(width), int(height)), cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT, borderValue=(0, 0, 0) ) # show the result fx = 1200 / int(width) fy = 800 / int(height) f = min(fx, fy) print(int(width)*f, int(height)*f) resized = cv2.resize(result, None, fx=f, fy=f, interpolation=cv2.INTER_AREA) attr *= f p = attr.astype(int) cv2.line(resized, tuple(p[0]), tuple(p[1]), (255, 0, 0), 3) cv2.line(resized, tuple(p[1]), tuple(p[2]), (255, 0, 0), 3) cv2.line(resized, tuple(p[2]), tuple(p[3]), (255, 0, 0), 3) cv2.line(resized, tuple(p[3]), tuple(p[0]), (255, 0, 0), 3) cv2.imshow('transform', resized) cv2.moveWindow('transform', 200, 200) cv2.waitKey(0) self.set_status(self.ButtonTransformation, False) if status_edit == 'edit': self.set_status(self.ButtonEdit, True) # connect to --> self.ButtonRemove def DelPolygon(self): if self.pixHeight is None: # don't read a file self.ShowErrorToStatusbar(f'[ERROR] not read a picture yet but clicked [Remove]') return if self.status == 'del_poly': self.set_status(self.ButtonRemove, False) elif self.status is None: self.set_status(self.ButtonRemove, True) else: self.ShowErrorToStatusbar(f'[ERROR] try to set status [del_poly] on while status [{self.status}] on') def TryDeletePolygon(self, idx): ''' Highlight polygon idx MessageBox to double check ''' # TODO Highlight polygon i self.polygon(self.attribute[idx], 3, self.color_index[idx]) reply = QMessageBox.question(self.centralwidget, "刪除", "刪除這個多邊形?", QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) if reply == QMessageBox.Yes: # print('reply Yes') del self.attribute[idx] del self.color_index[idx] self.tableWidget.removeRow(idx) # Remove table[idx] # self.ReDraw(update_for_tracking_pixmap=True) # set_status 裡面就會做一次了 self.set_status(self.ButtonRemove, False) elif reply == QMessageBox.No: # 把全部都重畫 self.ReDraw(update_for_tracking_pixmap=False) def set_status(self, button, onoff): # ! daugerous, direct change status no matter what status is if onoff: self.status = self.map_Button_to_status[button] button.setStyleSheet('QPushButton {background-color: cyan;}') else: self.status = None button.setStyleSheet('QPushButton {background-color: None;}') # 換狀態順便重畫一次 self.tableWidget.clearSelection() # ! REDRAW self.ReDraw(update_for_tracking_pixmap=True) # self.LabelPicture.setPixmap(self.for_delete) # for i, poly in enumerate(self.attribute): # self.polygon(poly, 1, self.color_index[i]) def ShowErrorToStatusbar(self, text): print(text) self.statusbar.showMessage(text, 3000) # ---------------------------------------------------------------- DRAWING POLYGON # mouseMoveEvent def mouseMove(self, event): if not self.LabelPicture.pixmap(): return # map pixel on LabelPicture to pixel on image file x = event.pos().x() # real x point on the image y = event.pos().y() - 450 + self.pixHeight / 2 # self.attribute: [polygons], polygon: [points], point: [x, y] if self.status == 'edit': if self.moving_dot: # plot after editing i, j = self.moving_dot self.attribute[i][j][0] = x self.attribute[i][j][1] = y # ! REDRAW self.LabelPicture.setPixmap(self.for_editing_pixmap) self.polygon(self.attribute[i], 1, self.color_index[i]) # polygon() will copy another pixmap # self.ReDraw(update_for_tracking_pixmap=True) # for i, poly in enumerate(self.attribute): # self.polygon(poly, 1, self.color_index[i]) else: # plot before editing # ! REDRAW self.ReDraw(update_for_tracking_pixmap=False) # self.LabelPicture.setPixmap(self.for_delete) # for i, poly in enumerate(self.attribute): # self.polygon(poly, 1, self.color_index[i]) for i, poly in enumerate(self.attribute): for j, point in enumerate(poly): p_x, p_y = point if abs(p_x-x) < ClickedDetectSize and abs(p_y-y) < ClickedDetectSize: # highlight this point: self.attribute[i][j] self.draw_point(p_x, p_y, ClickedDetectSize) elif self.status == 'add_poly': if self.tracking: self.pos_x = event.pos().x() self.pos_y = event.pos().y() - 450 + self.pixHeight/2 self.Draw() else: pass # mousePressEvent def mouseRelease(self, event): # self.pos_x, self.pos_y = event.pos().x(), event.pos().y() - 450 + pixHeight/2 if self.status == 'edit': self.LabelPicture.setMouseTracking(True) self.ReDraw(update_for_tracking_pixmap=True) self.moving_dot = None # mousePressEvent def getPos(self, event): if self.pixHeight is None: self.ShowErrorToStatusbar(f'[ERROR] not read a picture yet but clicked [Label region]') return # real pixmap height x = event.pos().x() # real x point on the image y = event.pos().y() - 450 + self.pixHeight / 2 if self.status == 'add_poly': if len(self.tmp) == 0: self.start_x = x self.start_y = y self.tracking = True # 第二個點不能點回第一個點 if len(self.tmp)==2 and \ abs(x-self.start_x) < ClickedDetectSize and\ abs(y-self.start_y) < ClickedDetectSize: self.tmp = [] self.tmp.append([x, y]) self.PreviousPair = (x, y) # 刪掉不小心點兩下的點 if len(self.tmp) >=2 and \ abs(x-self.tmp[-2][0]) < 3 and\ abs(y-self.tmp[-2][1]) < 3: del self.tmp[-1] # 一定要三個點以上才能組成多邊形 if len(self.tmp) > 2 and \ abs(x-self.start_x) < ClickedDetectSize and\ abs(y-self.start_y) < ClickedDetectSize: self.tracking = False del self.tmp[-1] print(self.tmp) self.attribute.append(self.tmp) self.ReDraw(update_for_tracking_pixmap=True) self.AfterPolygon() # add name and attribute on the table self.set_status(self.ButtonAddRegion, False) # LabelPic 的座標(1500, 900) # print(f'original x: {event.pos().x()}, y: {event.pos().y()}') # print(f' Move to ({event.pos().x()}, {(event.pos().y() - 450 + pixHeight/2)})') # print(f' Pix On Pic ({x}, {y})') # OK # choose which polygon has to be deleted -> after DelPolygon(self) elif self.status == 'del_poly': p = Point(x, y) idx = -1 for i in range(len(self.attribute)): if p.within(Polygon(self.attribute[i])) == True: idx = i break if idx != -1: self.TryDeletePolygon(idx) elif self.status == 'edit': for i, poly in enumerate(self.attribute): for j, point in enumerate(poly): p_x, p_y = point if abs(p_x-x) < ClickedDetectSize and abs(p_y-y) < ClickedDetectSize: # highlight this point: self.attribute[i][j] # self.draw(p_x, p_y, 20 / self.resize) self.moving_dot = (i, j) self.ReDraw(False, except_row=i) # update_for_tracking_pixmap not important here # print(f'Edit polygon [{i}]') break elif self.status == None: # Highlight corresponding table row p = Point(x, y) idx = -1 for i in range(len(self.attribute)): if p.within(Polygon(self.attribute[i])) == True: idx = i break if idx != -1: self.tableWidget.selectRow(idx) else: self.selected_row = None self.tableWidget.clearSelection() # ! REDRAW self.ReDraw(update_for_tracking_pixmap=False) # self.LabelPicture.setPixmap(self.for_delete) # for i, poly in enumerate(self.attribute): # self.polygon(poly, 1, self.color_index[i]) # ---------------------------------------------------------------- def draw_point(self, x, y, pen_size=5): pixmap = QPixmap(self.LabelPicture.pixmap()) qp = QPainter(pixmap) pen = QPen(Qt.black, pen_size) qp.setPen(pen) qp.drawPoint(x, y) qp.end() self.LabelPicture.setPixmap(pixmap) def polygon(self, tmp, load, idx): p = [] for qpoint in tmp: x = qpoint[0] y = qpoint[1] p.append(QtCore.QPoint(x, y)) pixmap = QtGui.QPixmap(self.LabelPicture.pixmap()) qp = QtGui.QPainter(pixmap) pen = QtGui.QPen(Qt.black, 3) qp.setPen(pen) # for new polygon if load == 0: qp.setBrush(self.semi_color[self.index]) # for delete polygon elif load == 1: qp.setBrush(self.semi_color[idx]) # for load old polygon elif load == 2: c = np.random.randint(len(self.semi_color)) # [0, 7] qp.setBrush(self.semi_color[c]) self.color_index.append(c) # for highlight the polygon elif load == 3: # qp.setBrush(self.semi_color[idx].darker(int=1000000)) qp.setBrush(QtGui.QColor(255, 0, 0, 200)) qp.drawPolygon(p) qp.end() self.LabelPicture.setPixmap(pixmap) def fun(self): self.number = 0 self.tmp = [] # random choose a color self.index = np.random.randint(len(self.semi_color)) # [0, 7] self.color_index.append(self.index) self.for_tracking_pixmap = QtGui.QPixmap(self.LabelPicture.pixmap()) # ---- for transfrom ---- def distance(self, a1, a2, a3, a4): # sqrt(x*x + y*y) length = round(np.linalg.norm([a1-a2, a3-a4])) return length def size(self, a1, a2, a3, a4, b1, b2, b3, b4): return self.distance(a1, a2, a3, a4)/self.distance(b1, b2, b3, b4) def cal_point(self, x, y, m): dst_x = (m[0][0]*x+m[0][1]*y+m[0][2])/(m[2][0]*x+m[2][1]*y+m[2][2]) dst_y = (m[1][0]*x+m[1][1]*y+m[1][2])/(m[2][0]*x+m[2][1]*y+m[2][2]) return dst_x, dst_y def shift(self, pts, m): p1_x, p1_y = self.cal_point(pts[0][0], pts[0][1], m) p2_x, p2_y = self.cal_point(pts[1][0], pts[1][1], m) p3_x, p3_y = self.cal_point(pts[2][0], pts[2][1], m) p4_x, p4_y = self.cal_point(pts[3][0], pts[3][1], m) x = [p1_x, p2_x, p3_x, p4_x] y = [p1_y, p2_y, p3_y, p4_y] shift_x = min(x) shift_y = min(y) width = max(x) - min(x) + 200 height = max(y) - min(y) + 200 return width, height, shift_x, shift_y # ---- for transfrom ---- def Draw(self): # for mouseMove, 'add_poly', tracing # self.empty_pixmap = QPixmap(self.for_tracking_pixmap) # self.LabelPicture.setPixmap(self.empty_pixmap) # pixmap = QPixmap(self.LabelPicture.pixmap()) pixmap = QPixmap(self.for_tracking_pixmap) painter = QPainter(pixmap) painter.setPen(QPen(Qt.black, 2, Qt.SolidLine)) if self.PreviousPair: painter.drawLine(*self.PreviousPair, self.pos_x, self.pos_y) # Draw Dots if len(self.tmp) >= 1: prev = self.tmp[0] if abs(self.pos_x-prev[0]) < ClickedDetectSize and \ abs(self.pos_y-prev[1]) < ClickedDetectSize: painter.setPen(QPen(Qt.black, ClickedDetectSize)) painter.drawPoint(prev[0], prev[1]) painter.setPen(QPen(Qt.black, 5)) for pair in self.tmp: painter.drawPoint(*pair) # Draw old lines if len(self.tmp) >= 2: painter.setPen(QPen(Qt.black, 2)) previous_pair = self.tmp[0] for pair in self.tmp[1: ]: painter.drawLine(*previous_pair, *pair) previous_pair = pair painter.end() self.LabelPicture.setPixmap(pixmap) def ReDraw(self, update_for_tracking_pixmap, except_row=None): # except_row == None -> for tracking pixmap if except_row is None: if update_for_tracking_pixmap: self.LabelPicture.setPixmap(self.for_delete) for i, poly in enumerate(self.attribute): self.polygon(poly, 1, self.color_index[i]) self.for_tracking_pixmap = QPixmap(self.LabelPicture.pixmap()) else: self.LabelPicture.setPixmap(self.for_tracking_pixmap) # except_row != None -> for editing pixmap else: self.LabelPicture.setPixmap(self.for_delete) for i, poly in enumerate(self.attribute): if i == except_row: continue self.polygon(poly, 1, self.color_index[i]) self.for_editing_pixmap = QPixmap(self.LabelPicture.pixmap()) # 取得需要的 pixmap 之後,再把圖畫完整( 避免剛點下去的瞬間少一個多邊形 ) self.polygon(self.attribute[except_row], 1, self.color_index[except_row])
import os import re import math from datetime import timedelta import pprint import logging from tinydb import TinyDB, Query from tqdm import tqdm from config import built_ins, MAX_BATCH from util import chunks, file_time_str from tablo.api import Api from tablo.apiexception import APIError from tablo.entities.show import Show from recording import Recording logger = logging.getLogger(__name__) def view(args): print() path = built_ins['db']['recordings'] rec_db = TinyDB(path) id_set = [] cnt = 0 for item in rec_db.all(): cnt += 1 if args.id_list: obj_id = item['data']['object_id'] if obj_id not in id_set: id_set.append(obj_id) elif args.full: pprint.pprint(item) else: Recording(item['data']).print() if args.id_list: print(id_set) else: print(f'Total recordings found: {cnt}') def print_stats(): path = built_ins['db']['recordings'] rec_db = TinyDB(path) shows = Query() shows_qry = shows.data field_title = '{:17}' print("Overview") print("-" * 50) print(f"Built: {file_time_str(path)}") cnt = len(rec_db.all()) print('{:10}'.format("Total Recordings") + ": " + f'{cnt}') cnt = rec_db.count(shows_qry.user_info.watched == True) # noqa: E712 print('{:10}'.format("Total Watched") + ": " + f'{cnt}') print() print("By Current Recording State") print("-"*50) cnt = rec_db.count(shows_qry.video_details.state == 'finished') print(field_title.format("Finished") + ": " + f'{cnt}') cnt = rec_db.count(shows_qry.video_details.state == 'failed') print(field_title.format("Failed") + ": " + f'{cnt}') cnt = rec_db.count(shows_qry.video_details.state == 'recording') print(field_title.format("Recording") + ": " + f'{cnt}') print() print("By Recording Type") print("-" * 50) cnt = rec_db.count(shows.path.matches(f'.*episode.*', flags=re.IGNORECASE)) print(field_title.format("Episodes/Series") + ": " + f'{cnt}') cnt = rec_db.count(shows.path.matches(f'.*movie.*', flags=re.IGNORECASE)) print(field_title.format("Movies") + ": " + f'{cnt}') cnt = rec_db.count(shows.path.matches(f'.*sports.*', flags=re.IGNORECASE)) print(field_title.format("Sports/Events") + ": " + f'{cnt}') cnt = rec_db.count( shows.path.matches(f'.*programs.*', flags=re.IGNORECASE) ) print(field_title.format("Programs") + ": " + f'{cnt}') print() print("By Show") print("-" * 50) shows = {} max_width = 0 for item in rec_db.all(): title = item['data']['airing_details']['show_title'] max_width = max(max_width, len(title)) key = _sortable_title(title) if key not in shows.keys(): shows[key] = {'cnt': 1, 'title': title} else: shows[key]['cnt'] += 1 for key in sorted(shows.keys()): # print(f"{shows[key]["title"]} - {shows[key]["cnt"]}") print( ('{:' + str(max_width) + '}').format(shows[key]['title']) + ' - {:>2}'.format(shows[key]['cnt']) ) def _sortable_title(title): # toss a/an/the, force non-letters to end articles = ['a', 'an', 'the'] word = title.split(' ', 1)[0].lower() sort_title = title if word in articles: try: sort_title = title.split(' ', 1)[1] except Exception: sort_title = title if ord(sort_title[0]) not in range(ord('A'), ord('z') + 1): sort_title = "ZZZZ" + sort_title return sort_title def build(): print("Building library. NO videos are being fetched.") print("-"*50) Api.discover() connected = Api.selectDevice() if not connected: logger.exception("NOT CONNECTED") # don't think we'll need this # _build_guide() _build_recordings() def _build_guide(): guide_path = built_ins['db']['guide'] if not built_ins['dry_run']: try: os.unlink(guide_path) except Exception: pass guide_db = {} if not built_ins['dry_run']: guide_db = TinyDB(guide_path) # Load all the shows print('Loading All Guide/Show data') sections = Api.views('guide').shows.get() total = sum(len(section.get('contents')) for section in sections) print(f"Total Shows: {total}") for section in sections: contents = section.get('contents') if not contents: logger.info(f"Section {section.get("key").upper()} (0)") continue logger.info(f"Section {section.get("key").upper()} ({len(contents)})") for piece in chunks(contents, MAX_BATCH): shows = Api.batch.post(piece) for path, data in shows.items(): show = Show.newFromData(data) if not built_ins['dry_run']: guide_db.insert({ 'id': show.object_id, 'path': show.path, 'data': show.data, 'version': Api.device.version }) def _build_recordings(): recs_path = built_ins['db']['recordings'] recshow_path = built_ins['db']['recording_shows'] if not built_ins['dry_run']: try: os.unlink(recs_path) except Exception: pass try: os.unlink(recshow_path) except Exception: pass recs_db = TinyDB(recs_path) programs = Api.recordings.airings.get() show_paths = [] print(f"Total Recordings: {len(programs)}") # cnt = 0 with tqdm(total=len(programs)) as pbar: for piece in chunks(programs, MAX_BATCH): airings = Api.batch.post(piece) # cnt += len(airings) # print(f"\tchunk: {cnt}/{len(programs)}") for path, data in airings.items(): airing = Recording(data) if airing.showPath not in show_paths: show_paths.append(airing.showPath) if not built_ins['dry_run']: recs_db.insert({ 'id': airing.object_id, 'path': airing.path, 'show_path': airing.showPath, 'data': airing.data, 'version': Api.device.version }) pbar.update(1) recshow_db = TinyDB(recshow_path) print(f"Total Recorded Shows: {len(show_paths)}") my_show = Query() with tqdm(total=len(show_paths)) as pbar: # this is silly and just to make the progress bar move :/ for piece in chunks(show_paths, math.ceil(MAX_BATCH/5)): # not caring about progress, we'd use this: # for piece in chunks(show_paths, MAX_BATCH): airing_shows = Api.batch.post(piece) for path, data in airing_shows.items(): stuff = recshow_db.search(my_show.show_path == path) pbar.update(1) if not stuff: if not built_ins['dry_run']: recshow_db.insert({ 'id': data['object_id'], 'show_path': path, 'data': data, 'version': Api.device.version }) print("Done!") def print_dupes(): dupes = _find_dupes() for key, data in dupes.items(): if len(data) > 1: print(key + " = " + str(len(data))) for item in data: rec = Recording(item) print("\t" + str(rec.object_id) + " | " + rec.get_description() + " - " + rec.get_dur()) def _find_dupes(): path = built_ins['db']['recordings'] rec_db = TinyDB(path) dupes = {} for item in rec_db.all(): data = item['data'] if 'episode' in data.keys(): tmsid = data['episode']['tms_id'] if tmsid.startswith('SH'): # TODO: this is easy, but wrong. SH* tms_id duplicates for # every episode. Maybe replace with psuedo-title? continue if tmsid not in dupes: dupes[tmsid] = [] dupes[tmsid].append(data) else: dupes[tmsid].append(data) return dupes def print_incomplete(args): # weird way I made it work... percent = args.incomplete if percent == -1: percent = 100 else: percent = min(percent, 100) percent = max(percent, 0) percent = percent / 100 dupes = _find_dupes() proper_dur = 0 matched = 0 total_recs = 0 id_set = [] for key, data in dupes.items(): if key.startswith('SH'): continue if len(data) > 0: sum_actual_dur = 0 recs = [] for item in data: rec = Recording(item) actual_dur = rec.video_details['duration'] proper_dur = rec.airing_details['duration'] sum_actual_dur += actual_dur if proper_dur > actual_dur: recs.append(rec) if (proper_dur * percent) > sum_actual_dur: matched += 1 total_recs += len(recs) header = None for x in recs: if args.id_list: if x.object_id not in id_set: id_set.append(x.object_id) else: if not header: header = x.get_description() + \ " - " + x.episode['tms_id'] print(header) print("\t" + str(x.object_id) + " | " + x.get_description() + " - " + x.get_dur()) if not args.id_list: sum_txt = str(timedelta(seconds=sum_actual_dur)) total_txt = str(timedelta(seconds=proper_dur)) pct = str(round(sum_actual_dur / proper_dur * 100, 2)) print(f"\n\t{sum_txt} / {total_txt} ({pct}%)") print() if args.id_list: print(id_set) else: print(f"Total incomplete shows less than {percent*100}% - {matched} " f"({total_recs} items)") def delete(id_list, args): # TODO: add a confirmation (sans --yyyyassss) total = len(id_list) if total == 0: print(f"Nothing to delete, exiting...") return elif total == 1: print(f"Deleting {total} recording") else: print(f"Deleting {total} recordings") print("-" * 50) # Load all the recs path = built_ins['db']['recordings'] rec_db = TinyDB(path) shows = Query() # shortcut for later shows_qry = shows.data recs = [] total = 0 for obj_id in id_list: obj = rec_db.get( (shows_qry.object_id == int(obj_id)) & (shows_qry.video_details.state != 'recording') ) if not obj: print(f'ERROR: Unable to find recording with ' f'object_id == "{obj_id}", skipping...') continue total += 1 recs.append( { 'doc_id': obj.doc_id, 'obj_id': obj_id, 'rec': Recording(obj['data']) }) # TODO: don't "total" like this if total <= 0: print(f"No recordings found; {len(id_list)} requested.") elif total == 1: print(f"Deleting {total} recording...") else: print(f"Deleting {total} recordings...") if total > 0: for rec in recs: rec = rec['rec'] print(f" - {rec.get_actual_dur()} | {rec.get_description()} ") print("-" * 50) if not args.yes: print() print('\tAdd the "--yes" flag to actually delete things...') print() else: for rec in recs: _delete(rec, rec_db) print("\nFINISHED") def _delete(rec, rec_db): doc_id = rec['doc_id'] item = rec['rec'] print(f"Deleting: {item.get_description()} ({item.get_actual_dur()})") if built_ins['dry_run']: print("DRY RUN: would have deleted...") else: try: # try to delete the full recording item.delete() # delete the local db record instead of REBUILDing everything rec_db.remove(doc_ids=[doc_id]) print("\tDeleted!") except APIError: print("Recording no longer exists") pass
import os import re import math from datetime import timedelta import pprint import logging from tinydb import TinyDB, Query from tqdm import tqdm from config import built_ins, MAX_BATCH from util import chunks, file_time_str from tablo.api import Api from tablo.apiexception import APIError from tablo.entities.show import Show from recording import Recording logger = logging.getLogger(__name__) def view(args): print() path = built_ins['db']['recordings'] rec_db = TinyDB(path) id_set = [] cnt = 0 for item in rec_db.all(): cnt += 1 if args.id_list: obj_id = item['data']['object_id'] if obj_id not in id_set: id_set.append(obj_id) elif args.full: pprint.pprint(item) else: Recording(item['data']).print() if args.id_list: print(id_set) else: print(f'Total recordings found: {cnt}') def print_stats(): path = built_ins['db']['recordings'] rec_db = TinyDB(path) shows = Query() shows_qry = shows.data field_title = '{:17}' print("Overview") print("-" * 50) print(f"Built: {file_time_str(path)}") cnt = len(rec_db.all()) print('{:10}'.format("Total Recordings") + ": " + f'{cnt}') cnt = rec_db.count(shows_qry.user_info.watched == True) # noqa: E712 print('{:10}'.format("Total Watched") + ": " + f'{cnt}') print() print("By Current Recording State") print("-"*50) cnt = rec_db.count(shows_qry.video_details.state == 'finished') print(field_title.format("Finished") + ": " + f'{cnt}') cnt = rec_db.count(shows_qry.video_details.state == 'failed') print(field_title.format("Failed") + ": " + f'{cnt}') cnt = rec_db.count(shows_qry.video_details.state == 'recording') print(field_title.format("Recording") + ": " + f'{cnt}') print() print("By Recording Type") print("-" * 50) cnt = rec_db.count(shows.path.matches(f'.*episode.*', flags=re.IGNORECASE)) print(field_title.format("Episodes/Series") + ": " + f'{cnt}') cnt = rec_db.count(shows.path.matches(f'.*movie.*', flags=re.IGNORECASE)) print(field_title.format("Movies") + ": " + f'{cnt}') cnt = rec_db.count(shows.path.matches(f'.*sports.*', flags=re.IGNORECASE)) print(field_title.format("Sports/Events") + ": " + f'{cnt}') cnt = rec_db.count( shows.path.matches(f'.*programs.*', flags=re.IGNORECASE) ) print(field_title.format("Programs") + ": " + f'{cnt}') print() print("By Show") print("-" * 50) shows = {} max_width = 0 for item in rec_db.all(): title = item['data']['airing_details']['show_title'] max_width = max(max_width, len(title)) key = _sortable_title(title) if key not in shows.keys(): shows[key] = {'cnt': 1, 'title': title} else: shows[key]['cnt'] += 1 for key in sorted(shows.keys()): # print(f"{shows[key]['title']} - {shows[key]['cnt']}") print( ('{:' + str(max_width) + '}').format(shows[key]['title']) + ' - {:>2}'.format(shows[key]['cnt']) ) def _sortable_title(title): # toss a/an/the, force non-letters to end articles = ['a', 'an', 'the'] word = title.split(' ', 1)[0].lower() sort_title = title if word in articles: try: sort_title = title.split(' ', 1)[1] except Exception: sort_title = title if ord(sort_title[0]) not in range(ord('A'), ord('z') + 1): sort_title = "ZZZZ" + sort_title return sort_title def build(): print("Building library. NO videos are being fetched.") print("-"*50) Api.discover() connected = Api.selectDevice() if not connected: logger.exception("NOT CONNECTED") # don't think we'll need this # _build_guide() _build_recordings() def _build_guide(): guide_path = built_ins['db']['guide'] if not built_ins['dry_run']: try: os.unlink(guide_path) except Exception: pass guide_db = {} if not built_ins['dry_run']: guide_db = TinyDB(guide_path) # Load all the shows print('Loading All Guide/Show data') sections = Api.views('guide').shows.get() total = sum(len(section.get('contents')) for section in sections) print(f"Total Shows: {total}") for section in sections: contents = section.get('contents') if not contents: logger.info(f"Section {section.get('key').upper()} (0)") continue logger.info(f"Section {section.get('key').upper()} ({len(contents)})") for piece in chunks(contents, MAX_BATCH): shows = Api.batch.post(piece) for path, data in shows.items(): show = Show.newFromData(data) if not built_ins['dry_run']: guide_db.insert({ 'id': show.object_id, 'path': show.path, 'data': show.data, 'version': Api.device.version }) def _build_recordings(): recs_path = built_ins['db']['recordings'] recshow_path = built_ins['db']['recording_shows'] if not built_ins['dry_run']: try: os.unlink(recs_path) except Exception: pass try: os.unlink(recshow_path) except Exception: pass recs_db = TinyDB(recs_path) programs = Api.recordings.airings.get() show_paths = [] print(f"Total Recordings: {len(programs)}") # cnt = 0 with tqdm(total=len(programs)) as pbar: for piece in chunks(programs, MAX_BATCH): airings = Api.batch.post(piece) # cnt += len(airings) # print(f"\tchunk: {cnt}/{len(programs)}") for path, data in airings.items(): airing = Recording(data) if airing.showPath not in show_paths: show_paths.append(airing.showPath) if not built_ins['dry_run']: recs_db.insert({ 'id': airing.object_id, 'path': airing.path, 'show_path': airing.showPath, 'data': airing.data, 'version': Api.device.version }) pbar.update(1) recshow_db = TinyDB(recshow_path) print(f"Total Recorded Shows: {len(show_paths)}") my_show = Query() with tqdm(total=len(show_paths)) as pbar: # this is silly and just to make the progress bar move :/ for piece in chunks(show_paths, math.ceil(MAX_BATCH/5)): # not caring about progress, we'd use this: # for piece in chunks(show_paths, MAX_BATCH): airing_shows = Api.batch.post(piece) for path, data in airing_shows.items(): stuff = recshow_db.search(my_show.show_path == path) pbar.update(1) if not stuff: if not built_ins['dry_run']: recshow_db.insert({ 'id': data['object_id'], 'show_path': path, 'data': data, 'version': Api.device.version }) print("Done!") def print_dupes(): dupes = _find_dupes() for key, data in dupes.items(): if len(data) > 1: print(key + " = " + str(len(data))) for item in data: rec = Recording(item) print("\t" + str(rec.object_id) + " | " + rec.get_description() + " - " + rec.get_dur()) def _find_dupes(): path = built_ins['db']['recordings'] rec_db = TinyDB(path) dupes = {} for item in rec_db.all(): data = item['data'] if 'episode' in data.keys(): tmsid = data['episode']['tms_id'] if tmsid.startswith('SH'): # TODO: this is easy, but wrong. SH* tms_id duplicates for # every episode. Maybe replace with psuedo-title? continue if tmsid not in dupes: dupes[tmsid] = [] dupes[tmsid].append(data) else: dupes[tmsid].append(data) return dupes def print_incomplete(args): # weird way I made it work... percent = args.incomplete if percent == -1: percent = 100 else: percent = min(percent, 100) percent = max(percent, 0) percent = percent / 100 dupes = _find_dupes() proper_dur = 0 matched = 0 total_recs = 0 id_set = [] for key, data in dupes.items(): if key.startswith('SH'): continue if len(data) > 0: sum_actual_dur = 0 recs = [] for item in data: rec = Recording(item) actual_dur = rec.video_details['duration'] proper_dur = rec.airing_details['duration'] sum_actual_dur += actual_dur if proper_dur > actual_dur: recs.append(rec) if (proper_dur * percent) > sum_actual_dur: matched += 1 total_recs += len(recs) header = None for x in recs: if args.id_list: if x.object_id not in id_set: id_set.append(x.object_id) else: if not header: header = x.get_description() + \ " - " + x.episode['tms_id'] print(header) print("\t" + str(x.object_id) + " | " + x.get_description() + " - " + x.get_dur()) if not args.id_list: sum_txt = str(timedelta(seconds=sum_actual_dur)) total_txt = str(timedelta(seconds=proper_dur)) pct = str(round(sum_actual_dur / proper_dur * 100, 2)) print(f"\n\t{sum_txt} / {total_txt} ({pct}%)") print() if args.id_list: print(id_set) else: print(f"Total incomplete shows less than {percent*100}% - {matched} " f"({total_recs} items)") def delete(id_list, args): # TODO: add a confirmation (sans --yyyyassss) total = len(id_list) if total == 0: print(f"Nothing to delete, exiting...") return elif total == 1: print(f"Deleting {total} recording") else: print(f"Deleting {total} recordings") print("-" * 50) # Load all the recs path = built_ins['db']['recordings'] rec_db = TinyDB(path) shows = Query() # shortcut for later shows_qry = shows.data recs = [] total = 0 for obj_id in id_list: obj = rec_db.get( (shows_qry.object_id == int(obj_id)) & (shows_qry.video_details.state != 'recording') ) if not obj: print(f'ERROR: Unable to find recording with ' f'object_id == "{obj_id}", skipping...') continue total += 1 recs.append( { 'doc_id': obj.doc_id, 'obj_id': obj_id, 'rec': Recording(obj['data']) }) # TODO: don't "total" like this if total <= 0: print(f"No recordings found; {len(id_list)} requested.") elif total == 1: print(f"Deleting {total} recording...") else: print(f"Deleting {total} recordings...") if total > 0: for rec in recs: rec = rec['rec'] print(f" - {rec.get_actual_dur()} | {rec.get_description()} ") print("-" * 50) if not args.yes: print() print('\tAdd the "--yes" flag to actually delete things...') print() else: for rec in recs: _delete(rec, rec_db) print("\nFINISHED") def _delete(rec, rec_db): doc_id = rec['doc_id'] item = rec['rec'] print(f"Deleting: {item.get_description()} ({item.get_actual_dur()})") if built_ins['dry_run']: print("DRY RUN: would have deleted...") else: try: # try to delete the full recording item.delete() # delete the local db record instead of REBUILDing everything rec_db.remove(doc_ids=[doc_id]) print("\tDeleted!") except APIError: print("Recording no longer exists") pass
# Copyright 2018 The Cirq Developers # # 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. """Workarounds for compatibility issues between versions and libraries.""" import functools import importlib import os import re import sys import traceback import warnings from types import ModuleType from typing import Any, Callable, Optional, Dict, Tuple, Type, Set import numpy as np import pandas as pd import sympy def proper_repr(value: Any) -> str: """Overrides sympy and numpy returning repr strings that don't parse.""" if isinstance(value, sympy.Basic): result = sympy.srepr(value) # HACK: work around https://github.com/sympy/sympy/issues/16074 # (only handles a few cases) fixed_tokens = ['Symbol', 'pi', 'Mul', 'Pow', 'Add', 'Mod', 'Integer', 'Float', 'Rational'] for token in fixed_tokens: result = result.replace(token, 'sympy.' + token) return result if isinstance(value, np.ndarray): if np.issubdtype(value.dtype, np.datetime64): return f'np.array({value.tolist()!r}, dtype=np.{value.dtype!r})' return f'np.array({value.tolist()!r}, dtype=np.{value.dtype})' if isinstance(value, pd.MultiIndex): return f'pd.MultiIndex.from_tuples({repr(list(value))}, names={repr(list(value.names))})' if isinstance(value, pd.Index): return ( f'pd.Index({repr(list(value))}, ' f'name={repr(value.name)}, ' f'dtype={repr(str(value.dtype))})' ) if isinstance(value, pd.DataFrame): cols = [value[col].tolist() for col in value.columns] rows = list(zip(*cols)) return ( f'pd.DataFrame(' f'\n columns={proper_repr(value.columns)}, ' f'\n index={proper_repr(value.index)}, ' f'\n data={repr(rows)}' f'\n)' ) return repr(value) def proper_eq(a: Any, b: Any) -> bool: """Compares objects for equality, working around __eq__ not always working. For example, in numpy a == b broadcasts and returns an array instead of doing what np.array_equal(a, b) does. This method uses np.array_equal(a, b) when dealing with numpy arrays. """ if type(a) == type(b): if isinstance(a, np.ndarray): return np.array_equal(a, b) if isinstance(a, (pd.DataFrame, pd.Index, pd.MultiIndex)): return a.equals(b) if isinstance(a, (tuple, list)): return len(a) == len(b) and all(proper_eq(x, y) for x, y in zip(a, b)) return a == b def _warn_or_error(msg): from cirq.testing.deprecation import ALLOW_DEPRECATION_IN_TEST called_from_test = 'PYTEST_CURRENT_TEST' in os.environ deprecation_allowed = ALLOW_DEPRECATION_IN_TEST in os.environ if called_from_test and not deprecation_allowed: raise ValueError(f"Cirq should not use deprecated functionality: {msg}") # we have to dynamically count the non-internal frames # due to the potentially multiple nested module wrappers stack_level = 1 for filename, _, _, _ in reversed(traceback.extract_stack()): if not _is_internal(filename) and "_compat.py" not in filename: break if "_compat.py" in filename: stack_level += 1 warnings.warn( msg, DeprecationWarning, stacklevel=stack_level, ) def _validate_deadline(deadline: str): DEADLINE_REGEX = r"^v(\d)+\.(\d)+$" assert re.match(DEADLINE_REGEX, deadline), "deadline should match vX.Y" def deprecated( *, deadline: str, fix: str, name: Optional[str] = None ) -> Callable[[Callable], Callable]: """Marks a function as deprecated. Args: deadline: The version where the function will be deleted. It should be a minor version (e.g. "v0.7"). fix: A complete sentence describing what the user should be using instead of this particular function (e.g. "Use cos instead.") name: How to refer to the function. Defaults to `func.__qualname__`. Returns: A decorator that decorates functions with a deprecation warning. """ _validate_deadline(deadline) def decorator(func: Callable) -> Callable: @functools.wraps(func) def decorated_func(*args, **kwargs) -> Any: qualname = func.__qualname__ if name is None else name _warn_or_error( f'{qualname} was used but is deprecated.\n' f'It will be removed in cirq {deadline}.\n' f'{fix}\n' ) return func(*args, **kwargs) decorated_func.__doc__ = ( f'THIS FUNCTION IS DEPRECATED.\n\n' f'IT WILL BE REMOVED IN `cirq {deadline}`.\n\n' f'{fix}\n\n' f'{decorated_func.__doc__ or ''}' ) return decorated_func return decorator def deprecated_class( *, deadline: str, fix: str, name: Optional[str] = None ) -> Callable[[Type], Type]: """Marks a class as deprecated. Args: deadline: The version where the function will be deleted. It should be a minor version (e.g. "v0.7"). fix: A complete sentence describing what the user should be using instead of this particular function (e.g. "Use cos instead.") name: How to refer to the class. Defaults to `class.__qualname__`. Returns: A decorator that decorates classes with a deprecation warning. """ _validate_deadline(deadline) def decorator(clazz: Type) -> Type: clazz_new = clazz.__new__ def patched_new(cls, *args, **kwargs): qualname = clazz.__qualname__ if name is None else name _warn_or_error( f'{qualname} was used but is deprecated.\n' f'It will be removed in cirq {deadline}.\n' f'{fix}\n' ) return clazz_new(cls) setattr(clazz, '__new__', patched_new) clazz.__doc__ = ( f'THIS CLASS IS DEPRECATED.\n\n' f'IT WILL BE REMOVED IN `cirq {deadline}`.\n\n' f'{fix}\n\n' f'{clazz.__doc__ or ''}' ) return clazz return decorator def deprecated_parameter( *, deadline: str, fix: str, func_name: Optional[str] = None, parameter_desc: str, match: Callable[[Tuple[Any, ...], Dict[str, Any]], bool], rewrite: Optional[ Callable[[Tuple[Any, ...], Dict[str, Any]], Tuple[Tuple[Any, ...], Dict[str, Any]]] ] = None, ) -> Callable[[Callable], Callable]: """Marks a function parameter as deprecated. Also handles rewriting the deprecated parameter into the new signature. Args: deadline: The version where the function will be deleted. It should be a minor version (e.g. "v0.7"). fix: A complete sentence describing what the user should be using instead of this particular function (e.g. "Use cos instead.") func_name: How to refer to the function. Defaults to `func.__qualname__`. parameter_desc: The name and type of the parameter being deprecated, e.g. "janky_count" or "janky_count keyword" or "positional janky_count". match: A lambda that takes args, kwargs and determines if the deprecated parameter is present or not. This determines whether or not the deprecation warning is printed, and also whether or not rewrite is called. rewrite: Returns new args/kwargs that don't use the deprecated parameter. Defaults to making no changes. Returns: A decorator that decorates functions with a parameter deprecation warning. """ _validate_deadline(deadline) def decorator(func: Callable) -> Callable: @functools.wraps(func) def decorated_func(*args, **kwargs) -> Any: if match(args, kwargs): if rewrite is not None: args, kwargs = rewrite(args, kwargs) qualname = func.__qualname__ if func_name is None else func_name _warn_or_error( f'The {parameter_desc} parameter of {qualname} was ' f'used but is deprecated.\n' f'It will be removed in cirq {deadline}.\n' f'{fix}\n', ) return func(*args, **kwargs) return decorated_func return decorator def deprecate_attributes(module: ModuleType, deprecated_attributes: Dict[str, Tuple[str, str]]): """Wrap a module with deprecated attributes that give warnings. Args: module: The module to wrap. deprecated_attributes: A dictionary from attribute name to a tuple of strings, where the first string gives the version that the attribute will be removed in, and the second string describes what the user should do instead of accessing this deprecated attribute. Returns: Wrapped module with deprecated attributes. Use of these attributes will cause a warning for these deprecated attributes. """ for (deadline, _) in deprecated_attributes.values(): _validate_deadline(deadline) class Wrapped(ModuleType): __dict__ = module.__dict__ def __getattr__(self, name): if name in deprecated_attributes: deadline, fix = deprecated_attributes[name] _warn_or_error( f'{name} was used but is deprecated.\n' f'It will be removed in cirq {deadline}.\n' f'{fix}\n' ) return getattr(module, name) return Wrapped(module.__name__, module.__doc__) class DeprecatedModuleLoader(importlib.abc.Loader): """A Loader for deprecated modules. It wraps an existing Loader instance, to which it delegates the loading. On top of that it ensures that the sys.modules cache has both the deprecated module's name and the new module's name pointing to the same exact ModuleType instance. Args: loader: the loader to be wrapped old_module_name: the deprecated module's fully qualified name new_module_name: the new module's fully qualified name """ def __init__(self, loader: Any, old_module_name: str, new_module_name: str): """A module loader that uses an existing module loader and intercepts the execution of a module. """ self.loader = loader if hasattr(loader, 'exec_module'): # mypy#2427 self.exec_module = self._wrap_exec_module(loader.exec_module) # type: ignore # while this is rare and load_module was deprecated in 3.4 # in older environments this line makes them work as well if hasattr(loader, 'load_module'): # mypy#2427 self.load_module = self._wrap_load_module(loader.load_module) # type: ignore if hasattr(loader, 'create_module'): self.create_module = loader.create_module # type: ignore self.old_module_name = old_module_name self.new_module_name = new_module_name def module_repr(self, module: ModuleType) -> str: return self.loader.module_repr(module) def _wrap_load_module(self, method: Any) -> Any: def load_module(fullname: str) -> ModuleType: assert fullname == self.old_module_name, ( f"DeprecatedModuleLoader for {self.old_module_name} was asked to " f"load {fullname}" ) if self.new_module_name in sys.modules: sys.modules[self.old_module_name] = sys.modules[self.new_module_name] return sys.modules[self.old_module_name] method(self.new_module_name) assert self.new_module_name in sys.modules, ( f"Wrapped loader {self.loader} was " f"expected to insert " f"{self.new_module_name} in sys.modules " f"but it did not." ) sys.modules[self.old_module_name] = sys.modules[self.new_module_name] return sys.modules[self.old_module_name] return load_module def _wrap_exec_module(self, method: Any) -> Any: def exec_module(module: ModuleType) -> None: assert module.__name__ == self.old_module_name, ( f"DeprecatedModuleLoader for {self.old_module_name} was asked to " f"load {module.__name__}" ) # check for new_module whether it was loaded if self.new_module_name in sys.modules: # found it - no need to load the module again sys.modules[self.old_module_name] = sys.modules[self.new_module_name] return # now we know we have to initialize the module sys.modules[self.old_module_name] = module sys.modules[self.new_module_name] = module try: return method(module) except BaseException: # if there's an error, we atomically remove both del sys.modules[self.new_module_name] del sys.modules[self.old_module_name] raise return exec_module def _is_internal(filename: str) -> bool: """Returns whether filename is internal to python. This is similar to how the built-in warnings module differentiates frames from internal modules. It is specific to CPython - see https://github.com/python/cpython/blob/41ec17e45d54473d32f543396293256f1581e44d/Lib/warnings.py#L275. """ return 'importlib' in filename and '_bootstrap' in filename _warned: Set[str] = set() def _deduped_module_warn_or_error(old_module_name, new_module_name, deadline): if old_module_name in _warned: return _warned.add(old_module_name) _warn_or_error( f"{old_module_name} was used but is deprecated.\n " f"it will be removed in cirq {deadline}.\n " f"Use {new_module_name} instead.\n", ) class DeprecatedModuleFinder(importlib.abc.MetaPathFinder): """A module finder to handle deprecated module references. It sends a deprecation warning when a deprecated module is asked to be found. It is meant to be used as a wrapper around existing MetaPathFinder instances. Args: finder: the finder to wrap. new_module_name: the new module's fully qualified name old_module_name: the deprecated module's fully qualified name deadline: the deprecation deadline """ def __init__( self, finder: Any, new_module_name: str, old_module_name: str, deadline: str, ): """An aliasing module finder that uses an existing module finder to find a python module spec and intercept the execution of matching modules. """ self.finder = finder self.new_module_name = new_module_name self.old_module_name = old_module_name self.deadline = deadline # to cater for metadata path finders # https://docs.python.org/3/library/importlib.metadata.html#extending-the-search-algorithm if hasattr(finder, "find_distributions"): def find_distributions(context): return self.finder.find_distributions(context) self.find_distributions = find_distributions if hasattr(finder, "invalidate_caches"): def invalidate_caches() -> None: return self.finder.invalidate_caches() # mypy#2427 self.invalidate_caches = invalidate_caches # type: ignore def find_spec(self, fullname: str, path: Any = None, target: Any = None) -> Any: """Finds the specification of a module. This is an implementation of the importlib.abc.MetaPathFinder.find_spec method. See https://docs.python.org/3/library/importlib.html#importlib.abc.MetaPathFinder. Args: fullname: name of the module. path: if presented, this is the parent module's submodule search path. target: When passed in, target is a module object that the finder may use to make a more educated guess about what spec to return. We don't use it here, just pass it along to the wrapped finder. """ if fullname != self.old_module_name and not fullname.startswith(self.old_module_name + "."): # if we are not interested in it, then just pass through to the wrapped finder return self.finder.find_spec(fullname, path, target) # warn for deprecation _deduped_module_warn_or_error(self.old_module_name, self.new_module_name, self.deadline) new_fullname = self.new_module_name + fullname[len(self.old_module_name) :] # find the corresponding spec in the new structure if fullname == self.old_module_name: # this is the first time the deprecated module is being found # which means that the new parent needs to be found first and under # the new parent's path, we should be able to find the new name of # the deprecated module # this code is heavily inspired by importlib.util.find_spec parent_name = new_fullname.rpartition('.')[0] if parent_name: parent = __import__(parent_name, fromlist=['__path__']) # note that compared to importlib.util.find_spec we don't handle # AttributeError here because it is not expected to happen in case # of a DeprecatedModuleLoader - the new parent should exist and be # a proper package parent_path = parent.__path__ else: parent_path = None spec = self.finder.find_spec(new_fullname, parent_path, None) else: # we are finding a submodule of the parent of the deprecated module, # which means that the parent was already found, and thus, `path` is # correctly pointing to the module's parent in the new hierarchy spec = self.finder.find_spec( new_fullname, path=path, target=target, ) # if the spec exists, return the DeprecatedModuleLoader that will do the loading as well # as set the alias(es) in sys.modules as necessary if spec is not None: # change back the name to the deprecated module name spec.name = fullname # some loaders do a check to ensure the module's name is the same # as the loader was created for if getattr(spec.loader, "name", None) == new_fullname: setattr(spec.loader, "name", fullname) spec.loader = DeprecatedModuleLoader(spec.loader, fullname, new_fullname) return spec def deprecated_submodule( *, new_module_name: str, old_parent: str, old_child: str, deadline: str, create_attribute: bool ): """Creates a deprecated module reference recursively for a module. For `new_module_name` (e.g. cirq_google) creates an alias (e.g cirq.google) in Python's module cache. It also recursively checks for the already imported submodules (e.g. cirq_google.api) and creates the alias for them too (e.g. cirq.google.api). With this method it is possible to create an alias that really looks like a module, e.g you can do things like `from cirq.google import api` - which would be otherwise impossible. Note that this method will execute `new_module_name` in order to ensure that it is in the module cache. Args: new_module_name: absolute module name for the new module old_parent: the current module that had the original submodule old_child: the submodule that is being relocated create_attribute: if True, the submodule will be added as a deprecated attribute to the old_parent module Returns: None """ _validate_deadline(deadline) old_module_name = f"{old_parent}.{old_child}" if create_attribute: new_module = importlib.import_module(new_module_name) _setup_deprecated_submodule_attribute( new_module_name, old_parent, old_child, deadline, new_module ) def wrap(finder: Any) -> Any: if not hasattr(finder, 'find_spec'): return finder # this is just to make mypy not complain about the type of new_module_spec being Optional return DeprecatedModuleFinder(finder, new_module_name, old_module_name, deadline) sys.meta_path = [wrap(finder) for finder in sys.meta_path] def _setup_deprecated_submodule_attribute( new_module_name: str, old_parent: str, old_child: str, deadline: str, new_module: ModuleType ): parent_module = sys.modules[old_parent] setattr(parent_module, old_child, new_module) class Wrapped(ModuleType): __dict__ = parent_module.__dict__ def __getattr__(self, name): if name == old_child: _deduped_module_warn_or_error( f"{old_parent}.{old_child}", new_module_name, deadline ) return getattr(parent_module, name) sys.modules[old_parent] = Wrapped(parent_module.__name__, parent_module.__doc__)
# Copyright 2018 The Cirq Developers # # 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. """Workarounds for compatibility issues between versions and libraries.""" import functools import importlib import os import re import sys import traceback import warnings from types import ModuleType from typing import Any, Callable, Optional, Dict, Tuple, Type, Set import numpy as np import pandas as pd import sympy def proper_repr(value: Any) -> str: """Overrides sympy and numpy returning repr strings that don't parse.""" if isinstance(value, sympy.Basic): result = sympy.srepr(value) # HACK: work around https://github.com/sympy/sympy/issues/16074 # (only handles a few cases) fixed_tokens = ['Symbol', 'pi', 'Mul', 'Pow', 'Add', 'Mod', 'Integer', 'Float', 'Rational'] for token in fixed_tokens: result = result.replace(token, 'sympy.' + token) return result if isinstance(value, np.ndarray): if np.issubdtype(value.dtype, np.datetime64): return f'np.array({value.tolist()!r}, dtype=np.{value.dtype!r})' return f'np.array({value.tolist()!r}, dtype=np.{value.dtype})' if isinstance(value, pd.MultiIndex): return f'pd.MultiIndex.from_tuples({repr(list(value))}, names={repr(list(value.names))})' if isinstance(value, pd.Index): return ( f'pd.Index({repr(list(value))}, ' f'name={repr(value.name)}, ' f'dtype={repr(str(value.dtype))})' ) if isinstance(value, pd.DataFrame): cols = [value[col].tolist() for col in value.columns] rows = list(zip(*cols)) return ( f'pd.DataFrame(' f'\n columns={proper_repr(value.columns)}, ' f'\n index={proper_repr(value.index)}, ' f'\n data={repr(rows)}' f'\n)' ) return repr(value) def proper_eq(a: Any, b: Any) -> bool: """Compares objects for equality, working around __eq__ not always working. For example, in numpy a == b broadcasts and returns an array instead of doing what np.array_equal(a, b) does. This method uses np.array_equal(a, b) when dealing with numpy arrays. """ if type(a) == type(b): if isinstance(a, np.ndarray): return np.array_equal(a, b) if isinstance(a, (pd.DataFrame, pd.Index, pd.MultiIndex)): return a.equals(b) if isinstance(a, (tuple, list)): return len(a) == len(b) and all(proper_eq(x, y) for x, y in zip(a, b)) return a == b def _warn_or_error(msg): from cirq.testing.deprecation import ALLOW_DEPRECATION_IN_TEST called_from_test = 'PYTEST_CURRENT_TEST' in os.environ deprecation_allowed = ALLOW_DEPRECATION_IN_TEST in os.environ if called_from_test and not deprecation_allowed: raise ValueError(f"Cirq should not use deprecated functionality: {msg}") # we have to dynamically count the non-internal frames # due to the potentially multiple nested module wrappers stack_level = 1 for filename, _, _, _ in reversed(traceback.extract_stack()): if not _is_internal(filename) and "_compat.py" not in filename: break if "_compat.py" in filename: stack_level += 1 warnings.warn( msg, DeprecationWarning, stacklevel=stack_level, ) def _validate_deadline(deadline: str): DEADLINE_REGEX = r"^v(\d)+\.(\d)+$" assert re.match(DEADLINE_REGEX, deadline), "deadline should match vX.Y" def deprecated( *, deadline: str, fix: str, name: Optional[str] = None ) -> Callable[[Callable], Callable]: """Marks a function as deprecated. Args: deadline: The version where the function will be deleted. It should be a minor version (e.g. "v0.7"). fix: A complete sentence describing what the user should be using instead of this particular function (e.g. "Use cos instead.") name: How to refer to the function. Defaults to `func.__qualname__`. Returns: A decorator that decorates functions with a deprecation warning. """ _validate_deadline(deadline) def decorator(func: Callable) -> Callable: @functools.wraps(func) def decorated_func(*args, **kwargs) -> Any: qualname = func.__qualname__ if name is None else name _warn_or_error( f'{qualname} was used but is deprecated.\n' f'It will be removed in cirq {deadline}.\n' f'{fix}\n' ) return func(*args, **kwargs) decorated_func.__doc__ = ( f'THIS FUNCTION IS DEPRECATED.\n\n' f'IT WILL BE REMOVED IN `cirq {deadline}`.\n\n' f'{fix}\n\n' f'{decorated_func.__doc__ or ""}' ) return decorated_func return decorator def deprecated_class( *, deadline: str, fix: str, name: Optional[str] = None ) -> Callable[[Type], Type]: """Marks a class as deprecated. Args: deadline: The version where the function will be deleted. It should be a minor version (e.g. "v0.7"). fix: A complete sentence describing what the user should be using instead of this particular function (e.g. "Use cos instead.") name: How to refer to the class. Defaults to `class.__qualname__`. Returns: A decorator that decorates classes with a deprecation warning. """ _validate_deadline(deadline) def decorator(clazz: Type) -> Type: clazz_new = clazz.__new__ def patched_new(cls, *args, **kwargs): qualname = clazz.__qualname__ if name is None else name _warn_or_error( f'{qualname} was used but is deprecated.\n' f'It will be removed in cirq {deadline}.\n' f'{fix}\n' ) return clazz_new(cls) setattr(clazz, '__new__', patched_new) clazz.__doc__ = ( f'THIS CLASS IS DEPRECATED.\n\n' f'IT WILL BE REMOVED IN `cirq {deadline}`.\n\n' f'{fix}\n\n' f'{clazz.__doc__ or ""}' ) return clazz return decorator def deprecated_parameter( *, deadline: str, fix: str, func_name: Optional[str] = None, parameter_desc: str, match: Callable[[Tuple[Any, ...], Dict[str, Any]], bool], rewrite: Optional[ Callable[[Tuple[Any, ...], Dict[str, Any]], Tuple[Tuple[Any, ...], Dict[str, Any]]] ] = None, ) -> Callable[[Callable], Callable]: """Marks a function parameter as deprecated. Also handles rewriting the deprecated parameter into the new signature. Args: deadline: The version where the function will be deleted. It should be a minor version (e.g. "v0.7"). fix: A complete sentence describing what the user should be using instead of this particular function (e.g. "Use cos instead.") func_name: How to refer to the function. Defaults to `func.__qualname__`. parameter_desc: The name and type of the parameter being deprecated, e.g. "janky_count" or "janky_count keyword" or "positional janky_count". match: A lambda that takes args, kwargs and determines if the deprecated parameter is present or not. This determines whether or not the deprecation warning is printed, and also whether or not rewrite is called. rewrite: Returns new args/kwargs that don't use the deprecated parameter. Defaults to making no changes. Returns: A decorator that decorates functions with a parameter deprecation warning. """ _validate_deadline(deadline) def decorator(func: Callable) -> Callable: @functools.wraps(func) def decorated_func(*args, **kwargs) -> Any: if match(args, kwargs): if rewrite is not None: args, kwargs = rewrite(args, kwargs) qualname = func.__qualname__ if func_name is None else func_name _warn_or_error( f'The {parameter_desc} parameter of {qualname} was ' f'used but is deprecated.\n' f'It will be removed in cirq {deadline}.\n' f'{fix}\n', ) return func(*args, **kwargs) return decorated_func return decorator def deprecate_attributes(module: ModuleType, deprecated_attributes: Dict[str, Tuple[str, str]]): """Wrap a module with deprecated attributes that give warnings. Args: module: The module to wrap. deprecated_attributes: A dictionary from attribute name to a tuple of strings, where the first string gives the version that the attribute will be removed in, and the second string describes what the user should do instead of accessing this deprecated attribute. Returns: Wrapped module with deprecated attributes. Use of these attributes will cause a warning for these deprecated attributes. """ for (deadline, _) in deprecated_attributes.values(): _validate_deadline(deadline) class Wrapped(ModuleType): __dict__ = module.__dict__ def __getattr__(self, name): if name in deprecated_attributes: deadline, fix = deprecated_attributes[name] _warn_or_error( f'{name} was used but is deprecated.\n' f'It will be removed in cirq {deadline}.\n' f'{fix}\n' ) return getattr(module, name) return Wrapped(module.__name__, module.__doc__) class DeprecatedModuleLoader(importlib.abc.Loader): """A Loader for deprecated modules. It wraps an existing Loader instance, to which it delegates the loading. On top of that it ensures that the sys.modules cache has both the deprecated module's name and the new module's name pointing to the same exact ModuleType instance. Args: loader: the loader to be wrapped old_module_name: the deprecated module's fully qualified name new_module_name: the new module's fully qualified name """ def __init__(self, loader: Any, old_module_name: str, new_module_name: str): """A module loader that uses an existing module loader and intercepts the execution of a module. """ self.loader = loader if hasattr(loader, 'exec_module'): # mypy#2427 self.exec_module = self._wrap_exec_module(loader.exec_module) # type: ignore # while this is rare and load_module was deprecated in 3.4 # in older environments this line makes them work as well if hasattr(loader, 'load_module'): # mypy#2427 self.load_module = self._wrap_load_module(loader.load_module) # type: ignore if hasattr(loader, 'create_module'): self.create_module = loader.create_module # type: ignore self.old_module_name = old_module_name self.new_module_name = new_module_name def module_repr(self, module: ModuleType) -> str: return self.loader.module_repr(module) def _wrap_load_module(self, method: Any) -> Any: def load_module(fullname: str) -> ModuleType: assert fullname == self.old_module_name, ( f"DeprecatedModuleLoader for {self.old_module_name} was asked to " f"load {fullname}" ) if self.new_module_name in sys.modules: sys.modules[self.old_module_name] = sys.modules[self.new_module_name] return sys.modules[self.old_module_name] method(self.new_module_name) assert self.new_module_name in sys.modules, ( f"Wrapped loader {self.loader} was " f"expected to insert " f"{self.new_module_name} in sys.modules " f"but it did not." ) sys.modules[self.old_module_name] = sys.modules[self.new_module_name] return sys.modules[self.old_module_name] return load_module def _wrap_exec_module(self, method: Any) -> Any: def exec_module(module: ModuleType) -> None: assert module.__name__ == self.old_module_name, ( f"DeprecatedModuleLoader for {self.old_module_name} was asked to " f"load {module.__name__}" ) # check for new_module whether it was loaded if self.new_module_name in sys.modules: # found it - no need to load the module again sys.modules[self.old_module_name] = sys.modules[self.new_module_name] return # now we know we have to initialize the module sys.modules[self.old_module_name] = module sys.modules[self.new_module_name] = module try: return method(module) except BaseException: # if there's an error, we atomically remove both del sys.modules[self.new_module_name] del sys.modules[self.old_module_name] raise return exec_module def _is_internal(filename: str) -> bool: """Returns whether filename is internal to python. This is similar to how the built-in warnings module differentiates frames from internal modules. It is specific to CPython - see https://github.com/python/cpython/blob/41ec17e45d54473d32f543396293256f1581e44d/Lib/warnings.py#L275. """ return 'importlib' in filename and '_bootstrap' in filename _warned: Set[str] = set() def _deduped_module_warn_or_error(old_module_name, new_module_name, deadline): if old_module_name in _warned: return _warned.add(old_module_name) _warn_or_error( f"{old_module_name} was used but is deprecated.\n " f"it will be removed in cirq {deadline}.\n " f"Use {new_module_name} instead.\n", ) class DeprecatedModuleFinder(importlib.abc.MetaPathFinder): """A module finder to handle deprecated module references. It sends a deprecation warning when a deprecated module is asked to be found. It is meant to be used as a wrapper around existing MetaPathFinder instances. Args: finder: the finder to wrap. new_module_name: the new module's fully qualified name old_module_name: the deprecated module's fully qualified name deadline: the deprecation deadline """ def __init__( self, finder: Any, new_module_name: str, old_module_name: str, deadline: str, ): """An aliasing module finder that uses an existing module finder to find a python module spec and intercept the execution of matching modules. """ self.finder = finder self.new_module_name = new_module_name self.old_module_name = old_module_name self.deadline = deadline # to cater for metadata path finders # https://docs.python.org/3/library/importlib.metadata.html#extending-the-search-algorithm if hasattr(finder, "find_distributions"): def find_distributions(context): return self.finder.find_distributions(context) self.find_distributions = find_distributions if hasattr(finder, "invalidate_caches"): def invalidate_caches() -> None: return self.finder.invalidate_caches() # mypy#2427 self.invalidate_caches = invalidate_caches # type: ignore def find_spec(self, fullname: str, path: Any = None, target: Any = None) -> Any: """Finds the specification of a module. This is an implementation of the importlib.abc.MetaPathFinder.find_spec method. See https://docs.python.org/3/library/importlib.html#importlib.abc.MetaPathFinder. Args: fullname: name of the module. path: if presented, this is the parent module's submodule search path. target: When passed in, target is a module object that the finder may use to make a more educated guess about what spec to return. We don't use it here, just pass it along to the wrapped finder. """ if fullname != self.old_module_name and not fullname.startswith(self.old_module_name + "."): # if we are not interested in it, then just pass through to the wrapped finder return self.finder.find_spec(fullname, path, target) # warn for deprecation _deduped_module_warn_or_error(self.old_module_name, self.new_module_name, self.deadline) new_fullname = self.new_module_name + fullname[len(self.old_module_name) :] # find the corresponding spec in the new structure if fullname == self.old_module_name: # this is the first time the deprecated module is being found # which means that the new parent needs to be found first and under # the new parent's path, we should be able to find the new name of # the deprecated module # this code is heavily inspired by importlib.util.find_spec parent_name = new_fullname.rpartition('.')[0] if parent_name: parent = __import__(parent_name, fromlist=['__path__']) # note that compared to importlib.util.find_spec we don't handle # AttributeError here because it is not expected to happen in case # of a DeprecatedModuleLoader - the new parent should exist and be # a proper package parent_path = parent.__path__ else: parent_path = None spec = self.finder.find_spec(new_fullname, parent_path, None) else: # we are finding a submodule of the parent of the deprecated module, # which means that the parent was already found, and thus, `path` is # correctly pointing to the module's parent in the new hierarchy spec = self.finder.find_spec( new_fullname, path=path, target=target, ) # if the spec exists, return the DeprecatedModuleLoader that will do the loading as well # as set the alias(es) in sys.modules as necessary if spec is not None: # change back the name to the deprecated module name spec.name = fullname # some loaders do a check to ensure the module's name is the same # as the loader was created for if getattr(spec.loader, "name", None) == new_fullname: setattr(spec.loader, "name", fullname) spec.loader = DeprecatedModuleLoader(spec.loader, fullname, new_fullname) return spec def deprecated_submodule( *, new_module_name: str, old_parent: str, old_child: str, deadline: str, create_attribute: bool ): """Creates a deprecated module reference recursively for a module. For `new_module_name` (e.g. cirq_google) creates an alias (e.g cirq.google) in Python's module cache. It also recursively checks for the already imported submodules (e.g. cirq_google.api) and creates the alias for them too (e.g. cirq.google.api). With this method it is possible to create an alias that really looks like a module, e.g you can do things like `from cirq.google import api` - which would be otherwise impossible. Note that this method will execute `new_module_name` in order to ensure that it is in the module cache. Args: new_module_name: absolute module name for the new module old_parent: the current module that had the original submodule old_child: the submodule that is being relocated create_attribute: if True, the submodule will be added as a deprecated attribute to the old_parent module Returns: None """ _validate_deadline(deadline) old_module_name = f"{old_parent}.{old_child}" if create_attribute: new_module = importlib.import_module(new_module_name) _setup_deprecated_submodule_attribute( new_module_name, old_parent, old_child, deadline, new_module ) def wrap(finder: Any) -> Any: if not hasattr(finder, 'find_spec'): return finder # this is just to make mypy not complain about the type of new_module_spec being Optional return DeprecatedModuleFinder(finder, new_module_name, old_module_name, deadline) sys.meta_path = [wrap(finder) for finder in sys.meta_path] def _setup_deprecated_submodule_attribute( new_module_name: str, old_parent: str, old_child: str, deadline: str, new_module: ModuleType ): parent_module = sys.modules[old_parent] setattr(parent_module, old_child, new_module) class Wrapped(ModuleType): __dict__ = parent_module.__dict__ def __getattr__(self, name): if name == old_child: _deduped_module_warn_or_error( f"{old_parent}.{old_child}", new_module_name, deadline ) return getattr(parent_module, name) sys.modules[old_parent] = Wrapped(parent_module.__name__, parent_module.__doc__)
#!/usr/bin/env python3 import os import sys import time from collections import defaultdict from typing import Any from itertools import zip_longest import cereal.messaging as messaging from cereal.visionipc import VisionIpcServer, VisionStreamType from common.spinner import Spinner from common.timeout import Timeout from common.transformations.camera import get_view_frame_from_road_frame, tici_f_frame_size, tici_d_frame_size from selfdrive.hardware import PC from selfdrive.manager.process_config import managed_processes from selfdrive.test.openpilotci import BASE_URL, get_url from selfdrive.test.process_replay.compare_logs import compare_logs, save_log from selfdrive.test.process_replay.test_processes import format_diff from selfdrive.version import get_commit from tools.lib.framereader import FrameReader from tools.lib.logreader import LogReader TEST_ROUTE = "4cf7a6ad03080c90|2021-09-29--13-46-36" SEGMENT = 0 MAX_FRAMES = 20 if PC else 1300 SEND_EXTRA_INPUTS = bool(os.getenv("SEND_EXTRA_INPUTS", "0")) VIPC_STREAM = {"roadCameraState": VisionStreamType.VISION_STREAM_ROAD, "driverCameraState": VisionStreamType.VISION_STREAM_DRIVER, "wideRoadCameraState": VisionStreamType.VISION_STREAM_WIDE_ROAD} def get_log_fn(ref_commit, test_route): return f"{test_route}_model_tici_{ref_commit}.bz2" def replace_calib(msg, calib): msg = msg.as_builder() if calib is not None: msg.liveCalibration.extrinsicMatrix = get_view_frame_from_road_frame(*calib, 1.22).flatten().tolist() return msg def model_replay(lr, frs): if not PC: spinner = Spinner() spinner.update("starting model replay") else: spinner = None vipc_server = VisionIpcServer("camerad") vipc_server.create_buffers(VisionStreamType.VISION_STREAM_ROAD, 40, False, *(tici_f_frame_size)) vipc_server.create_buffers(VisionStreamType.VISION_STREAM_DRIVER, 40, False, *(tici_d_frame_size)) vipc_server.create_buffers(VisionStreamType.VISION_STREAM_WIDE_ROAD, 40, False, *(tici_f_frame_size)) vipc_server.start_listener() sm = messaging.SubMaster(['modelV2', 'driverStateV2']) pm = messaging.PubMaster(['roadCameraState', 'wideRoadCameraState', 'driverCameraState', 'liveCalibration', 'lateralPlan']) try: managed_processes['modeld'].start() managed_processes['dmonitoringmodeld'].start() time.sleep(5) sm.update(1000) log_msgs = [] last_desire = None recv_cnt = defaultdict(int) frame_idxs = defaultdict(int) # init modeld with valid calibration cal_msgs = [msg for msg in lr if msg.which() == "liveCalibration"] for _ in range(5): pm.send(cal_msgs[0].which(), cal_msgs[0].as_builder()) time.sleep(0.1) msgs = defaultdict(list) for msg in lr: msgs[msg.which()].append(msg) for cam_msgs in zip_longest(msgs['roadCameraState'], msgs['wideRoadCameraState'], msgs['driverCameraState']): # need a pair of road/wide msgs if None in (cam_msgs[0], cam_msgs[1]): break for msg in cam_msgs: if msg is None: continue if SEND_EXTRA_INPUTS: if msg.which() == "liveCalibration": last_calib = list(msg.liveCalibration.rpyCalib) pm.send(msg.which(), replace_calib(msg, last_calib)) elif msg.which() == "lateralPlan": last_desire = msg.lateralPlan.desire dat = messaging.new_message('lateralPlan') dat.lateralPlan.desire = last_desire pm.send('lateralPlan', dat) if msg.which() in VIPC_STREAM: msg = msg.as_builder() camera_state = getattr(msg, msg.which()) img = frs[msg.which()].get(frame_idxs[msg.which()], pix_fmt="nv12")[0] frame_idxs[msg.which()] += 1 # send camera state and frame camera_state.frameId = frame_idxs[msg.which()] pm.send(msg.which(), msg) vipc_server.send(VIPC_STREAM[msg.which()], img.flatten().tobytes(), camera_state.frameId, camera_state.timestampSof, camera_state.timestampEof) recv = None if msg.which() in ('roadCameraState', 'wideRoadCameraState'): if min(frame_idxs['roadCameraState'], frame_idxs['wideRoadCameraState']) > recv_cnt['modelV2']: recv = "modelV2" elif msg.which() == 'driverCameraState': recv = "driverStateV2" # wait for a response with Timeout(15, f"timed out waiting for {recv}"): if recv: recv_cnt[recv] += 1 log_msgs.append(messaging.recv_one(sm.sock[recv])) if spinner: spinner.update("replaying models: road %d/%d, driver %d/%d" % (frame_idxs['roadCameraState'], frs['roadCameraState'].frame_count, frame_idxs['driverCameraState'], frs['driverCameraState'].frame_count)) if any(frame_idxs[c] >= frs[c].frame_count for c in frame_idxs.keys()) or frame_idxs['roadCameraState'] == MAX_FRAMES: break else: print(f'Received {frame_idxs['roadCameraState']} frames') finally: if spinner: spinner.close() managed_processes['modeld'].stop() managed_processes['dmonitoringmodeld'].stop() return log_msgs if __name__ == "__main__": update = "--update" in sys.argv replay_dir = os.path.dirname(os.path.abspath(__file__)) ref_commit_fn = os.path.join(replay_dir, "model_replay_ref_commit") # load logs lr = list(LogReader(get_url(TEST_ROUTE, SEGMENT))) frs = { 'roadCameraState': FrameReader(get_url(TEST_ROUTE, SEGMENT, log_type="fcamera")), 'driverCameraState': FrameReader(get_url(TEST_ROUTE, SEGMENT, log_type="dcamera")), 'wideRoadCameraState': FrameReader(get_url(TEST_ROUTE, SEGMENT, log_type="ecamera")) } # run replay log_msgs = model_replay(lr, frs) # get diff failed = False if not update: with open(ref_commit_fn) as f: ref_commit = f.read().strip() log_fn = get_log_fn(ref_commit, TEST_ROUTE) try: cmp_log = list(LogReader(BASE_URL + log_fn))[:2*MAX_FRAMES] ignore = [ 'logMonoTime', 'modelV2.frameDropPerc', 'modelV2.modelExecutionTime', 'driverStateV2.modelExecutionTime', 'driverStateV2.dspExecutionTime' ] # TODO this tolerence is absurdly large tolerance = 5e-1 if PC else None results: Any = {TEST_ROUTE: {}} results[TEST_ROUTE]["models"] = compare_logs(cmp_log, log_msgs, tolerance=tolerance, ignore_fields=ignore) diff1, diff2, failed = format_diff(results, ref_commit) print(diff2) print('-------------\n'*5) print(diff1) with open("model_diff.txt", "w") as f: f.write(diff2) except Exception as e: print(str(e)) failed = True # upload new refs if (update or failed) and not PC: from selfdrive.test.openpilotci import upload_file print("Uploading new refs") new_commit = get_commit() log_fn = get_log_fn(new_commit, TEST_ROUTE) save_log(log_fn, log_msgs) try: upload_file(log_fn, os.path.basename(log_fn)) except Exception as e: print("failed to upload", e) with open(ref_commit_fn, 'w') as f: f.write(str(new_commit)) print("\n\nNew ref commit: ", new_commit) sys.exit(int(failed))
#!/usr/bin/env python3 import os import sys import time from collections import defaultdict from typing import Any from itertools import zip_longest import cereal.messaging as messaging from cereal.visionipc import VisionIpcServer, VisionStreamType from common.spinner import Spinner from common.timeout import Timeout from common.transformations.camera import get_view_frame_from_road_frame, tici_f_frame_size, tici_d_frame_size from selfdrive.hardware import PC from selfdrive.manager.process_config import managed_processes from selfdrive.test.openpilotci import BASE_URL, get_url from selfdrive.test.process_replay.compare_logs import compare_logs, save_log from selfdrive.test.process_replay.test_processes import format_diff from selfdrive.version import get_commit from tools.lib.framereader import FrameReader from tools.lib.logreader import LogReader TEST_ROUTE = "4cf7a6ad03080c90|2021-09-29--13-46-36" SEGMENT = 0 MAX_FRAMES = 20 if PC else 1300 SEND_EXTRA_INPUTS = bool(os.getenv("SEND_EXTRA_INPUTS", "0")) VIPC_STREAM = {"roadCameraState": VisionStreamType.VISION_STREAM_ROAD, "driverCameraState": VisionStreamType.VISION_STREAM_DRIVER, "wideRoadCameraState": VisionStreamType.VISION_STREAM_WIDE_ROAD} def get_log_fn(ref_commit, test_route): return f"{test_route}_model_tici_{ref_commit}.bz2" def replace_calib(msg, calib): msg = msg.as_builder() if calib is not None: msg.liveCalibration.extrinsicMatrix = get_view_frame_from_road_frame(*calib, 1.22).flatten().tolist() return msg def model_replay(lr, frs): if not PC: spinner = Spinner() spinner.update("starting model replay") else: spinner = None vipc_server = VisionIpcServer("camerad") vipc_server.create_buffers(VisionStreamType.VISION_STREAM_ROAD, 40, False, *(tici_f_frame_size)) vipc_server.create_buffers(VisionStreamType.VISION_STREAM_DRIVER, 40, False, *(tici_d_frame_size)) vipc_server.create_buffers(VisionStreamType.VISION_STREAM_WIDE_ROAD, 40, False, *(tici_f_frame_size)) vipc_server.start_listener() sm = messaging.SubMaster(['modelV2', 'driverStateV2']) pm = messaging.PubMaster(['roadCameraState', 'wideRoadCameraState', 'driverCameraState', 'liveCalibration', 'lateralPlan']) try: managed_processes['modeld'].start() managed_processes['dmonitoringmodeld'].start() time.sleep(5) sm.update(1000) log_msgs = [] last_desire = None recv_cnt = defaultdict(int) frame_idxs = defaultdict(int) # init modeld with valid calibration cal_msgs = [msg for msg in lr if msg.which() == "liveCalibration"] for _ in range(5): pm.send(cal_msgs[0].which(), cal_msgs[0].as_builder()) time.sleep(0.1) msgs = defaultdict(list) for msg in lr: msgs[msg.which()].append(msg) for cam_msgs in zip_longest(msgs['roadCameraState'], msgs['wideRoadCameraState'], msgs['driverCameraState']): # need a pair of road/wide msgs if None in (cam_msgs[0], cam_msgs[1]): break for msg in cam_msgs: if msg is None: continue if SEND_EXTRA_INPUTS: if msg.which() == "liveCalibration": last_calib = list(msg.liveCalibration.rpyCalib) pm.send(msg.which(), replace_calib(msg, last_calib)) elif msg.which() == "lateralPlan": last_desire = msg.lateralPlan.desire dat = messaging.new_message('lateralPlan') dat.lateralPlan.desire = last_desire pm.send('lateralPlan', dat) if msg.which() in VIPC_STREAM: msg = msg.as_builder() camera_state = getattr(msg, msg.which()) img = frs[msg.which()].get(frame_idxs[msg.which()], pix_fmt="nv12")[0] frame_idxs[msg.which()] += 1 # send camera state and frame camera_state.frameId = frame_idxs[msg.which()] pm.send(msg.which(), msg) vipc_server.send(VIPC_STREAM[msg.which()], img.flatten().tobytes(), camera_state.frameId, camera_state.timestampSof, camera_state.timestampEof) recv = None if msg.which() in ('roadCameraState', 'wideRoadCameraState'): if min(frame_idxs['roadCameraState'], frame_idxs['wideRoadCameraState']) > recv_cnt['modelV2']: recv = "modelV2" elif msg.which() == 'driverCameraState': recv = "driverStateV2" # wait for a response with Timeout(15, f"timed out waiting for {recv}"): if recv: recv_cnt[recv] += 1 log_msgs.append(messaging.recv_one(sm.sock[recv])) if spinner: spinner.update("replaying models: road %d/%d, driver %d/%d" % (frame_idxs['roadCameraState'], frs['roadCameraState'].frame_count, frame_idxs['driverCameraState'], frs['driverCameraState'].frame_count)) if any(frame_idxs[c] >= frs[c].frame_count for c in frame_idxs.keys()) or frame_idxs['roadCameraState'] == MAX_FRAMES: break else: print(f'Received {frame_idxs["roadCameraState"]} frames') finally: if spinner: spinner.close() managed_processes['modeld'].stop() managed_processes['dmonitoringmodeld'].stop() return log_msgs if __name__ == "__main__": update = "--update" in sys.argv replay_dir = os.path.dirname(os.path.abspath(__file__)) ref_commit_fn = os.path.join(replay_dir, "model_replay_ref_commit") # load logs lr = list(LogReader(get_url(TEST_ROUTE, SEGMENT))) frs = { 'roadCameraState': FrameReader(get_url(TEST_ROUTE, SEGMENT, log_type="fcamera")), 'driverCameraState': FrameReader(get_url(TEST_ROUTE, SEGMENT, log_type="dcamera")), 'wideRoadCameraState': FrameReader(get_url(TEST_ROUTE, SEGMENT, log_type="ecamera")) } # run replay log_msgs = model_replay(lr, frs) # get diff failed = False if not update: with open(ref_commit_fn) as f: ref_commit = f.read().strip() log_fn = get_log_fn(ref_commit, TEST_ROUTE) try: cmp_log = list(LogReader(BASE_URL + log_fn))[:2*MAX_FRAMES] ignore = [ 'logMonoTime', 'modelV2.frameDropPerc', 'modelV2.modelExecutionTime', 'driverStateV2.modelExecutionTime', 'driverStateV2.dspExecutionTime' ] # TODO this tolerence is absurdly large tolerance = 5e-1 if PC else None results: Any = {TEST_ROUTE: {}} results[TEST_ROUTE]["models"] = compare_logs(cmp_log, log_msgs, tolerance=tolerance, ignore_fields=ignore) diff1, diff2, failed = format_diff(results, ref_commit) print(diff2) print('-------------\n'*5) print(diff1) with open("model_diff.txt", "w") as f: f.write(diff2) except Exception as e: print(str(e)) failed = True # upload new refs if (update or failed) and not PC: from selfdrive.test.openpilotci import upload_file print("Uploading new refs") new_commit = get_commit() log_fn = get_log_fn(new_commit, TEST_ROUTE) save_log(log_fn, log_msgs) try: upload_file(log_fn, os.path.basename(log_fn)) except Exception as e: print("failed to upload", e) with open(ref_commit_fn, 'w') as f: f.write(str(new_commit)) print("\n\nNew ref commit: ", new_commit) sys.exit(int(failed))
import os import logging import configparser import sys import smtplib import csv import time from pycoingecko import CoinGeckoAPI from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart # ------------------------------------------------------------------ # Logging Setup # ------------------------------------------------------------------ logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(lineno)d - %(message)s', datefmt='%d-%m-%y %H:%M:%S') file_handler = logging.FileHandler("settings\\logs.log", encoding='utf8') file_handler.setFormatter(formatter) logger.addHandler(file_handler) # ------------------------------------------------------------------ # Config Setup config = configparser.RawConfigParser() configFilePath = r"settings/config.txt" config.read(configFilePath, encoding="utf-8") # Global Variables geckoAPI = CoinGeckoAPI() def get_coins(): """ Gets user inputted coins and adds them to a csv file. Only gets run on the first run of the program. If the coins.csv file isn't found this function will be run It asks the user to input the names of the coins they want to track, splitting them up by commas It then graps each coin and makes sure that the coin can be found on CoinGecko If not an error is returned Then adds all coins to a csv and writes them to file """ print("\nPlease enter the FULL NAME of the coins you want to get the price of (if getting multiple, seperate them with commas):") coins = input().split(",") for i in range(len(coins)): coins[i] = coins[i].strip() response = geckoAPI.get_price(ids=coins[i], vs_currencies=config.get("CONFIG", "VS_CURRENCY")) if len(response) == 0: print(coins[i] + " doesn't exist on CoinGecko, please try again!") sys.exit() with open("settings/coins.csv", "w") as file: csvwriter = csv.writer(file) csvwriter.writerow(coins) def get_crypto_price(): """ Reads the coins and returns the price and 24hr change data back to the main function First reads the coins from the coins.csv It gets the price against the defined vs Currency and the 24hr change Adds all the necessary info to a dictionary and returns it to the main function Any errors get added to the log files Raises ------ TypeError Raised when syntax is wrong in code KeyError Raised when the coin name in the csv is different than the name returned from CoinGecko; happens normally with coins with a space ie. Shiba Inu Exception Just there to catch any extra exceptions that I may have missed """ crypto_list = [] try: with open("settings/coins.csv", "r") as file: reader = csv.reader(file) coins = next(reader) for crypto in coins: response = geckoAPI.get_price(ids=crypto, vs_currencies=config.get("CONFIG", "VS_CURRENCY"), include_24hr_change=True,) listings = { "coin": crypto, "price": "{:,}".format(response[crypto.replace(" ", "")][config.get("CONFIG", "VS_CURRENCY").lower()]), "change": round(response[crypto.replace(" ", "")][config.get("CONFIG", "VS_CURRENCY").lower() + "_24h_change"], 2) } crypto_list.append(listings) return crypto_list except TypeError as e: logger.error("Type Error: ", e) except KeyError as e: logger.error("Key Error for: ", e) except Exception as e: logger.erorr("General Error: ", e) def send_email(listings): """ Sends an email to the user with the data for each coin Sets up the SMTP connection to the user's email with the details given in config.txt Creates a string called msg Loops through the listings and adds the details to the msg Sends that finished message to the user via email Parameters ----------- listings : list, required The data for each coin, their price and 24hr change Raises ------ Exception Raised when something goes wrong with the email being sent. Output gets sent to the logger """ try: email_content = "Here is your crypto updates:" for i in range(len(listings)): # msg += f'\n{listings[i]['coin']} ->\tPrice:\t{listings[i]['price']} {config.get('CONFIG', 'VS_CURRENCY')}\tChange:\t{listings[i]['change']}%' email_content += "\n" + listings[i]["coin"].upper() + " - >Price: " + str(listings[i]["price"]) + config.get("CONFIG", "VS_CURRENCY") + "-> Change: " + str(listings[i]["change"]) + "%" smtp = smtplib.SMTP(config.get('CONFIG', 'SMTP_SERVER'), int(config.get('CONFIG', 'SMTP_PORT'))) smtp.ehlo() smtp.starttls() smtp.login(config.get('CONFIG', 'SMTP_SENDING_EMAIL'), config.get('CONFIG', 'SMTP_PASSWORD')) message = MIMEMultipart() message["Subject"] = "Crypto Price Updates" message.attach(MIMEText(email_content)) smtp.sendmail( from_addr=config.get('CONFIG', 'SMTP_SENDING_EMAIL'), to_addrs=config.get('CONFIG', 'SMTP_RECEIVING_EMAIL'), msg=message.as_string() ) logger.info("Email successfully sent to " + config.get('CONFIG', 'SMTP_RECEIVING_EMAIL')) except Exception as e: logger.error(e) finally: smtp.quit() def main(): if not os.path.isfile("settings/coins.csv"): get_coins() # infinite loop while True: pricelistings = get_crypto_price() send_email(pricelistings) time.sleep(config.get("CONFIG", "TIME_INTERVAL")) if __name__ == '__main__': main()
import os import logging import configparser import sys import smtplib import csv import time from pycoingecko import CoinGeckoAPI from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart # ------------------------------------------------------------------ # Logging Setup # ------------------------------------------------------------------ logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(lineno)d - %(message)s', datefmt='%d-%m-%y %H:%M:%S') file_handler = logging.FileHandler("settings\\logs.log", encoding='utf8') file_handler.setFormatter(formatter) logger.addHandler(file_handler) # ------------------------------------------------------------------ # Config Setup config = configparser.RawConfigParser() configFilePath = r"settings/config.txt" config.read(configFilePath, encoding="utf-8") # Global Variables geckoAPI = CoinGeckoAPI() def get_coins(): """ Gets user inputted coins and adds them to a csv file. Only gets run on the first run of the program. If the coins.csv file isn't found this function will be run It asks the user to input the names of the coins they want to track, splitting them up by commas It then graps each coin and makes sure that the coin can be found on CoinGecko If not an error is returned Then adds all coins to a csv and writes them to file """ print("\nPlease enter the FULL NAME of the coins you want to get the price of (if getting multiple, seperate them with commas):") coins = input().split(",") for i in range(len(coins)): coins[i] = coins[i].strip() response = geckoAPI.get_price(ids=coins[i], vs_currencies=config.get("CONFIG", "VS_CURRENCY")) if len(response) == 0: print(coins[i] + " doesn't exist on CoinGecko, please try again!") sys.exit() with open("settings/coins.csv", "w") as file: csvwriter = csv.writer(file) csvwriter.writerow(coins) def get_crypto_price(): """ Reads the coins and returns the price and 24hr change data back to the main function First reads the coins from the coins.csv It gets the price against the defined vs Currency and the 24hr change Adds all the necessary info to a dictionary and returns it to the main function Any errors get added to the log files Raises ------ TypeError Raised when syntax is wrong in code KeyError Raised when the coin name in the csv is different than the name returned from CoinGecko; happens normally with coins with a space ie. Shiba Inu Exception Just there to catch any extra exceptions that I may have missed """ crypto_list = [] try: with open("settings/coins.csv", "r") as file: reader = csv.reader(file) coins = next(reader) for crypto in coins: response = geckoAPI.get_price(ids=crypto, vs_currencies=config.get("CONFIG", "VS_CURRENCY"), include_24hr_change=True,) listings = { "coin": crypto, "price": "{:,}".format(response[crypto.replace(" ", "")][config.get("CONFIG", "VS_CURRENCY").lower()]), "change": round(response[crypto.replace(" ", "")][config.get("CONFIG", "VS_CURRENCY").lower() + "_24h_change"], 2) } crypto_list.append(listings) return crypto_list except TypeError as e: logger.error("Type Error: ", e) except KeyError as e: logger.error("Key Error for: ", e) except Exception as e: logger.erorr("General Error: ", e) def send_email(listings): """ Sends an email to the user with the data for each coin Sets up the SMTP connection to the user's email with the details given in config.txt Creates a string called msg Loops through the listings and adds the details to the msg Sends that finished message to the user via email Parameters ----------- listings : list, required The data for each coin, their price and 24hr change Raises ------ Exception Raised when something goes wrong with the email being sent. Output gets sent to the logger """ try: email_content = "Here is your crypto updates:" for i in range(len(listings)): # msg += f'\n{listings[i]["coin"]} ->\tPrice:\t{listings[i]["price"]} {config.get("CONFIG", "VS_CURRENCY")}\tChange:\t{listings[i]["change"]}%' email_content += "\n" + listings[i]["coin"].upper() + " - >Price: " + str(listings[i]["price"]) + config.get("CONFIG", "VS_CURRENCY") + "-> Change: " + str(listings[i]["change"]) + "%" smtp = smtplib.SMTP(config.get('CONFIG', 'SMTP_SERVER'), int(config.get('CONFIG', 'SMTP_PORT'))) smtp.ehlo() smtp.starttls() smtp.login(config.get('CONFIG', 'SMTP_SENDING_EMAIL'), config.get('CONFIG', 'SMTP_PASSWORD')) message = MIMEMultipart() message["Subject"] = "Crypto Price Updates" message.attach(MIMEText(email_content)) smtp.sendmail( from_addr=config.get('CONFIG', 'SMTP_SENDING_EMAIL'), to_addrs=config.get('CONFIG', 'SMTP_RECEIVING_EMAIL'), msg=message.as_string() ) logger.info("Email successfully sent to " + config.get('CONFIG', 'SMTP_RECEIVING_EMAIL')) except Exception as e: logger.error(e) finally: smtp.quit() def main(): if not os.path.isfile("settings/coins.csv"): get_coins() # infinite loop while True: pricelistings = get_crypto_price() send_email(pricelistings) time.sleep(config.get("CONFIG", "TIME_INTERVAL")) if __name__ == '__main__': main()
import os import subprocess from os.path import join from nerblackbox.modules.datasets.formatter.base_formatter import BaseFormatter from nerblackbox.modules.utils.env_variable import env_variable class SICFormatter(BaseFormatter): def __init__(self): ner_dataset = "sic" ner_tag_list = [ "person", "animal", "myth", "place", "inst", "product", "work", "event", "other", ] super().__init__(ner_dataset, ner_tag_list) #################################################################################################################### # ABSTRACT BASE METHODS #################################################################################################################### def get_data(self, verbose: bool): """ I: get data ---------- :param verbose: [bool] :return: - """ bash_cmds = [ f"mkdir {env_variable("DIR_DATASETS")}/_sic", f"curl -o {env_variable("DIR_DATASETS")}/_sic/sic.zip " "https://www.ling.su.se/polopoly_fs/1.99145.1380811903\!/menu/standard/file/sic.zip", f"cd {env_variable("DIR_DATASETS")}/_sic && unzip -o sic.zip", f"mkdir {env_variable("DIR_DATASETS")}/sic/raw_data", f"mv {env_variable("DIR_DATASETS")}/_sic/sic/annotated/* {env_variable("DIR_DATASETS")}/sic/raw_data", f"rm -r {env_variable("DIR_DATASETS")}/_sic", f"cat {env_variable("DIR_DATASETS")}/sic/raw_data/*.conll " f"> {env_variable("DIR_DATASETS")}/sic/sic-train.conll", ] for bash_cmd in bash_cmds: if verbose: print(bash_cmd) try: subprocess.run(bash_cmd, shell=True, check=True) except subprocess.CalledProcessError as e: print(e) def create_ner_tag_mapping(self): """ II: customize ner_training tag mapping if wanted ------------------------------------------------ :return: ner_tag_mapping: [dict] w/ keys = tags in original data, values = tags in formatted data """ return dict() def format_data(self): """ III: format data ---------------- :return: - """ for phase in ["train"]: rows = self._read_original_file(phase) self._write_formatted_csv(phase, rows) def resplit_data(self, val_fraction: float): """ IV: resplit data ---------------- :param val_fraction: [float] :return: - """ # train -> train, val, test df_train_val_test = self._read_formatted_csvs(["train"]) df_train_val, df_test = self._split_off_validation_set( df_train_val_test, val_fraction ) df_train, df_val = self._split_off_validation_set(df_train_val, val_fraction) self._write_final_csv("train", df_train) self._write_final_csv("val", df_val) self._write_final_csv("test", df_test) #################################################################################################################### # HELPER: READ ORIGINAL #################################################################################################################### def _read_original_file(self, phase): """ III: format data --------------------------------------------- :param phase: [str] 'train' or 'test' :return: _rows: [list] of [list] of [str], e.g. [[], ['Inger', 'PER'], ['säger', '0'], ..] """ file_name = { "train": "sic-train.conll", } file_path_original = join(self.dataset_path, file_name[phase]) _rows = list() if os.path.isfile(file_path_original): with open(file_path_original) as f: for i, row in enumerate(f.readlines()): _rows.append(row.strip().split()) print(f"\n> read {file_path_original}") else: raise Exception(f"> original file {file_path_original} could not be found.") _rows = [ [row[1], self.transform_tags(row[-3], row[-2])] if len(row) > 0 and row[-3] not in ["_", "U"] # filter out "_-_" and "_-person" (bugs in SIC dataset) else list() for row in _rows ] return _rows @staticmethod def transform_tags(bio, tag): """ :param bio: [str] 'O', 'B', 'I' :param tag: [str] '_', 'person', .. :return: transformed tag: [str], e.g. 'O', 'B-person', .. """ if bio == "O": return "O" else: return f"{bio}-{tag}"
import os import subprocess from os.path import join from nerblackbox.modules.datasets.formatter.base_formatter import BaseFormatter from nerblackbox.modules.utils.env_variable import env_variable class SICFormatter(BaseFormatter): def __init__(self): ner_dataset = "sic" ner_tag_list = [ "person", "animal", "myth", "place", "inst", "product", "work", "event", "other", ] super().__init__(ner_dataset, ner_tag_list) #################################################################################################################### # ABSTRACT BASE METHODS #################################################################################################################### def get_data(self, verbose: bool): """ I: get data ---------- :param verbose: [bool] :return: - """ bash_cmds = [ f"mkdir {env_variable('DIR_DATASETS')}/_sic", f"curl -o {env_variable('DIR_DATASETS')}/_sic/sic.zip " "https://www.ling.su.se/polopoly_fs/1.99145.1380811903\!/menu/standard/file/sic.zip", f"cd {env_variable('DIR_DATASETS')}/_sic && unzip -o sic.zip", f"mkdir {env_variable('DIR_DATASETS')}/sic/raw_data", f"mv {env_variable('DIR_DATASETS')}/_sic/sic/annotated/* {env_variable('DIR_DATASETS')}/sic/raw_data", f"rm -r {env_variable('DIR_DATASETS')}/_sic", f"cat {env_variable('DIR_DATASETS')}/sic/raw_data/*.conll " f"> {env_variable('DIR_DATASETS')}/sic/sic-train.conll", ] for bash_cmd in bash_cmds: if verbose: print(bash_cmd) try: subprocess.run(bash_cmd, shell=True, check=True) except subprocess.CalledProcessError as e: print(e) def create_ner_tag_mapping(self): """ II: customize ner_training tag mapping if wanted ------------------------------------------------ :return: ner_tag_mapping: [dict] w/ keys = tags in original data, values = tags in formatted data """ return dict() def format_data(self): """ III: format data ---------------- :return: - """ for phase in ["train"]: rows = self._read_original_file(phase) self._write_formatted_csv(phase, rows) def resplit_data(self, val_fraction: float): """ IV: resplit data ---------------- :param val_fraction: [float] :return: - """ # train -> train, val, test df_train_val_test = self._read_formatted_csvs(["train"]) df_train_val, df_test = self._split_off_validation_set( df_train_val_test, val_fraction ) df_train, df_val = self._split_off_validation_set(df_train_val, val_fraction) self._write_final_csv("train", df_train) self._write_final_csv("val", df_val) self._write_final_csv("test", df_test) #################################################################################################################### # HELPER: READ ORIGINAL #################################################################################################################### def _read_original_file(self, phase): """ III: format data --------------------------------------------- :param phase: [str] 'train' or 'test' :return: _rows: [list] of [list] of [str], e.g. [[], ['Inger', 'PER'], ['säger', '0'], ..] """ file_name = { "train": "sic-train.conll", } file_path_original = join(self.dataset_path, file_name[phase]) _rows = list() if os.path.isfile(file_path_original): with open(file_path_original) as f: for i, row in enumerate(f.readlines()): _rows.append(row.strip().split()) print(f"\n> read {file_path_original}") else: raise Exception(f"> original file {file_path_original} could not be found.") _rows = [ [row[1], self.transform_tags(row[-3], row[-2])] if len(row) > 0 and row[-3] not in ["_", "U"] # filter out "_-_" and "_-person" (bugs in SIC dataset) else list() for row in _rows ] return _rows @staticmethod def transform_tags(bio, tag): """ :param bio: [str] 'O', 'B', 'I' :param tag: [str] '_', 'person', .. :return: transformed tag: [str], e.g. 'O', 'B-person', .. """ if bio == "O": return "O" else: return f"{bio}-{tag}"
#usando dicionario d = {} d['Nome'] = str(input('Nome: ')).strip() d['Media'] = float(input(f'Media de {d['Nome']}: ')) if d['Media'] >= 7: d['Situação'] = 'Aprovado' elif 5 <= d['Media'] <= 7: d['Situação'] = 'Recuperação' else: d['Situação'] = 'Reprovado' print('=-' * 20) for k, v in d.items(): print(f' - {k} é igual a {v}')
#usando dicionario d = {} d['Nome'] = str(input('Nome: ')).strip() d['Media'] = float(input(f'Media de {d["Nome"]}: ')) if d['Media'] >= 7: d['Situação'] = 'Aprovado' elif 5 <= d['Media'] <= 7: d['Situação'] = 'Recuperação' else: d['Situação'] = 'Reprovado' print('=-' * 20) for k, v in d.items(): print(f' - {k} é igual a {v}')
''' Filters that determine whether a Locus meets a particular criteria. ''' # %% from antares_client._api.models import Locus from typing import Generator def apply( stream: Generator[Locus, None, None], *filters, debug=False, ): ''' Apply a series of filters to an iterable sequence of loci. @param stream Input sequence of loci. @param filters A sequence of filters you want to apply. If no filters is provided, then this function has no effect. @param debug If set True, then it will print out when each Locus gets filtered out. ''' if not debug: def validate(locus): for crit in filters: if not crit(locus): # if debug: # print( # f'locus {locus.locus_id} filtered out by {crit.__name__}' # ) return False return True for locus in stream: if validate(locus): yield locus else: def validate(locus): for f in filters: if not f(locus): counters[f] += 1 # if debug: # print( # f'locus {locus.locus_id} filtered out by {crit.__name__}' # ) return False counters['pass'] += 1 return True counters = dict() for f in filters: counters.setdefault(f, 0) counters.setdefault('pass', 0) for locus in stream: if validate(locus): yield locus print(('->'.join((f'{f.__name__}({counters[f]})' for f in filters))), '->', f'pass({counters['pass']})') return [counters[f] for f in filters] + [counters['pass']] # %% Meta-filters def logic_and(*fs): def composite_filter(locus: Locus) -> bool: for f in fs: if not f(locus): return False return True return composite_filter def logic_or(*fs): def composite_filter(locus: Locus) -> bool: for f in fs: if f(locus): return True return False return composite_filter def logic_not(f): def composite_filter(locus: Locus) -> bool: return not f(locus) return composite_filter # %% # Standard Filters. def date_range(max=200, min=0): from .analysis.lightcurve import get_date_range def date_range_filter(locus: Locus) -> bool: duration = get_date_range(locus.lightcurve) return min <= duration <= max return date_range_filter def lightcurve_datapoints(min=20, max=9e9): def lc_datapoints_filter(locus: Locus) -> bool: lc = locus.lightcurve return min <= len(lc) <= max return lc_datapoints_filter def snr_slope_cut(snr_max=0.3, slope_max=0.0025): "True if likely non-bogus. " from .analysis.simple_classification import snr_and_linear def snr_slope_filter(locus: Locus) -> bool: snr, slope = snr_and_linear(locus) return snr > snr_max or slope > slope_max return snr_slope_filter
''' Filters that determine whether a Locus meets a particular criteria. ''' # %% from antares_client._api.models import Locus from typing import Generator def apply( stream: Generator[Locus, None, None], *filters, debug=False, ): ''' Apply a series of filters to an iterable sequence of loci. @param stream Input sequence of loci. @param filters A sequence of filters you want to apply. If no filters is provided, then this function has no effect. @param debug If set True, then it will print out when each Locus gets filtered out. ''' if not debug: def validate(locus): for crit in filters: if not crit(locus): # if debug: # print( # f'locus {locus.locus_id} filtered out by {crit.__name__}' # ) return False return True for locus in stream: if validate(locus): yield locus else: def validate(locus): for f in filters: if not f(locus): counters[f] += 1 # if debug: # print( # f'locus {locus.locus_id} filtered out by {crit.__name__}' # ) return False counters['pass'] += 1 return True counters = dict() for f in filters: counters.setdefault(f, 0) counters.setdefault('pass', 0) for locus in stream: if validate(locus): yield locus print(('->'.join((f'{f.__name__}({counters[f]})' for f in filters))), '->', f'pass({counters["pass"]})') return [counters[f] for f in filters] + [counters['pass']] # %% Meta-filters def logic_and(*fs): def composite_filter(locus: Locus) -> bool: for f in fs: if not f(locus): return False return True return composite_filter def logic_or(*fs): def composite_filter(locus: Locus) -> bool: for f in fs: if f(locus): return True return False return composite_filter def logic_not(f): def composite_filter(locus: Locus) -> bool: return not f(locus) return composite_filter # %% # Standard Filters. def date_range(max=200, min=0): from .analysis.lightcurve import get_date_range def date_range_filter(locus: Locus) -> bool: duration = get_date_range(locus.lightcurve) return min <= duration <= max return date_range_filter def lightcurve_datapoints(min=20, max=9e9): def lc_datapoints_filter(locus: Locus) -> bool: lc = locus.lightcurve return min <= len(lc) <= max return lc_datapoints_filter def snr_slope_cut(snr_max=0.3, slope_max=0.0025): "True if likely non-bogus. " from .analysis.simple_classification import snr_and_linear def snr_slope_filter(locus: Locus) -> bool: snr, slope = snr_and_linear(locus) return snr > snr_max or slope > slope_max return snr_slope_filter
from copy import deepcopy from .types import ( Account, Collection, Comment, DirectMedia, DirectMessage, DirectResponse, DirectShortThread, DirectThread, Hashtag, Location, Media, MediaOembed, Resource, Story, StoryLink, StoryMention, User, UserShort, Usertag, ) from .utils import InstagramIdCodec, json_value MEDIA_TYPES_GQL = {"GraphImage": 1, "GraphVideo": 2, "GraphSidecar": 8, "StoryVideo": 2} def extract_media_v1(data): """Extract media from Private API""" media = deepcopy(data) if "video_versions" in media: # Select Best Quality by Resolutiuon media["video_url"] = sorted( media["video_versions"], key=lambda o: o["height"] * o["width"] )[-1]["url"] if media["media_type"] == 2 and not media.get("product_type"): media["product_type"] = "feed" if "image_versions2" in media: media["thumbnail_url"] = sorted( media["image_versions2"]["candidates"], key=lambda o: o["height"] * o["width"], )[-1]["url"] if media["media_type"] == 8: # remove thumbnail_url and video_url for albums # see resources media.pop("thumbnail_url", "") media.pop("video_url", "") location = media.get("location") media["location"] = location and extract_location(location) media["user"] = extract_user_short(media.get("user")) media["usertags"] = sorted( [ extract_usertag(usertag) for usertag in media.get("usertags", {}).get("in", []) ], key=lambda tag: tag.user.pk, ) media["like_count"] = media.get("like_count", 0) media["has_liked"] = media.get("has_liked", False) return Media( caption_text=(media.get("caption") or {}).get("text", ""), resources=[ extract_resource_v1(edge) for edge in media.get("carousel_media", []) ], **media, ) def extract_media_gql(data): """Extract media from GraphQL""" media = deepcopy(data) user = extract_user_short(media["owner"]) # if "full_name" in user: # user = extract_user_short(user) # else: # user["pk"] = user.pop("id") try: media["media_type"] = MEDIA_TYPES_GQL[media["__typename"]] except KeyError: media["media_type"] = 0 if media.get("media_type") == 2 and not media.get("product_type"): media["product_type"] = "feed" media["thumbnail_url"] = sorted( # display_resources - user feed, thumbnail_resources - hashtag feed media.get("display_resources", media.get("thumbnail_resources")), key=lambda o: o["config_width"] * o["config_height"], )[-1]["src"] if media.get("media_type") == 8: # remove thumbnail_url and video_url for albums # see resources media.pop("thumbnail_url", "") media.pop("video_url", "") location = media.pop("location", None) media_id = media.get("id") media["pk"] = media_id media["id"] = f"{media_id}_{user.pk}" return Media( code=media.get("shortcode"), taken_at=media.get("taken_at_timestamp"), location=extract_location(location) if location else None, user=user, view_count=media.get("video_view_count", 0), comment_count=json_value(media, "edge_media_to_comment", "count"), like_count=json_value(media, "edge_media_preview_like", "count"), caption_text=json_value( media, "edge_media_to_caption", "edges", 0, "node", "text", default="" ), usertags=sorted( [ extract_usertag(usertag["node"]) for usertag in media.get("edge_media_to_tagged_user", {}).get( "edges", [] ) ], key=lambda tag: tag.user.pk, ), resources=[ extract_resource_gql(edge["node"]) for edge in media.get("edge_sidecar_to_children", {}).get("edges", []) ], **media, ) def extract_resource_v1(data): if "video_versions" in data: data["video_url"] = sorted( data["video_versions"], key=lambda o: o["height"] * o["width"] )[-1]["url"] data["thumbnail_url"] = sorted( data["image_versions2"]["candidates"], key=lambda o: o["height"] * o["width"], )[-1]["url"] return Resource(**data) def extract_resource_gql(data): data["media_type"] = MEDIA_TYPES_GQL[data["__typename"]] return Resource(pk=data["id"], thumbnail_url=data["display_url"], **data) def extract_usertag(data): """Extract user tag""" x, y = data.get("position", [data.get("x"), data.get("y")]) return Usertag(user=extract_user_short(data["user"]), x=x, y=y) def extract_user_short(data): """Extract User Short info""" data["pk"] = data.get("id", data.get("pk", None)) assert data["pk"], f'User without pk "{data}"' return UserShort(**data) def extract_user_gql(data): """For Public GraphQL API""" return User( pk=data["id"], media_count=data["edge_owner_to_timeline_media"]["count"], follower_count=data["edge_followed_by"]["count"], following_count=data["edge_follow"]["count"], is_business=data["is_business_account"], public_email=data["business_email"], contact_phone_number=data["business_phone_number"], **data, ) def extract_user_v1(data): """For Private API""" data["external_url"] = data.get("external_url") or None return User(**data) def extract_location(data): """Extract location info""" if not data: return None data["pk"] = data.get("id", data.get("pk", None)) data["external_id"] = data.get("external_id", data.get("facebook_places_id")) data["external_id_source"] = data.get( "external_id_source", data.get("external_source") ) # address_json = data.get("address_json", "{}") # if isinstance(address_json, str): # address_json = json.loads(address_json) # data['address_json'] = address_json return Location(**data) def extract_comment(data): """Extract comment""" data["has_liked"] = data.get("has_liked_comment") data["like_count"] = data.get("comment_like_count") return Comment(**data) def extract_collection(data): """Extract collection for authorized account Example: {'collection_id': '17851406186124602', 'collection_name': 'Repost', 'collection_type': 'MEDIA', 'collection_media_count': 1, 'cover_media': {...} """ data = {key.replace("collection_", ""): val for key, val in data.items()} # data['pk'] = data.get('id') return Collection(**data) def extract_media_oembed(data): """Return short version of Media""" return MediaOembed(**data) def extract_direct_thread(data): data["messages"] = [extract_direct_message(item) for item in data["items"]] data["users"] = [extract_user_short(u) for u in data["users"]] if "inviter" in data: data["inviter"] = extract_user_short(data["inviter"]) data["pk"] = data.get("thread_v2_id") data["id"] = data.get("thread_id") data["left_users"] = data.get("left_users", []) return DirectThread(**data) def extract_direct_short_thread(data): data["users"] = [extract_user_short(u) for u in data["users"]] data["id"] = data.get("thread_id") return DirectShortThread(**data) def extract_direct_response(data): return DirectResponse(**data) def extract_direct_message(data): data["id"] = data.get("item_id") if "media_share" in data: data["media_share"] = extract_media_v1(data["media_share"]) if "media" in data: data["media"] = extract_direct_media(data["media"]) clip = data.get("clip", {}) if clip: if "clip" in clip: # Instagram ¯\_(ツ)_/¯ clip = clip.get("clip") data["clip"] = extract_media_v1(clip) return DirectMessage(**data) def extract_direct_media(data): media = deepcopy(data) if "video_versions" in media: # Select Best Quality by Resolutiuon media["video_url"] = sorted( media["video_versions"], key=lambda o: o["height"] * o["width"] )[-1]["url"] if "image_versions2" in media: media["thumbnail_url"] = sorted( media["image_versions2"]["candidates"], key=lambda o: o["height"] * o["width"], )[-1]["url"] if "user" in media: media["user"] = extract_user_short(media.get("user")) return DirectMedia(**media) def extract_account(data): data["external_url"] = data.get("external_url") or None return Account(**data) def extract_hashtag_gql(data): data["media_count"] = data.get("edge_hashtag_to_media", {}).get("count") return Hashtag(**data) def extract_hashtag_v1(data): data["allow_following"] = data.get("allow_following") == 1 return Hashtag(**data) def extract_story_v1(data): """Extract story from Private API""" story = deepcopy(data) if "video_versions" in story: # Select Best Quality by Resolutiuon story["video_url"] = sorted( story["video_versions"], key=lambda o: o["height"] * o["width"] )[-1]["url"] if story["media_type"] == 2 and not story.get("product_type"): story["product_type"] = "feed" if "image_versions2" in story: story["thumbnail_url"] = sorted( story["image_versions2"]["candidates"], key=lambda o: o["height"] * o["width"], )[-1]["url"] story["mentions"] = [ StoryMention(**mention) for mention in story.get("reel_mentions", []) ] story["locations"] = [] story["hashtags"] = [] story["stickers"] = [] story["links"] = [] for cta in story.get("story_cta", []): for link in cta.get("links", []): story["links"].append(StoryLink(**link)) story["user"] = extract_user_short(story.get("user")) return Story(**story) def extract_story_gql(data): """Extract story from Public API""" story = deepcopy(data) if "video_resources" in story: # Select Best Quality by Resolutiuon story["video_url"] = sorted( story["video_resources"], key=lambda o: o["config_height"] * o["config_width"] )[-1]["src"] # if story["tappable_objects"] and "GraphTappableFeedMedia" in [x["__typename"] for x in story["tappable_objects"]]: story["product_type"] = "feed" story["thumbnail_url"] = story.get("display_url") story["mentions"] = [] for mention in story.get("tappable_objects", []): if mention["__typename"] == "GraphTappableMention": mention["id"] = 1 mention["user"] = extract_user_short(mention) story["mentions"].append(StoryMention(**mention)) story["locations"] = [] story["hashtags"] = [] story["stickers"] = [] story["links"] = [] story_cta_url = story.get("story_cta_url", []) if story_cta_url: story["links"] = [StoryLink(**{'webUri': story_cta_url})] story["user"] = extract_user_short(story.get("owner")) story["pk"] = int(story["id"]) story["id"] = f"{story["id"]}_{story["owner"]["id"]}" story["code"] = InstagramIdCodec.encode(story["pk"]) story["taken_at"] = story["taken_at_timestamp"] story["media_type"] = 2 if story["is_video"] else 1 return Story(**story)
from copy import deepcopy from .types import ( Account, Collection, Comment, DirectMedia, DirectMessage, DirectResponse, DirectShortThread, DirectThread, Hashtag, Location, Media, MediaOembed, Resource, Story, StoryLink, StoryMention, User, UserShort, Usertag, ) from .utils import InstagramIdCodec, json_value MEDIA_TYPES_GQL = {"GraphImage": 1, "GraphVideo": 2, "GraphSidecar": 8, "StoryVideo": 2} def extract_media_v1(data): """Extract media from Private API""" media = deepcopy(data) if "video_versions" in media: # Select Best Quality by Resolutiuon media["video_url"] = sorted( media["video_versions"], key=lambda o: o["height"] * o["width"] )[-1]["url"] if media["media_type"] == 2 and not media.get("product_type"): media["product_type"] = "feed" if "image_versions2" in media: media["thumbnail_url"] = sorted( media["image_versions2"]["candidates"], key=lambda o: o["height"] * o["width"], )[-1]["url"] if media["media_type"] == 8: # remove thumbnail_url and video_url for albums # see resources media.pop("thumbnail_url", "") media.pop("video_url", "") location = media.get("location") media["location"] = location and extract_location(location) media["user"] = extract_user_short(media.get("user")) media["usertags"] = sorted( [ extract_usertag(usertag) for usertag in media.get("usertags", {}).get("in", []) ], key=lambda tag: tag.user.pk, ) media["like_count"] = media.get("like_count", 0) media["has_liked"] = media.get("has_liked", False) return Media( caption_text=(media.get("caption") or {}).get("text", ""), resources=[ extract_resource_v1(edge) for edge in media.get("carousel_media", []) ], **media, ) def extract_media_gql(data): """Extract media from GraphQL""" media = deepcopy(data) user = extract_user_short(media["owner"]) # if "full_name" in user: # user = extract_user_short(user) # else: # user["pk"] = user.pop("id") try: media["media_type"] = MEDIA_TYPES_GQL[media["__typename"]] except KeyError: media["media_type"] = 0 if media.get("media_type") == 2 and not media.get("product_type"): media["product_type"] = "feed" media["thumbnail_url"] = sorted( # display_resources - user feed, thumbnail_resources - hashtag feed media.get("display_resources", media.get("thumbnail_resources")), key=lambda o: o["config_width"] * o["config_height"], )[-1]["src"] if media.get("media_type") == 8: # remove thumbnail_url and video_url for albums # see resources media.pop("thumbnail_url", "") media.pop("video_url", "") location = media.pop("location", None) media_id = media.get("id") media["pk"] = media_id media["id"] = f"{media_id}_{user.pk}" return Media( code=media.get("shortcode"), taken_at=media.get("taken_at_timestamp"), location=extract_location(location) if location else None, user=user, view_count=media.get("video_view_count", 0), comment_count=json_value(media, "edge_media_to_comment", "count"), like_count=json_value(media, "edge_media_preview_like", "count"), caption_text=json_value( media, "edge_media_to_caption", "edges", 0, "node", "text", default="" ), usertags=sorted( [ extract_usertag(usertag["node"]) for usertag in media.get("edge_media_to_tagged_user", {}).get( "edges", [] ) ], key=lambda tag: tag.user.pk, ), resources=[ extract_resource_gql(edge["node"]) for edge in media.get("edge_sidecar_to_children", {}).get("edges", []) ], **media, ) def extract_resource_v1(data): if "video_versions" in data: data["video_url"] = sorted( data["video_versions"], key=lambda o: o["height"] * o["width"] )[-1]["url"] data["thumbnail_url"] = sorted( data["image_versions2"]["candidates"], key=lambda o: o["height"] * o["width"], )[-1]["url"] return Resource(**data) def extract_resource_gql(data): data["media_type"] = MEDIA_TYPES_GQL[data["__typename"]] return Resource(pk=data["id"], thumbnail_url=data["display_url"], **data) def extract_usertag(data): """Extract user tag""" x, y = data.get("position", [data.get("x"), data.get("y")]) return Usertag(user=extract_user_short(data["user"]), x=x, y=y) def extract_user_short(data): """Extract User Short info""" data["pk"] = data.get("id", data.get("pk", None)) assert data["pk"], f'User without pk "{data}"' return UserShort(**data) def extract_user_gql(data): """For Public GraphQL API""" return User( pk=data["id"], media_count=data["edge_owner_to_timeline_media"]["count"], follower_count=data["edge_followed_by"]["count"], following_count=data["edge_follow"]["count"], is_business=data["is_business_account"], public_email=data["business_email"], contact_phone_number=data["business_phone_number"], **data, ) def extract_user_v1(data): """For Private API""" data["external_url"] = data.get("external_url") or None return User(**data) def extract_location(data): """Extract location info""" if not data: return None data["pk"] = data.get("id", data.get("pk", None)) data["external_id"] = data.get("external_id", data.get("facebook_places_id")) data["external_id_source"] = data.get( "external_id_source", data.get("external_source") ) # address_json = data.get("address_json", "{}") # if isinstance(address_json, str): # address_json = json.loads(address_json) # data['address_json'] = address_json return Location(**data) def extract_comment(data): """Extract comment""" data["has_liked"] = data.get("has_liked_comment") data["like_count"] = data.get("comment_like_count") return Comment(**data) def extract_collection(data): """Extract collection for authorized account Example: {'collection_id': '17851406186124602', 'collection_name': 'Repost', 'collection_type': 'MEDIA', 'collection_media_count': 1, 'cover_media': {...} """ data = {key.replace("collection_", ""): val for key, val in data.items()} # data['pk'] = data.get('id') return Collection(**data) def extract_media_oembed(data): """Return short version of Media""" return MediaOembed(**data) def extract_direct_thread(data): data["messages"] = [extract_direct_message(item) for item in data["items"]] data["users"] = [extract_user_short(u) for u in data["users"]] if "inviter" in data: data["inviter"] = extract_user_short(data["inviter"]) data["pk"] = data.get("thread_v2_id") data["id"] = data.get("thread_id") data["left_users"] = data.get("left_users", []) return DirectThread(**data) def extract_direct_short_thread(data): data["users"] = [extract_user_short(u) for u in data["users"]] data["id"] = data.get("thread_id") return DirectShortThread(**data) def extract_direct_response(data): return DirectResponse(**data) def extract_direct_message(data): data["id"] = data.get("item_id") if "media_share" in data: data["media_share"] = extract_media_v1(data["media_share"]) if "media" in data: data["media"] = extract_direct_media(data["media"]) clip = data.get("clip", {}) if clip: if "clip" in clip: # Instagram ¯\_(ツ)_/¯ clip = clip.get("clip") data["clip"] = extract_media_v1(clip) return DirectMessage(**data) def extract_direct_media(data): media = deepcopy(data) if "video_versions" in media: # Select Best Quality by Resolutiuon media["video_url"] = sorted( media["video_versions"], key=lambda o: o["height"] * o["width"] )[-1]["url"] if "image_versions2" in media: media["thumbnail_url"] = sorted( media["image_versions2"]["candidates"], key=lambda o: o["height"] * o["width"], )[-1]["url"] if "user" in media: media["user"] = extract_user_short(media.get("user")) return DirectMedia(**media) def extract_account(data): data["external_url"] = data.get("external_url") or None return Account(**data) def extract_hashtag_gql(data): data["media_count"] = data.get("edge_hashtag_to_media", {}).get("count") return Hashtag(**data) def extract_hashtag_v1(data): data["allow_following"] = data.get("allow_following") == 1 return Hashtag(**data) def extract_story_v1(data): """Extract story from Private API""" story = deepcopy(data) if "video_versions" in story: # Select Best Quality by Resolutiuon story["video_url"] = sorted( story["video_versions"], key=lambda o: o["height"] * o["width"] )[-1]["url"] if story["media_type"] == 2 and not story.get("product_type"): story["product_type"] = "feed" if "image_versions2" in story: story["thumbnail_url"] = sorted( story["image_versions2"]["candidates"], key=lambda o: o["height"] * o["width"], )[-1]["url"] story["mentions"] = [ StoryMention(**mention) for mention in story.get("reel_mentions", []) ] story["locations"] = [] story["hashtags"] = [] story["stickers"] = [] story["links"] = [] for cta in story.get("story_cta", []): for link in cta.get("links", []): story["links"].append(StoryLink(**link)) story["user"] = extract_user_short(story.get("user")) return Story(**story) def extract_story_gql(data): """Extract story from Public API""" story = deepcopy(data) if "video_resources" in story: # Select Best Quality by Resolutiuon story["video_url"] = sorted( story["video_resources"], key=lambda o: o["config_height"] * o["config_width"] )[-1]["src"] # if story["tappable_objects"] and "GraphTappableFeedMedia" in [x["__typename"] for x in story["tappable_objects"]]: story["product_type"] = "feed" story["thumbnail_url"] = story.get("display_url") story["mentions"] = [] for mention in story.get("tappable_objects", []): if mention["__typename"] == "GraphTappableMention": mention["id"] = 1 mention["user"] = extract_user_short(mention) story["mentions"].append(StoryMention(**mention)) story["locations"] = [] story["hashtags"] = [] story["stickers"] = [] story["links"] = [] story_cta_url = story.get("story_cta_url", []) if story_cta_url: story["links"] = [StoryLink(**{'webUri': story_cta_url})] story["user"] = extract_user_short(story.get("owner")) story["pk"] = int(story["id"]) story["id"] = f"{story['id']}_{story['owner']['id']}" story["code"] = InstagramIdCodec.encode(story["pk"]) story["taken_at"] = story["taken_at_timestamp"] story["media_type"] = 2 if story["is_video"] else 1 return Story(**story)
# https://codeforces.com/problemset/problem/1220/A n, s = int(input()), input() ones = s.count('n') zeros = (n-(ones*3))//4 print(f"{"1 "*ones}{"0 "*zeros}")
# https://codeforces.com/problemset/problem/1220/A n, s = int(input()), input() ones = s.count('n') zeros = (n-(ones*3))//4 print(f"{'1 '*ones}{'0 '*zeros}")
from imagekit.admin import AdminThumbnail from django.contrib.admin import TabularInline from core.admin.forms import LimitedInlineFormSet from core.admin.utils import ( get_change_view_link, get_changelist_view_link ) from ..models import PremierProduct class PremierManufacturerProductsTabularInline(TabularInline): model = PremierProduct fk_name = 'manufacturer' formset = LimitedInlineFormSet extra = 0 verbose_name_plural = 'products (top 10)' all_link_query = 'manufacturer__id__exact' ordering = ( 'premier_part_number', ) classes = ( 'collapse', ) fields = ( 'all_link', 'detail_link', 'premier_part_number', 'vendor_part_number', 'description', 'manufacturer', 'inventory_ab', 'cost_cad', 'primary_image_preview', 'may_be_relevant_flag', 'is_relevant', 'relevancy_warnings', 'relevancy_errors', 'relevancy_exception' ) readonly_fields = ( 'relevancy_warnings', 'relevancy_errors', 'may_be_relevant_flag', 'primary_image_preview', 'all_link', 'detail_link' ) def get_rel_obj(self, obj): return getattr(obj, self.fk_name) def detail_link(self, obj): if not obj.pk: return None return get_change_view_link(obj, 'Details') detail_link.short_description = '' def all_link(self, obj): if not obj: return None query = f'{self.all_link_query}={getattr(self.get_rel_obj(obj), 'pk')}' return get_changelist_view_link(obj._meta.model, 'See All', query) all_link.short_description = '' primary_image_preview = AdminThumbnail( image_field='primary_image_thumbnail' ) primary_image_preview.short_description = 'primary image' def may_be_relevant_flag(self, obj): if obj.is_relevant != obj.may_be_relevant: return '~' else: return '' may_be_relevant_flag.short_description = '' def get_queryset(self, request): return super().get_queryset(request).filter( is_relevant=True ).with_admin_data() def get_readonly_fields(self, request, obj=None): readonly_fields = super().get_readonly_fields(request, obj) if not request.user.is_superuser: readonly_fields += ( 'premier_part_number', ) return readonly_fields
from imagekit.admin import AdminThumbnail from django.contrib.admin import TabularInline from core.admin.forms import LimitedInlineFormSet from core.admin.utils import ( get_change_view_link, get_changelist_view_link ) from ..models import PremierProduct class PremierManufacturerProductsTabularInline(TabularInline): model = PremierProduct fk_name = 'manufacturer' formset = LimitedInlineFormSet extra = 0 verbose_name_plural = 'products (top 10)' all_link_query = 'manufacturer__id__exact' ordering = ( 'premier_part_number', ) classes = ( 'collapse', ) fields = ( 'all_link', 'detail_link', 'premier_part_number', 'vendor_part_number', 'description', 'manufacturer', 'inventory_ab', 'cost_cad', 'primary_image_preview', 'may_be_relevant_flag', 'is_relevant', 'relevancy_warnings', 'relevancy_errors', 'relevancy_exception' ) readonly_fields = ( 'relevancy_warnings', 'relevancy_errors', 'may_be_relevant_flag', 'primary_image_preview', 'all_link', 'detail_link' ) def get_rel_obj(self, obj): return getattr(obj, self.fk_name) def detail_link(self, obj): if not obj.pk: return None return get_change_view_link(obj, 'Details') detail_link.short_description = '' def all_link(self, obj): if not obj: return None query = f'{self.all_link_query}={getattr(self.get_rel_obj(obj), "pk")}' return get_changelist_view_link(obj._meta.model, 'See All', query) all_link.short_description = '' primary_image_preview = AdminThumbnail( image_field='primary_image_thumbnail' ) primary_image_preview.short_description = 'primary image' def may_be_relevant_flag(self, obj): if obj.is_relevant != obj.may_be_relevant: return '~' else: return '' may_be_relevant_flag.short_description = '' def get_queryset(self, request): return super().get_queryset(request).filter( is_relevant=True ).with_admin_data() def get_readonly_fields(self, request, obj=None): readonly_fields = super().get_readonly_fields(request, obj) if not request.user.is_superuser: readonly_fields += ( 'premier_part_number', ) return readonly_fields
import sys from collections import Counter import datetime as dt from pathlib import Path from time import sleep import curses from curses import wrapper # from basin_weights_analysis import gen_task_ctrl def main(stdscr, status_dir='.remake/metadata_v3/task_status'): status_dir = Path(status_dir) # task_ctrl = gen_task_ctrl(False) curses.curs_set(0) while True: stdscr.clear() paths = status_dir.glob('*.status') statuses = Counter() running = [] for path in paths: time, status = path.read_text().split('\n')[-2].split(';') statuses[status] += 1 if status == 'RUNNING': running.append(path) stdscr.addstr(0, 0, f'Time : {dt.datetime.now()}') stdscr.addstr(1, 0, f'Complete: {statuses['COMPLETE']}') stdscr.addstr(2, 0, f'Running : {statuses['RUNNING']}') stdscr.addstr(3, 0, f'Error : {statuses['ERROR']}') for i, path in enumerate(running[:40]): stdscr.addstr(5 + i, 0, f'{path.stem}') stdscr.refresh() curses.napms(1000) if __name__ == '__main__': if len(sys.argv) == 2: wrapper(main, sys.argv[1]) else: wrapper(main)
import sys from collections import Counter import datetime as dt from pathlib import Path from time import sleep import curses from curses import wrapper # from basin_weights_analysis import gen_task_ctrl def main(stdscr, status_dir='.remake/metadata_v3/task_status'): status_dir = Path(status_dir) # task_ctrl = gen_task_ctrl(False) curses.curs_set(0) while True: stdscr.clear() paths = status_dir.glob('*.status') statuses = Counter() running = [] for path in paths: time, status = path.read_text().split('\n')[-2].split(';') statuses[status] += 1 if status == 'RUNNING': running.append(path) stdscr.addstr(0, 0, f'Time : {dt.datetime.now()}') stdscr.addstr(1, 0, f'Complete: {statuses["COMPLETE"]}') stdscr.addstr(2, 0, f'Running : {statuses["RUNNING"]}') stdscr.addstr(3, 0, f'Error : {statuses["ERROR"]}') for i, path in enumerate(running[:40]): stdscr.addstr(5 + i, 0, f'{path.stem}') stdscr.refresh() curses.napms(1000) if __name__ == '__main__': if len(sys.argv) == 2: wrapper(main, sys.argv[1]) else: wrapper(main)
# -*- coding: utf-8 -*- # Copyright © 2017 Apple Inc. All rights reserved. # # Use of this source code is governed by a BSD-3-clause license that can # be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause from __future__ import print_function as _ from __future__ import division as _ from __future__ import absolute_import as _ import math import unittest import warnings import turicreate as tc from . import util # turicreate test utils (in oss_src) class FeatureEngineeringTest(unittest.TestCase): """ Test the text utilities for creating and cleaning features. """ @classmethod def setUpClass(self): self.sa_word = tc.SArray(["I like big dogs. They are fun. I LIKE BIG DOGS", "I like.", "I like big"]) self.sa_char = tc.SArray(["Fun. is. fun","Fun is fun.","fu", "fun"]) self.languages = tc.SArray(["This is someurl http://someurl!!", "中文 应该也 行", "Сблъсъкът между"]) self.languages_double = tc.SArray(["This is someurl http://someurl!! This is someurl http://someurl!!", "中文 应该也 行 中文 应该也 行", "Сблъсъкът между Сблъсъкът между"]) self.punctuated = tc.SArray(["This is some url http://www.someurl.com!!", "Should we? Yes, we should."]) self.punctuated_double = tc.SArray(["This is some url http://www.someurl.com!! This is some url http://www.someurl.com!!", "Should we? Yes, we should. Should we? Yes, we should."]) self.docs = tc.SArray([{'this': 1, 'is': 1, 'a': 2, 'sample': 1}, {'this': 1, 'is': 1, 'another': 2, 'example': 3}]) self.sframe_comparer = util.SFrameComparer() def test_count_ngrams(self): """ Check correctness of the `text_analytics.count_ngrams` function. This code copies the same test in test_sarray.py, but that test will be removed when the SArray version of count_ngrams is removed in GLC version 1.7. """ # Testing word n-gram functionality result = tc.text_analytics.count_ngrams(self.sa_word, 3) result2 = tc.text_analytics.count_ngrams(self.sa_word, 2) result3 = tc.text_analytics.count_ngrams(self.sa_word, 3,"word", to_lower=False) result4 = tc.text_analytics.count_ngrams(self.sa_word, 2,"word", to_lower=False) expected = [{'fun i like': 1, 'i like big': 2, 'they are fun': 1, 'big dogs they': 1, 'like big dogs': 2, 'are fun i': 1, 'dogs they are': 1}, {}, {'i like big': 1}] expected2 = [{'i like': 2, 'dogs they': 1, 'big dogs': 2, 'are fun': 1, 'like big': 2, 'they are': 1, 'fun i': 1}, {'i like': 1}, {'i like': 1, 'like big': 1}] expected3 = [{'I like big': 1, 'fun I LIKE': 1, 'I LIKE BIG': 1, 'LIKE BIG DOGS': 1, 'They are fun': 1, 'big dogs They': 1, 'like big dogs': 1, 'are fun I': 1, 'dogs They are': 1}, {}, {'I like big': 1}] expected4 = [{'I like': 1, 'like big': 1, 'I LIKE': 1, 'BIG DOGS': 1, 'are fun': 1, 'LIKE BIG': 1, 'big dogs': 1, 'They are': 1, 'dogs They': 1, 'fun I': 1}, {'I like': 1}, {'I like': 1, 'like big': 1}] self.assertEqual(result.dtype, dict) self.sframe_comparer._assert_sarray_equal(result, expected) self.assertEqual(result2.dtype, dict) self.sframe_comparer._assert_sarray_equal(result2, expected2) self.assertEqual(result3.dtype, dict) self.sframe_comparer._assert_sarray_equal(result3, expected3) self.assertEqual(result4.dtype, dict) self.sframe_comparer._assert_sarray_equal(result4, expected4) #Testing character n-gram functionality result5 = tc.text_analytics.count_ngrams(self.sa_char, 3, "character") result6 = tc.text_analytics.count_ngrams(self.sa_char, 2, "character") result7 = tc.text_analytics.count_ngrams(self.sa_char, 3, "character", to_lower=False) result8 = tc.text_analytics.count_ngrams(self.sa_char, 2, "character", to_lower=False) result9 = tc.text_analytics.count_ngrams(self.sa_char, 3, "character", to_lower=False, ignore_space=False) result10 = tc.text_analytics.count_ngrams(self.sa_char, 2, "character", to_lower=False, ignore_space=False) result11 = tc.text_analytics.count_ngrams(self.sa_char, 3, "character", to_lower=True, ignore_space=False) result12 = tc.text_analytics.count_ngrams(self.sa_char, 2, "character", to_lower=True, ignore_space=False) result13 = tc.text_analytics.count_ngrams(self.sa_char, 3, "character", to_lower=False, ignore_punct=False, ignore_space=False) result14 = tc.text_analytics.count_ngrams(self.sa_char, 2, "character", to_lower=False, ignore_punct=False, ignore_space=False) result15 = tc.text_analytics.count_ngrams(self.sa_char, 3, "character", to_lower=False, ignore_punct=False, ignore_space=True) result16 = tc.text_analytics.count_ngrams(self.sa_char, 2, "character", to_lower=False, ignore_punct=False, ignore_space=True) expected5 = [{'fun': 2, 'nis': 1, 'sfu': 1, 'isf': 1, 'uni': 1}, {'fun': 2, 'nis': 1, 'sfu': 1, 'isf': 1, 'uni': 1}, {}, {'fun': 1}] expected6 = [{'ni': 1, 'is': 1, 'un': 2, 'sf': 1, 'fu': 2}, {'ni': 1, 'is': 1, 'un': 2, 'sf': 1, 'fu': 2}, {'fu': 1}, {'un': 1, 'fu': 1}] expected7 = [{'sfu': 1, 'Fun': 1, 'uni': 1, 'fun': 1, 'nis': 1, 'isf': 1}, {'sfu': 1, 'Fun': 1, 'uni': 1, 'fun': 1, 'nis': 1, 'isf': 1}, {}, {'fun': 1}] expected8 = [{'ni': 1, 'Fu': 1, 'is': 1, 'un': 2, 'sf': 1, 'fu': 1}, {'ni': 1, 'Fu': 1, 'is': 1, 'un': 2, 'sf': 1, 'fu': 1}, {'fu': 1}, {'un': 1, 'fu': 1}] expected9 = [{' fu': 1, ' is': 1, 's f': 1, 'un ': 1, 'Fun': 1, 'n i': 1, 'fun': 1, 'is ': 1}, {' fu': 1, ' is': 1, 's f': 1, 'un ': 1, 'Fun': 1, 'n i': 1, 'fun': 1, 'is ': 1}, {}, {'fun': 1}] expected10 = [{' f': 1, 'fu': 1, 'n ': 1, 'is': 1, ' i': 1, 'un': 2, 's ': 1, 'Fu': 1}, {' f': 1, 'fu': 1, 'n ': 1, 'is': 1, ' i': 1, 'un': 2, 's ': 1, 'Fu': 1}, {'fu': 1}, {'un': 1, 'fu': 1}] expected11 = [{' fu': 1, ' is': 1, 's f': 1, 'un ': 1, 'n i': 1, 'fun': 2, 'is ': 1}, {' fu': 1, ' is': 1, 's f': 1, 'un ': 1, 'n i': 1, 'fun': 2, 'is ': 1}, {}, {'fun': 1}] expected12 = [{' f': 1, 'fu': 2, 'n ': 1, 'is': 1, ' i': 1, 'un': 2, 's ': 1}, {' f': 1, 'fu': 2, 'n ': 1, 'is': 1, ' i': 1, 'un': 2, 's ': 1}, {'fu': 1}, {'un': 1, 'fu': 1}] expected13 = [{' fu': 1, 's. ': 1, ' is': 1, 'n. ': 1, 'Fun': 1, '. i': 1, 'is.': 1, 'fun': 1, '. f': 1, 'un.': 1}, {' fu': 1, ' is': 1, 's f': 1, 'un ': 1, 'Fun': 1, 'n i': 1, 'fun': 1, 'is ': 1, 'un.': 1}, {}, {'fun': 1}] expected14 = [{' f': 1, 'fu': 1, 'n.': 1, '. ': 2, 'is': 1, ' i': 1, 'un': 2, 's.': 1, 'Fu': 1}, {' f': 1, 'fu': 1, 'n.': 1, 'n ': 1, 'is': 1, ' i': 1, 'un': 2, 's ': 1, 'Fu': 1}, {'fu': 1}, {'un': 1, 'fu': 1}] expected15 = [{'s.f': 1, 'n.i': 1, 'Fun': 1, '.fu': 1, 'is.': 1, 'fun': 1, '.is': 1, 'un.': 1}, {'sfu': 1, 'Fun': 1, 'uni': 1, 'fun': 1, 'nis': 1, 'isf': 1, 'un.': 1}, {}, {'fun': 1}] expected16 = [{'.i': 1, 'fu': 1, 'n.': 1, 'is': 1, '.f': 1, 'un': 2, 's.': 1, 'Fu': 1}, {'ni': 1, 'fu': 1, 'n.': 1, 'is': 1, 'un': 2, 'sf': 1, 'Fu': 1}, {'fu': 1}, {'un': 1, 'fu': 1}] self.assertEqual(result5.dtype, dict) self.sframe_comparer._assert_sarray_equal(result5, expected5) self.assertEqual(result6.dtype, dict) self.sframe_comparer._assert_sarray_equal(result6, expected6) self.assertEqual(result7.dtype, dict) self.sframe_comparer._assert_sarray_equal(result7, expected7) self.assertEqual(result8.dtype, dict) self.sframe_comparer._assert_sarray_equal(result8, expected8) self.assertEqual(result9.dtype, dict) self.sframe_comparer._assert_sarray_equal(result9, expected9) self.assertEqual(result10.dtype, dict) self.sframe_comparer._assert_sarray_equal(result10, expected10) self.assertEqual(result11.dtype, dict) self.sframe_comparer._assert_sarray_equal(result11, expected11) self.assertEqual(result12.dtype, dict) self.sframe_comparer._assert_sarray_equal(result12, expected12) self.assertEqual(result13.dtype, dict) self.sframe_comparer._assert_sarray_equal(result13, expected13) self.assertEqual(result14.dtype, dict) self.sframe_comparer._assert_sarray_equal(result14, expected14) self.assertEqual(result15.dtype, dict) self.sframe_comparer._assert_sarray_equal(result15, expected15) self.assertEqual(result16.dtype, dict) self.sframe_comparer._assert_sarray_equal(result16, expected16) ## Bogus input types and values sa = tc.SArray([1, 2, 3]) with self.assertRaises(RuntimeError): tc.text_analytics.count_ngrams(sa) with self.assertRaises(TypeError): tc.text_analytics.count_ngrams(self.sa_word, n=1.01) with self.assertRaises(ValueError): tc.text_analytics.count_ngrams(self.sa_word, n=0) with self.assertRaises(ValueError): tc.text_analytics.count_ngrams(self.sa_char, n=3, method="bla") with warnings.catch_warnings(record=True) as context: warnings.simplefilter("always") tc.text_analytics.count_ngrams(self.sa_word, n=10, method='word') assert len(context) == 1 def test_trim_rare_words(self): """ Check correctness of the `text_analytics.trim_rare_words` function. This code copies the same test in test_sarray.py, but that test will be removed when the SArray version of count_ngrams is removed in GLC version 1.7. """ ## Bogus input type sa = tc.SArray([1, 2, 3]) with self.assertRaises(RuntimeError): tc.text_analytics.trim_rare_words(sa) ## Other languages expected = ["this is someurl http://someurl!! this is someurl http://someurl!!", "中文 应该也 行 中文 应该也 行", "Сблъсъкът между Сблъсъкът между"] expected2 = ["This is someurl http://someurl!! This is someurl http://someurl!!", "中文 应该也 行 中文 应该也 行", "Сблъсъкът между Сблъсъкът между"] result = tc.text_analytics.trim_rare_words(self.languages_double) self.assertEqual(result.dtype, str) self.sframe_comparer._assert_sarray_equal(result, expected) result = tc.text_analytics.trim_rare_words(self.languages_double, to_lower=False) self.assertEqual(result.dtype, str) self.sframe_comparer._assert_sarray_equal(result, expected2) ## Check that delimiters work properly by default and when modified. expected1 = ['this is some url http://www.someurl.com!! this is some url http://www.someurl.com!!', 'should we? yes, we should. should we? yes, we should.'] expected2 = ['this is some url http://www.someurl.com this is some url http://www.someurl.com', 'should we yes we should. should we yes we should.'] word_counts1 = tc.text_analytics.trim_rare_words(self.punctuated_double) word_counts2 = tc.text_analytics.trim_rare_words(self.punctuated_double, delimiters=["?", "!", ","," "]) self.assertEqual(word_counts1.dtype, str) self.sframe_comparer._assert_sarray_equal(word_counts1, expected1) self.assertEqual(word_counts2.dtype, str) self.sframe_comparer._assert_sarray_equal(word_counts2, expected2) def test_count_words(self): """ Check correctness of the `text_analytics.count_words` function. This code copies the same test in test_sarray.py, but that test will be removed when the SArray version of count_ngrams is removed in GLC version 1.7. """ ## Bogus input type sa = tc.SArray([1, 2, 3]) with self.assertRaises(RuntimeError): tc.text_analytics.count_words(sa) ## Other languages expected = [{"this": 1, "http://someurl!!": 1, "someurl": 1, "is": 1}, {"中文": 1, "应该也": 1, "行": 1}, {"Сблъсъкът": 1, "между": 1}] expected2 = [{"This": 1, "http://someurl!!": 1, "someurl": 1, "is": 1}, {"中文": 1, "应该也": 1, "行": 1}, {"Сблъсъкът": 1, "между": 1}] result = tc.text_analytics.count_words(self.languages) self.assertEqual(result.dtype, dict) self.sframe_comparer._assert_sarray_equal(result, expected) result = tc.text_analytics.count_words(self.languages, to_lower=False) self.assertEqual(result.dtype, dict) self.sframe_comparer._assert_sarray_equal(result, expected2) ## Check that delimiters work properly by default and when modified. expected1 = [{"this": 1, "is": 1, "some": 1, "url": 1, "http://www.someurl.com!!": 1}, {"should": 1, "we?": 1, "we": 1, "yes,": 1, "should.": 1}] expected2 = [{"this is some url http://www.someurl.com": 1}, {"should we": 1, " yes": 1, " we should.": 1}] word_counts1 = tc.text_analytics.count_words(self.punctuated) word_counts2 = tc.text_analytics.count_words(self.punctuated, delimiters=["?", "!", ","]) self.assertEqual(word_counts1.dtype, dict) self.sframe_comparer._assert_sarray_equal(word_counts1, expected1) self.assertEqual(word_counts2.dtype, dict) self.sframe_comparer._assert_sarray_equal(word_counts2, expected2) def test_stopwords(self): """ Check that the stopwords can be accessed properly as part of the text analytics toolkit. """ words = tc.text_analytics.stopwords() assert len(words) > 400 def test_tf_idf(self): """ Check correctness of the tf-idf mapping. """ # Use the example on wikipedia tfidf_docs = tc.text_analytics.tf_idf(self.docs) self.assertAlmostEqual(tfidf_docs[1]['example'], 3 * math.log(2)) self.assertAlmostEqual(tfidf_docs[0]['is'], 1 * math.log(1)) empty_sa = tc.text_analytics.tf_idf(tc.SArray()) self.assertEqual(len(empty_sa), 0) empty_dict_sf = tc.text_analytics.tf_idf(tc.SArray([{}])) assert len(empty_dict_sf) == 1 assert len(empty_dict_sf.apply(lambda x: len(x) == 0)) == 1 class RandomWordSplitTest(unittest.TestCase): """ Test that the random split utility in the text analytics toolkit works properly. """ @classmethod def setUpClass(self): self.docs = tc.SArray([{'a': 3, 'b': 5}, {'b': 5, 'c': 7}, {'a': 2, 'd': 3}]) def test_random_split(self): """ Test that the random split utility in the text analytics toolkit works properly. """ train, test = tc.text_analytics.random_split(self.docs) assert len(train) == len(self.docs) assert len(test) == len(self.docs) # Iterate through each doc and each word for i in range(len(self.docs)): a = train[i] b = test[i] # Make sure there are no zero values for (k, v) in a.items(): assert v != 0 for (k, v) in b.items(): assert v != 0 # Make sure the counts add up to the original counts for (k, v) in self.docs[i].items(): av = 0 bv = 0 if k in a: av = a[k] if k in b: bv = b[k] assert v == av + bv # Check that a low probability puts fewer items in the test set train, test = tc.text_analytics.random_split(self.docs, prob=.001) total_in_train = train.dict_values().apply(lambda x: sum(x)).sum() total_in_test = test.dict_values().apply(lambda x: sum(x)).sum() assert total_in_train > total_in_test class RetrievalTest(unittest.TestCase): """ Test document retrieval functions in the `text_analytics` toolkit. """ @classmethod def setUpClass(self): self.data = tc.SArray([{'a':5, 'b':7, 'c':10}, {'a':3, 'c':1, 'd':2}, {'a':10, 'b':3, 'e':5}, {'a':1}, {'f':5}]) def test_bm25(self): """ Check correctness of the BM2.5 query. """ # Test input formats query = ['a','b','c'] assert tc.text_analytics.bm25(self.data, query) is not None query = tc.SArray(['a','b','c']) assert tc.text_analytics.bm25(self.data, query) is not None query = {'a':5, 'b':3, 'c':1} assert tc.text_analytics.bm25(self.data, query) is not None # Only documents containing query words are included in result assert tc.text_analytics.bm25(self.data, query).num_rows() == 4 dataset = tc.SArray([ {'a':5, 'b':7, 'c':10}, {'a':3, 'c':1, 'd':2}, None, {'a':1}, {'f':5}]) res = tc.text_analytics.bm25(dataset, query) assert res.num_rows() == 3
# -*- coding: utf-8 -*- # Copyright © 2017 Apple Inc. All rights reserved. # # Use of this source code is governed by a BSD-3-clause license that can # be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause from __future__ import print_function as _ from __future__ import division as _ from __future__ import absolute_import as _ import math import unittest import warnings import turicreate as tc from . import util # turicreate test utils (in oss_src) class FeatureEngineeringTest(unittest.TestCase): """ Test the text utilities for creating and cleaning features. """ @classmethod def setUpClass(self): self.sa_word = tc.SArray(["I like big dogs. They are fun. I LIKE BIG DOGS", "I like.", "I like big"]) self.sa_char = tc.SArray(["Fun. is. fun","Fun is fun.","fu", "fun"]) self.languages = tc.SArray(["This is someurl http://someurl!!", "中文 应该也 行", "Сблъсъкът между"]) self.languages_double = tc.SArray(["This is someurl http://someurl!! This is someurl http://someurl!!", "中文 应该也 行 中文 应该也 行", "Сблъсъкът между Сблъсъкът между"]) self.punctuated = tc.SArray(["This is some url http://www.someurl.com!!", "Should we? Yes, we should."]) self.punctuated_double = tc.SArray(["This is some url http://www.someurl.com!! This is some url http://www.someurl.com!!", "Should we? Yes, we should. Should we? Yes, we should."]) self.docs = tc.SArray([{'this': 1, 'is': 1, 'a': 2, 'sample': 1}, {'this': 1, 'is': 1, 'another': 2, 'example': 3}]) self.sframe_comparer = util.SFrameComparer() def test_count_ngrams(self): """ Check correctness of the `text_analytics.count_ngrams` function. This code copies the same test in test_sarray.py, but that test will be removed when the SArray version of count_ngrams is removed in GLC version 1.7. """ # Testing word n-gram functionality result = tc.text_analytics.count_ngrams(self.sa_word, 3) result2 = tc.text_analytics.count_ngrams(self.sa_word, 2) result3 = tc.text_analytics.count_ngrams(self.sa_word, 3,"word", to_lower=False) result4 = tc.text_analytics.count_ngrams(self.sa_word, 2,"word", to_lower=False) expected = [{'fun i like': 1, 'i like big': 2, 'they are fun': 1, 'big dogs they': 1, 'like big dogs': 2, 'are fun i': 1, 'dogs they are': 1}, {}, {'i like big': 1}] expected2 = [{'i like': 2, 'dogs they': 1, 'big dogs': 2, 'are fun': 1, 'like big': 2, 'they are': 1, 'fun i': 1}, {'i like': 1}, {'i like': 1, 'like big': 1}] expected3 = [{'I like big': 1, 'fun I LIKE': 1, 'I LIKE BIG': 1, 'LIKE BIG DOGS': 1, 'They are fun': 1, 'big dogs They': 1, 'like big dogs': 1, 'are fun I': 1, 'dogs They are': 1}, {}, {'I like big': 1}] expected4 = [{'I like': 1, 'like big': 1, 'I LIKE': 1, 'BIG DOGS': 1, 'are fun': 1, 'LIKE BIG': 1, 'big dogs': 1, 'They are': 1, 'dogs They': 1, 'fun I': 1}, {'I like': 1}, {'I like': 1, 'like big': 1}] self.assertEqual(result.dtype, dict) self.sframe_comparer._assert_sarray_equal(result, expected) self.assertEqual(result2.dtype, dict) self.sframe_comparer._assert_sarray_equal(result2, expected2) self.assertEqual(result3.dtype, dict) self.sframe_comparer._assert_sarray_equal(result3, expected3) self.assertEqual(result4.dtype, dict) self.sframe_comparer._assert_sarray_equal(result4, expected4) #Testing character n-gram functionality result5 = tc.text_analytics.count_ngrams(self.sa_char, 3, "character") result6 = tc.text_analytics.count_ngrams(self.sa_char, 2, "character") result7 = tc.text_analytics.count_ngrams(self.sa_char, 3, "character", to_lower=False) result8 = tc.text_analytics.count_ngrams(self.sa_char, 2, "character", to_lower=False) result9 = tc.text_analytics.count_ngrams(self.sa_char, 3, "character", to_lower=False, ignore_space=False) result10 = tc.text_analytics.count_ngrams(self.sa_char, 2, "character", to_lower=False, ignore_space=False) result11 = tc.text_analytics.count_ngrams(self.sa_char, 3, "character", to_lower=True, ignore_space=False) result12 = tc.text_analytics.count_ngrams(self.sa_char, 2, "character", to_lower=True, ignore_space=False) result13 = tc.text_analytics.count_ngrams(self.sa_char, 3, "character", to_lower=False, ignore_punct=False, ignore_space=False) result14 = tc.text_analytics.count_ngrams(self.sa_char, 2, "character", to_lower=False, ignore_punct=False, ignore_space=False) result15 = tc.text_analytics.count_ngrams(self.sa_char, 3, "character", to_lower=False, ignore_punct=False, ignore_space=True) result16 = tc.text_analytics.count_ngrams(self.sa_char, 2, "character", to_lower=False, ignore_punct=False, ignore_space=True) expected5 = [{'fun': 2, 'nis': 1, 'sfu': 1, 'isf': 1, 'uni': 1}, {'fun': 2, 'nis': 1, 'sfu': 1, 'isf': 1, 'uni': 1}, {}, {'fun': 1}] expected6 = [{'ni': 1, 'is': 1, 'un': 2, 'sf': 1, 'fu': 2}, {'ni': 1, 'is': 1, 'un': 2, 'sf': 1, 'fu': 2}, {'fu': 1}, {'un': 1, 'fu': 1}] expected7 = [{'sfu': 1, 'Fun': 1, 'uni': 1, 'fun': 1, 'nis': 1, 'isf': 1}, {'sfu': 1, 'Fun': 1, 'uni': 1, 'fun': 1, 'nis': 1, 'isf': 1}, {}, {'fun': 1}] expected8 = [{'ni': 1, 'Fu': 1, 'is': 1, 'un': 2, 'sf': 1, 'fu': 1}, {'ni': 1, 'Fu': 1, 'is': 1, 'un': 2, 'sf': 1, 'fu': 1}, {'fu': 1}, {'un': 1, 'fu': 1}] expected9 = [{' fu': 1, ' is': 1, 's f': 1, 'un ': 1, 'Fun': 1, 'n i': 1, 'fun': 1, 'is ': 1}, {' fu': 1, ' is': 1, 's f': 1, 'un ': 1, 'Fun': 1, 'n i': 1, 'fun': 1, 'is ': 1}, {}, {'fun': 1}] expected10 = [{' f': 1, 'fu': 1, 'n ': 1, 'is': 1, ' i': 1, 'un': 2, 's ': 1, 'Fu': 1}, {' f': 1, 'fu': 1, 'n ': 1, 'is': 1, ' i': 1, 'un': 2, 's ': 1, 'Fu': 1}, {'fu': 1}, {'un': 1, 'fu': 1}] expected11 = [{' fu': 1, ' is': 1, 's f': 1, 'un ': 1, 'n i': 1, 'fun': 2, 'is ': 1}, {' fu': 1, ' is': 1, 's f': 1, 'un ': 1, 'n i': 1, 'fun': 2, 'is ': 1}, {}, {'fun': 1}] expected12 = [{' f': 1, 'fu': 2, 'n ': 1, 'is': 1, ' i': 1, 'un': 2, 's ': 1}, {' f': 1, 'fu': 2, 'n ': 1, 'is': 1, ' i': 1, 'un': 2, 's ': 1}, {'fu': 1}, {'un': 1, 'fu': 1}] expected13 = [{' fu': 1, 's. ': 1, ' is': 1, 'n. ': 1, 'Fun': 1, '. i': 1, 'is.': 1, 'fun': 1, '. f': 1, 'un.': 1}, {' fu': 1, ' is': 1, 's f': 1, 'un ': 1, 'Fun': 1, 'n i': 1, 'fun': 1, 'is ': 1, 'un.': 1}, {}, {'fun': 1}] expected14 = [{' f': 1, 'fu': 1, 'n.': 1, '. ': 2, 'is': 1, ' i': 1, 'un': 2, 's.': 1, 'Fu': 1}, {' f': 1, 'fu': 1, 'n.': 1, 'n ': 1, 'is': 1, ' i': 1, 'un': 2, 's ': 1, 'Fu': 1}, {'fu': 1}, {'un': 1, 'fu': 1}] expected15 = [{'s.f': 1, 'n.i': 1, 'Fun': 1, '.fu': 1, 'is.': 1, 'fun': 1, '.is': 1, 'un.': 1}, {'sfu': 1, 'Fun': 1, 'uni': 1, 'fun': 1, 'nis': 1, 'isf': 1, 'un.': 1}, {}, {'fun': 1}] expected16 = [{'.i': 1, 'fu': 1, 'n.': 1, 'is': 1, '.f': 1, 'un': 2, 's.': 1, 'Fu': 1}, {'ni': 1, 'fu': 1, 'n.': 1, 'is': 1, 'un': 2, 'sf': 1, 'Fu': 1}, {'fu': 1}, {'un': 1, 'fu': 1}] self.assertEqual(result5.dtype, dict) self.sframe_comparer._assert_sarray_equal(result5, expected5) self.assertEqual(result6.dtype, dict) self.sframe_comparer._assert_sarray_equal(result6, expected6) self.assertEqual(result7.dtype, dict) self.sframe_comparer._assert_sarray_equal(result7, expected7) self.assertEqual(result8.dtype, dict) self.sframe_comparer._assert_sarray_equal(result8, expected8) self.assertEqual(result9.dtype, dict) self.sframe_comparer._assert_sarray_equal(result9, expected9) self.assertEqual(result10.dtype, dict) self.sframe_comparer._assert_sarray_equal(result10, expected10) self.assertEqual(result11.dtype, dict) self.sframe_comparer._assert_sarray_equal(result11, expected11) self.assertEqual(result12.dtype, dict) self.sframe_comparer._assert_sarray_equal(result12, expected12) self.assertEqual(result13.dtype, dict) self.sframe_comparer._assert_sarray_equal(result13, expected13) self.assertEqual(result14.dtype, dict) self.sframe_comparer._assert_sarray_equal(result14, expected14) self.assertEqual(result15.dtype, dict) self.sframe_comparer._assert_sarray_equal(result15, expected15) self.assertEqual(result16.dtype, dict) self.sframe_comparer._assert_sarray_equal(result16, expected16) ## Bogus input types and values sa = tc.SArray([1, 2, 3]) with self.assertRaises(RuntimeError): tc.text_analytics.count_ngrams(sa) with self.assertRaises(TypeError): tc.text_analytics.count_ngrams(self.sa_word, n=1.01) with self.assertRaises(ValueError): tc.text_analytics.count_ngrams(self.sa_word, n=0) with self.assertRaises(ValueError): tc.text_analytics.count_ngrams(self.sa_char, n=3, method="bla") with warnings.catch_warnings(record=True) as context: warnings.simplefilter("always") tc.text_analytics.count_ngrams(self.sa_word, n=10, method='word') assert len(context) == 1 def test_trim_rare_words(self): """ Check correctness of the `text_analytics.trim_rare_words` function. This code copies the same test in test_sarray.py, but that test will be removed when the SArray version of count_ngrams is removed in GLC version 1.7. """ ## Bogus input type sa = tc.SArray([1, 2, 3]) with self.assertRaises(RuntimeError): tc.text_analytics.trim_rare_words(sa) ## Other languages expected = ["this is someurl http://someurl!! this is someurl http://someurl!!", "中文 应该也 行 中文 应该也 行", "Сблъсъкът между Сблъсъкът между"] expected2 = ["This is someurl http://someurl!! This is someurl http://someurl!!", "中文 应该也 行 中文 应该也 行", "Сблъсъкът между Сблъсъкът между"] result = tc.text_analytics.trim_rare_words(self.languages_double) self.assertEqual(result.dtype, str) self.sframe_comparer._assert_sarray_equal(result, expected) result = tc.text_analytics.trim_rare_words(self.languages_double, to_lower=False) self.assertEqual(result.dtype, str) self.sframe_comparer._assert_sarray_equal(result, expected2) ## Check that delimiters work properly by default and when modified. expected1 = ['this is some url http://www.someurl.com!! this is some url http://www.someurl.com!!', 'should we? yes, we should. should we? yes, we should.'] expected2 = ['this is some url http://www.someurl.com this is some url http://www.someurl.com', 'should we yes we should. should we yes we should.'] word_counts1 = tc.text_analytics.trim_rare_words(self.punctuated_double) word_counts2 = tc.text_analytics.trim_rare_words(self.punctuated_double, delimiters=["?", "!", ","," "]) self.assertEqual(word_counts1.dtype, str) self.sframe_comparer._assert_sarray_equal(word_counts1, expected1) self.assertEqual(word_counts2.dtype, str) self.sframe_comparer._assert_sarray_equal(word_counts2, expected2) def test_count_words(self): """ Check correctness of the `text_analytics.count_words` function. This code copies the same test in test_sarray.py, but that test will be removed when the SArray version of count_ngrams is removed in GLC version 1.7. """ ## Bogus input type sa = tc.SArray([1, 2, 3]) with self.assertRaises(RuntimeError): tc.text_analytics.count_words(sa) ## Other languages expected = [{"this": 1, "http://someurl!!": 1, "someurl": 1, "is": 1}, {"中文": 1, "应该也": 1, "行": 1}, {"Сблъсъкът": 1, "между": 1}] expected2 = [{"This": 1, "http://someurl!!": 1, "someurl": 1, "is": 1}, {"中文": 1, "应该也": 1, "行": 1}, {"Сблъсъкът": 1, "между": 1}] result = tc.text_analytics.count_words(self.languages) self.assertEqual(result.dtype, dict) self.sframe_comparer._assert_sarray_equal(result, expected) result = tc.text_analytics.count_words(self.languages, to_lower=False) self.assertEqual(result.dtype, dict) self.sframe_comparer._assert_sarray_equal(result, expected2) ## Check that delimiters work properly by default and when modified. expected1 = [{"this": 1, "is": 1, "some": 1, "url": 1, "http://www.someurl.com!!": 1}, {"should": 1, "we?": 1, "we": 1, "yes,": 1, "should.": 1}] expected2 = [{"this is some url http://www.someurl.com": 1}, {"should we": 1, " yes": 1, " we should.": 1}] word_counts1 = tc.text_analytics.count_words(self.punctuated) word_counts2 = tc.text_analytics.count_words(self.punctuated, delimiters=["?", "!", ","]) self.assertEqual(word_counts1.dtype, dict) self.sframe_comparer._assert_sarray_equal(word_counts1, expected1) self.assertEqual(word_counts2.dtype, dict) self.sframe_comparer._assert_sarray_equal(word_counts2, expected2) def test_stopwords(self): """ Check that the stopwords can be accessed properly as part of the text analytics toolkit. """ words = tc.text_analytics.stopwords() assert len(words) > 400 def test_tf_idf(self): """ Check correctness of the tf-idf mapping. """ # Use the example on wikipedia tfidf_docs = tc.text_analytics.tf_idf(self.docs) self.assertAlmostEqual(tfidf_docs[1]['example'], 3 * math.log(2)) self.assertAlmostEqual(tfidf_docs[0]['is'], 1 * math.log(1)) empty_sa = tc.text_analytics.tf_idf(tc.SArray()) self.assertEqual(len(empty_sa), 0) empty_dict_sf = tc.text_analytics.tf_idf(tc.SArray([{}])) assert len(empty_dict_sf) == 1 assert len(empty_dict_sf.apply(lambda x: len(x) == 0)) == 1 class RandomWordSplitTest(unittest.TestCase): """ Test that the random split utility in the text analytics toolkit works properly. """ @classmethod def setUpClass(self): self.docs = tc.SArray([{'a': 3, 'b': 5}, {'b': 5, 'c': 7}, {'a': 2, 'd': 3}]) def test_random_split(self): """ Test that the random split utility in the text analytics toolkit works properly. """ train, test = tc.text_analytics.random_split(self.docs) assert len(train) == len(self.docs) assert len(test) == len(self.docs) # Iterate through each doc and each word for i in range(len(self.docs)): a = train[i] b = test[i] # Make sure there are no zero values for (k, v) in a.items(): assert v != 0 for (k, v) in b.items(): assert v != 0 # Make sure the counts add up to the original counts for (k, v) in self.docs[i].items(): av = 0 bv = 0 if k in a: av = a[k] if k in b: bv = b[k] assert v == av + bv # Check that a low probability puts fewer items in the test set train, test = tc.text_analytics.random_split(self.docs, prob=.001) total_in_train = train.dict_values().apply(lambda x: sum(x)).sum() total_in_test = test.dict_values().apply(lambda x: sum(x)).sum() assert total_in_train > total_in_test class RetrievalTest(unittest.TestCase): """ Test document retrieval functions in the `text_analytics` toolkit. """ @classmethod def setUpClass(self): self.data = tc.SArray([{'a':5, 'b':7, 'c':10}, {'a':3, 'c':1, 'd':2}, {'a':10, 'b':3, 'e':5}, {'a':1}, {'f':5}]) def test_bm25(self): """ Check correctness of the BM2.5 query. """ # Test input formats query = ['a','b','c'] assert tc.text_analytics.bm25(self.data, query) is not None query = tc.SArray(['a','b','c']) assert tc.text_analytics.bm25(self.data, query) is not None query = {'a':5, 'b':3, 'c':1} assert tc.text_analytics.bm25(self.data, query) is not None # Only documents containing query words are included in result assert tc.text_analytics.bm25(self.data, query).num_rows() == 4 dataset = tc.SArray([ {'a':5, 'b':7, 'c':10}, {'a':3, 'c':1, 'd':2}, None, {'a':1}, {'f':5}]) res = tc.text_analytics.bm25(dataset, query) assert res.num_rows() == 3
#!/usr/bin/env python3 import sys import os import re """ This script accepts a list of gene or transcript symbol/synonyms and converts them into one or more FlyBase IDs. The synonyms file can be download from: ftp://ftp.flybase.org/releases/current/precomputed_files/synonyms/ Usage: ./symbol_to_id_lookup.py your_symbol_list.txt flybase_synonym_file.tsv > output.tsv Assumptions: * Only gene or transcript symbols/synonyms/names. * Drosophila melanogaster only Author: Josh Goodman <jogoodma@iu.edu> """ def insert_symbol(symbol: str, fbid: str, dict: dict): """ Modifies the dictionary in place by inserting the symbol as the key and the fbid as the value. If the symbol is already present in the dictionary the fbid is added to the unique set of FlyBase IDs in the value :param symbol:str - A single symbol to insert into the dictionary. :param fbid:str - A single FlyBase ID. :param dict:dict - The dictionary reference to modify. :return: None """ if symbol and symbol not in dict: # If we haven't seen this symbol before initialize the set. dict[symbol] = {fbid} elif symbol: # We have seen this symbol before so we add it to the set. dict[symbol].add(fbid) return None def generate_inverted_symbol_dict(sym_file: str): """ Generates an inverted dictionary of all symbols, synonyms, names, etc. as keys and a set of FBids as values. :param sym_file: str - The FlyBase synonyms file to parse. :return: The inverted symbol/synonym dictionary. """ """ Regex to split name synonyms on commas without spaces. Commas without a trailing space indicate a new name. Commas with a trailing space indicate a name with a comma in it. e.g. my gene1,my gene2 -> ['my gene1', 'my gene2'] my gene1, my gene2 -> ['my gene1, my gene2'] """ # Match commas that are not followed by a space. comma_ns_re = re.compile(r',(?!\s)') # Init the dictionary. symbol_dict = {} # Open file and loop over lines. with open(sym_file, "r") as file: for line in file: line = line.strip() # This script only cares about genes or transcripts ignore the rest. if line.startswith('FBgn') or line.startswith('FBtr'): # Split out the ID column and all the others. fbid, *cols = line.split('\t') try: col_len = len(cols) # Dmel only. if cols[0] != 'Dmel': continue # Symbol insert_symbol(cols[1], fbid, symbol_dict) # Fullname if col_len >= 3 and cols[2]: insert_symbol(cols[2], fbid, symbol_dict) # Fullname synonyms if col_len >= 4 and cols[3]: [insert_symbol(syn, fbid, symbol_dict) for syn in comma_ns_re.split(cols[3])] # Symbol synonyms if col_len >= 5 and cols[4]: [insert_symbol(syn, fbid, symbol_dict) for syn in comma_ns_re.split(cols[4])] except IndexError: print(f'Formatting problem found in line:\n{line}', file=sys.stderr) continue return symbol_dict if __name__ == '__main__': try: # Read in arguments. symbols_to_check, fb_synonym = sys.argv[1:3] # Generate the inverted dictionary. inverted_symbol_dict = generate_inverted_symbol_dict(fb_synonym) # Open their symbol file and loop over it. with open(symbols_to_check, 'r') as file: for symbol in file: symbol = symbol.strip() try: # Fetch the ID set for the symbol in their list. ids = inverted_symbol_dict[symbol] # Print out results. print(f"{symbol}\t{",".join(ids)}") except KeyError: # Symbol doesn't exist in dictionary. print(f"{symbol}") except ValueError: print(f"Usage: {os.path.basename(__file__)} your_symbols.txt fb_synonym.tsv", file=sys.stderr)
#!/usr/bin/env python3 import sys import os import re """ This script accepts a list of gene or transcript symbol/synonyms and converts them into one or more FlyBase IDs. The synonyms file can be download from: ftp://ftp.flybase.org/releases/current/precomputed_files/synonyms/ Usage: ./symbol_to_id_lookup.py your_symbol_list.txt flybase_synonym_file.tsv > output.tsv Assumptions: * Only gene or transcript symbols/synonyms/names. * Drosophila melanogaster only Author: Josh Goodman <jogoodma@iu.edu> """ def insert_symbol(symbol: str, fbid: str, dict: dict): """ Modifies the dictionary in place by inserting the symbol as the key and the fbid as the value. If the symbol is already present in the dictionary the fbid is added to the unique set of FlyBase IDs in the value :param symbol:str - A single symbol to insert into the dictionary. :param fbid:str - A single FlyBase ID. :param dict:dict - The dictionary reference to modify. :return: None """ if symbol and symbol not in dict: # If we haven't seen this symbol before initialize the set. dict[symbol] = {fbid} elif symbol: # We have seen this symbol before so we add it to the set. dict[symbol].add(fbid) return None def generate_inverted_symbol_dict(sym_file: str): """ Generates an inverted dictionary of all symbols, synonyms, names, etc. as keys and a set of FBids as values. :param sym_file: str - The FlyBase synonyms file to parse. :return: The inverted symbol/synonym dictionary. """ """ Regex to split name synonyms on commas without spaces. Commas without a trailing space indicate a new name. Commas with a trailing space indicate a name with a comma in it. e.g. my gene1,my gene2 -> ['my gene1', 'my gene2'] my gene1, my gene2 -> ['my gene1, my gene2'] """ # Match commas that are not followed by a space. comma_ns_re = re.compile(r',(?!\s)') # Init the dictionary. symbol_dict = {} # Open file and loop over lines. with open(sym_file, "r") as file: for line in file: line = line.strip() # This script only cares about genes or transcripts ignore the rest. if line.startswith('FBgn') or line.startswith('FBtr'): # Split out the ID column and all the others. fbid, *cols = line.split('\t') try: col_len = len(cols) # Dmel only. if cols[0] != 'Dmel': continue # Symbol insert_symbol(cols[1], fbid, symbol_dict) # Fullname if col_len >= 3 and cols[2]: insert_symbol(cols[2], fbid, symbol_dict) # Fullname synonyms if col_len >= 4 and cols[3]: [insert_symbol(syn, fbid, symbol_dict) for syn in comma_ns_re.split(cols[3])] # Symbol synonyms if col_len >= 5 and cols[4]: [insert_symbol(syn, fbid, symbol_dict) for syn in comma_ns_re.split(cols[4])] except IndexError: print(f'Formatting problem found in line:\n{line}', file=sys.stderr) continue return symbol_dict if __name__ == '__main__': try: # Read in arguments. symbols_to_check, fb_synonym = sys.argv[1:3] # Generate the inverted dictionary. inverted_symbol_dict = generate_inverted_symbol_dict(fb_synonym) # Open their symbol file and loop over it. with open(symbols_to_check, 'r') as file: for symbol in file: symbol = symbol.strip() try: # Fetch the ID set for the symbol in their list. ids = inverted_symbol_dict[symbol] # Print out results. print(f"{symbol}\t{','.join(ids)}") except KeyError: # Symbol doesn't exist in dictionary. print(f"{symbol}") except ValueError: print(f"Usage: {os.path.basename(__file__)} your_symbols.txt fb_synonym.tsv", file=sys.stderr)
"""Complete either attribute names or file names. Either on demand or after a user-selected delay after a key character, pop up a list of candidates. """ import __main__ import keyword import os import string import sys # Modified keyword list is used in fetch_completions. completion_kwds = [s for s in keyword.kwlist if s not in {'True', 'False', 'None'}] # In builtins. completion_kwds.extend(('match', 'case')) # Context keywords. completion_kwds.sort() # Two types of completions; defined here for autocomplete_w import below. ATTRS, FILES = 0, 1 from idlelib import autocomplete_w from idlelib.config import idleConf from idlelib.hyperparser import HyperParser # Tuples passed to open_completions. # EvalFunc, Complete, WantWin, Mode FORCE = True, False, True, None # Control-Space. TAB = False, True, True, None # Tab. TRY_A = False, False, False, ATTRS # '.' for attributes. TRY_F = False, False, False, FILES # '/' in quotes for file name. # This string includes all chars that may be in an identifier. # TODO Update this here and elsewhere. ID_CHARS = string.ascii_letters + string.digits + "_" SEPS = f"{os.sep}{os.altsep if os.altsep else ""}" TRIGGERS = f".{SEPS}" class AutoComplete: def __init__(self, editwin=None, tags=None): self.editwin = editwin if editwin is not None: # not in subprocess or no-gui test self.text = editwin.text self.tags = tags self.autocompletewindow = None # id of delayed call, and the index of the text insert when # the delayed call was issued. If _delayed_completion_id is # None, there is no delayed call. self._delayed_completion_id = None self._delayed_completion_index = None @classmethod def reload(cls): cls.popupwait = idleConf.GetOption( "extensions", "AutoComplete", "popupwait", type="int", default=0) def _make_autocomplete_window(self): # Makes mocking easier. return autocomplete_w.AutoCompleteWindow(self.text, tags=self.tags) def _remove_autocomplete_window(self, event=None): if self.autocompletewindow: self.autocompletewindow.hide_window() self.autocompletewindow = None def force_open_completions_event(self, event): "(^space) Open completion list, even if a function call is needed." self.open_completions(FORCE) return "break" def autocomplete_event(self, event): "(tab) Complete word or open list if multiple options." if hasattr(event, "mc_state") and event.mc_state or\ not self.text.get("insert linestart", "insert").strip(): # A modifier was pressed along with the tab or # there is only previous whitespace on this line, so tab. return None if self.autocompletewindow and self.autocompletewindow.is_active(): self.autocompletewindow.complete() return "break" else: opened = self.open_completions(TAB) return "break" if opened else None def try_open_completions_event(self, event=None): "(./) Open completion list after pause with no movement." lastchar = self.text.get("insert-1c") if lastchar in TRIGGERS: args = TRY_A if lastchar == "." else TRY_F self._delayed_completion_index = self.text.index("insert") if self._delayed_completion_id is not None: self.text.after_cancel(self._delayed_completion_id) self._delayed_completion_id = self.text.after( self.popupwait, self._delayed_open_completions, args) def _delayed_open_completions(self, args): "Call open_completions if index unchanged." self._delayed_completion_id = None if self.text.index("insert") == self._delayed_completion_index: self.open_completions(args) def open_completions(self, args): """Find the completions and create the AutoCompleteWindow. Return True if successful (no syntax error or so found). If complete is True, then if there's nothing to complete and no start of completion, won't open completions and return False. If mode is given, will open a completion list only in this mode. """ evalfuncs, complete, wantwin, mode = args # Cancel another delayed call, if it exists. if self._delayed_completion_id is not None: self.text.after_cancel(self._delayed_completion_id) self._delayed_completion_id = None hp = HyperParser(self.editwin, "insert") curline = self.text.get("insert linestart", "insert") i = j = len(curline) if hp.is_in_string() and (not mode or mode==FILES): # Find the beginning of the string. # fetch_completions will look at the file system to determine # whether the string value constitutes an actual file name # XXX could consider raw strings here and unescape the string # value if it's not raw. self._remove_autocomplete_window() mode = FILES # Find last separator or string start while i and curline[i-1] not in "'\"" + SEPS: i -= 1 comp_start = curline[i:j] j = i # Find string start while i and curline[i-1] not in "'\"": i -= 1 comp_what = curline[i:j] elif hp.is_in_code() and (not mode or mode==ATTRS): self._remove_autocomplete_window() mode = ATTRS while i and (curline[i-1] in ID_CHARS or ord(curline[i-1]) > 127): i -= 1 comp_start = curline[i:j] if i and curline[i-1] == '.': # Need object with attributes. hp.set_index("insert-%dc" % (len(curline)-(i-1))) comp_what = hp.get_expression() if (not comp_what or (not evalfuncs and comp_what.find('(') != -1)): return None else: comp_what = "" else: return None if complete and not comp_what and not comp_start: return None comp_lists = self.fetch_completions(comp_what, mode) if not comp_lists[0]: return None self.autocompletewindow = self._make_autocomplete_window() return not self.autocompletewindow.show_window( comp_lists, "insert-%dc" % len(comp_start), complete, mode, wantwin) def fetch_completions(self, what, mode): """Return a pair of lists of completions for something. The first list is a sublist of the second. Both are sorted. If there is a Python subprocess, get the comp. list there. Otherwise, either fetch_completions() is running in the subprocess itself or it was called in an IDLE EditorWindow before any script had been run. The subprocess environment is that of the most recently run script. If two unrelated modules are being edited some calltips in the current module may be inoperative if the module was not the last to run. """ try: rpcclt = self.editwin.flist.pyshell.interp.rpcclt except: rpcclt = None if rpcclt: return rpcclt.remotecall("exec", "get_the_completion_list", (what, mode), {}) else: if mode == ATTRS: if what == "": # Main module names. namespace = {**__main__.__builtins__.__dict__, **__main__.__dict__} bigl = eval("dir()", namespace) bigl.extend(completion_kwds) bigl.sort() if "__all__" in bigl: smalll = sorted(eval("__all__", namespace)) else: smalll = [s for s in bigl if s[:1] != '_'] else: try: entity = self.get_entity(what) bigl = dir(entity) bigl.sort() if "__all__" in bigl: smalll = sorted(entity.__all__) else: smalll = [s for s in bigl if s[:1] != '_'] except: return [], [] elif mode == FILES: if what == "": what = "." try: expandedpath = os.path.expanduser(what) bigl = os.listdir(expandedpath) bigl.sort() smalll = [s for s in bigl if s[:1] != '.'] except OSError: return [], [] if not smalll: smalll = bigl return smalll, bigl def get_entity(self, name): "Lookup name in a namespace spanning sys.modules and __main.dict__." return eval(name, {**sys.modules, **__main__.__dict__}) AutoComplete.reload() if __name__ == '__main__': from unittest import main main('idlelib.idle_test.test_autocomplete', verbosity=2)
"""Complete either attribute names or file names. Either on demand or after a user-selected delay after a key character, pop up a list of candidates. """ import __main__ import keyword import os import string import sys # Modified keyword list is used in fetch_completions. completion_kwds = [s for s in keyword.kwlist if s not in {'True', 'False', 'None'}] # In builtins. completion_kwds.extend(('match', 'case')) # Context keywords. completion_kwds.sort() # Two types of completions; defined here for autocomplete_w import below. ATTRS, FILES = 0, 1 from idlelib import autocomplete_w from idlelib.config import idleConf from idlelib.hyperparser import HyperParser # Tuples passed to open_completions. # EvalFunc, Complete, WantWin, Mode FORCE = True, False, True, None # Control-Space. TAB = False, True, True, None # Tab. TRY_A = False, False, False, ATTRS # '.' for attributes. TRY_F = False, False, False, FILES # '/' in quotes for file name. # This string includes all chars that may be in an identifier. # TODO Update this here and elsewhere. ID_CHARS = string.ascii_letters + string.digits + "_" SEPS = f"{os.sep}{os.altsep if os.altsep else ''}" TRIGGERS = f".{SEPS}" class AutoComplete: def __init__(self, editwin=None, tags=None): self.editwin = editwin if editwin is not None: # not in subprocess or no-gui test self.text = editwin.text self.tags = tags self.autocompletewindow = None # id of delayed call, and the index of the text insert when # the delayed call was issued. If _delayed_completion_id is # None, there is no delayed call. self._delayed_completion_id = None self._delayed_completion_index = None @classmethod def reload(cls): cls.popupwait = idleConf.GetOption( "extensions", "AutoComplete", "popupwait", type="int", default=0) def _make_autocomplete_window(self): # Makes mocking easier. return autocomplete_w.AutoCompleteWindow(self.text, tags=self.tags) def _remove_autocomplete_window(self, event=None): if self.autocompletewindow: self.autocompletewindow.hide_window() self.autocompletewindow = None def force_open_completions_event(self, event): "(^space) Open completion list, even if a function call is needed." self.open_completions(FORCE) return "break" def autocomplete_event(self, event): "(tab) Complete word or open list if multiple options." if hasattr(event, "mc_state") and event.mc_state or\ not self.text.get("insert linestart", "insert").strip(): # A modifier was pressed along with the tab or # there is only previous whitespace on this line, so tab. return None if self.autocompletewindow and self.autocompletewindow.is_active(): self.autocompletewindow.complete() return "break" else: opened = self.open_completions(TAB) return "break" if opened else None def try_open_completions_event(self, event=None): "(./) Open completion list after pause with no movement." lastchar = self.text.get("insert-1c") if lastchar in TRIGGERS: args = TRY_A if lastchar == "." else TRY_F self._delayed_completion_index = self.text.index("insert") if self._delayed_completion_id is not None: self.text.after_cancel(self._delayed_completion_id) self._delayed_completion_id = self.text.after( self.popupwait, self._delayed_open_completions, args) def _delayed_open_completions(self, args): "Call open_completions if index unchanged." self._delayed_completion_id = None if self.text.index("insert") == self._delayed_completion_index: self.open_completions(args) def open_completions(self, args): """Find the completions and create the AutoCompleteWindow. Return True if successful (no syntax error or so found). If complete is True, then if there's nothing to complete and no start of completion, won't open completions and return False. If mode is given, will open a completion list only in this mode. """ evalfuncs, complete, wantwin, mode = args # Cancel another delayed call, if it exists. if self._delayed_completion_id is not None: self.text.after_cancel(self._delayed_completion_id) self._delayed_completion_id = None hp = HyperParser(self.editwin, "insert") curline = self.text.get("insert linestart", "insert") i = j = len(curline) if hp.is_in_string() and (not mode or mode==FILES): # Find the beginning of the string. # fetch_completions will look at the file system to determine # whether the string value constitutes an actual file name # XXX could consider raw strings here and unescape the string # value if it's not raw. self._remove_autocomplete_window() mode = FILES # Find last separator or string start while i and curline[i-1] not in "'\"" + SEPS: i -= 1 comp_start = curline[i:j] j = i # Find string start while i and curline[i-1] not in "'\"": i -= 1 comp_what = curline[i:j] elif hp.is_in_code() and (not mode or mode==ATTRS): self._remove_autocomplete_window() mode = ATTRS while i and (curline[i-1] in ID_CHARS or ord(curline[i-1]) > 127): i -= 1 comp_start = curline[i:j] if i and curline[i-1] == '.': # Need object with attributes. hp.set_index("insert-%dc" % (len(curline)-(i-1))) comp_what = hp.get_expression() if (not comp_what or (not evalfuncs and comp_what.find('(') != -1)): return None else: comp_what = "" else: return None if complete and not comp_what and not comp_start: return None comp_lists = self.fetch_completions(comp_what, mode) if not comp_lists[0]: return None self.autocompletewindow = self._make_autocomplete_window() return not self.autocompletewindow.show_window( comp_lists, "insert-%dc" % len(comp_start), complete, mode, wantwin) def fetch_completions(self, what, mode): """Return a pair of lists of completions for something. The first list is a sublist of the second. Both are sorted. If there is a Python subprocess, get the comp. list there. Otherwise, either fetch_completions() is running in the subprocess itself or it was called in an IDLE EditorWindow before any script had been run. The subprocess environment is that of the most recently run script. If two unrelated modules are being edited some calltips in the current module may be inoperative if the module was not the last to run. """ try: rpcclt = self.editwin.flist.pyshell.interp.rpcclt except: rpcclt = None if rpcclt: return rpcclt.remotecall("exec", "get_the_completion_list", (what, mode), {}) else: if mode == ATTRS: if what == "": # Main module names. namespace = {**__main__.__builtins__.__dict__, **__main__.__dict__} bigl = eval("dir()", namespace) bigl.extend(completion_kwds) bigl.sort() if "__all__" in bigl: smalll = sorted(eval("__all__", namespace)) else: smalll = [s for s in bigl if s[:1] != '_'] else: try: entity = self.get_entity(what) bigl = dir(entity) bigl.sort() if "__all__" in bigl: smalll = sorted(entity.__all__) else: smalll = [s for s in bigl if s[:1] != '_'] except: return [], [] elif mode == FILES: if what == "": what = "." try: expandedpath = os.path.expanduser(what) bigl = os.listdir(expandedpath) bigl.sort() smalll = [s for s in bigl if s[:1] != '.'] except OSError: return [], [] if not smalll: smalll = bigl return smalll, bigl def get_entity(self, name): "Lookup name in a namespace spanning sys.modules and __main.dict__." return eval(name, {**sys.modules, **__main__.__dict__}) AutoComplete.reload() if __name__ == '__main__': from unittest import main main('idlelib.idle_test.test_autocomplete', verbosity=2)
"""Calculate ROUGE score.""" # Copyright 2020 Huawei Technologies Co., Ltd # # 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 # # http://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. # ============================================================================ from typing import List from rouge import Rouge def get_rouge_score(hypothesis: List[str], target: List[str]): """ Calculate ROUGE score. Args: hypothesis (List[str]): Inference result. target (List[str]): Reference. """ if not hypothesis or not target: raise ValueError(f"`hypothesis` and `target` can not be None.") _rouge = Rouge() print("hypothesis:", hypothesis) print("target:", target) scores = _rouge.get_scores(hypothesis, target, avg=True) print(" | ROUGE Score:") print(f" | RG-1(F): {scores["rouge-1"]["f"] * 100:8.2f}") print(f" | RG-2(F): {scores["rouge-2"]["f"] * 100:8.2f}") print(f" | RG-L(F): {scores["rouge-l"]["f"] * 100:8.2f}") return scores
"""Calculate ROUGE score.""" # Copyright 2020 Huawei Technologies Co., Ltd # # 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 # # http://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. # ============================================================================ from typing import List from rouge import Rouge def get_rouge_score(hypothesis: List[str], target: List[str]): """ Calculate ROUGE score. Args: hypothesis (List[str]): Inference result. target (List[str]): Reference. """ if not hypothesis or not target: raise ValueError(f"`hypothesis` and `target` can not be None.") _rouge = Rouge() print("hypothesis:", hypothesis) print("target:", target) scores = _rouge.get_scores(hypothesis, target, avg=True) print(" | ROUGE Score:") print(f" | RG-1(F): {scores['rouge-1']['f'] * 100:8.2f}") print(f" | RG-2(F): {scores['rouge-2']['f'] * 100:8.2f}") print(f" | RG-L(F): {scores['rouge-l']['f'] * 100:8.2f}") return scores
import difflib import io import os import re import sys import unicodedata import pytest from tests.helpers.test_utils import * from neoload_cli_lib import displayer @pytest.mark.results @pytest.mark.usefixtures("neoload_login") # it's like @Before on the neoload_login function class TestDisplayer: def test_print_result_summary_no_sla(self, monkeypatch): captured_output = io.StringIO() # Create StringIO object sys.stdout = captured_output # and redirect stdout. json_result = json.loads( '{"id": "d30fdcc2-319e-4be5-818e-f1978907a3ce","name": "SLA test","description": "","author": "Anakin Skywalker","terminationReason": "POLICY","lgCount": 1,"project": "Sample_Project","scenario": "WANImpact Local","status": "TERMINATED","qualityStatus": "FAILED","startDate": 1517410739300,"endDate": 1517411040416,"duration": 301116}') sla_json_global = json.loads('[]') sla_json_test = json.loads('[]') sla_json_interval = json.loads('[]') json_stats = json.loads( '{"totalRequestCountSuccess": 8415,"totalRequestCountFailure": 93,"totalRequestDurationAverage": 85.36695,"totalRequestCountPerSecond": 28.254892,"totalTransactionCountSuccess": 405,"totalTransactionCountFailure": 93,"totalTransactionDurationAverage": 571.5201,"totalTransactionCountPerSecond": 1.6538477,"totalIterationCountSuccess": 77,"totalIterationCountFailure": 77,"totalGlobalDownloadedBytes": 115011235,"totalGlobalDownloadedBytesPerSecond": 381949.94,"totalGlobalCountFailure": 93}') displayer.print_result_summary(json_result, sla_json_global, sla_json_test, sla_json_interval, json_stats) ## when storing output to file ## with open("tests/resources/expected_summary_text_no_sla.txt", mode='w') as f: print(captured_output.getvalue(), file=f) comp = compare_texts("", "") # initialize default for scoping with open("tests/resources/expected_summary_text_no_sla.txt", "r") as expected: comp = compare_texts(expected.read(), captured_output.getvalue()) sys.stdout = sys.__stdout__ # Reset redirect. captured_output.close() assert comp["equivalent"], comp["details"] def test_print_result_summary_with_sla(self, monkeypatch): captured_output = io.StringIO() # Create StringIO object sys.stdout = captured_output # and redirect stdout. json_result = json.loads( '{"id": "d30fdcc2-319e-4be5-818e-f1978907a3ce","name": "SLA test","description": "","author": "Anakin Skywalker","terminationReason": "POLICY","lgCount": 1,"project": "Sample_Project","scenario": "WANImpact Local","status": "TERMINATED","qualityStatus": "FAILED","startDate": 1517410739300,"endDate": 1517411040416,"duration": 301116}') sla_json_global = json.loads( '[{"kpi": "avg-request-resp-time","status": "PASSED","value": 0.085,"warningThreshold": {"operator": ">=","value": 0.1},"failedThreshold": {"operator": ">=","value": 0.5}}]') sla_json_test = json.loads( '[{"kpi": "error-rate","status": "FAILED","value": 6.097561,"warningThreshold": {"operator": ">=","value": 2},"failedThreshold": {"operator": ">=","value": 5},"element": {"elementId": "eb1cee2c-2f37-43f7-a2bd-92cc6990f92f","name": "submit","category": "TRANSACTION","userpath": "BrowserUser_Create_report","parent": "Try"}}, {"kpi": "avg-request-per-sec","status": "WARNING","value": 12.056263,"warningThreshold": {"operator": "<=","value": 25},"element": {"elementId": "fa450a25-8880-4263-8332-81999821711e","name": "/media/js/jquery.pngFix.pack.js","category": "REQUEST","userpath": "BrowserUser_Create_report","parent": "/"}}, {"kpi": "error-rate","status": "PASSED","value": 0,"warningThreshold": {"operator": ">=","value": 2},"failedThreshold": {"operator": ">=","value": 5},"element": {"elementId": "50e8a36f-2b86-45f7-8c9c-4b7af66051b6","name": "/media/js/ushahidi.js","category": "REQUEST","userpath": "BrowserUser_Create_report","parent": "/"}}]') sla_json_interval = json.loads( '[{"kpi": "avg-resp-time","status": "FAILED","warning": 100,"warningThreshold": {"operator": ">=","value": 0.05},"failed": 23.809525,"failedThreshold": {"operator": ">=","value": 0.5},"element": {"elementId": "03f084cd-b579-4284-97fc-8901cdb9f58c","name": "/media/js/OpenLayers.js","category": "REQUEST","userpath": "BrowserUser_Create_report","parent": "/"}}, {"kpi": "avg-resp-time","status": "WARNING","warning": 7.3170733,"warningThreshold": {"operator": ">=","value": 0.05},"failed": 0,"failedThreshold": {"operator": ">=","value": 0.5},"element": {"elementId": "269a00b9-25fa-4aa5-9481-d3ffde7b2ed7","name": "/media/img/colorpicker/colorpicker_rgb_g.png","category": "REQUEST","userpath": "BrowserUser_Create_report","parent": "/media/img/icon-calendar.gif"}}, {"kpi": "error-rate","status": "PASSED","warning": 0,"warningThreshold": {"operator": ">=","value": 5},"failed": 0,"failedThreshold": {"operator": ">=","value": 10},"element": {"elementId": "b8bfc48e-b7ed-48f8-b5ea-404d3faf15cb","name": "/media/js/jquery.js","category": "REQUEST","userpath": "BrowserUser_Create_report","parent": "/"}}]') json_stats = json.loads( '{"totalRequestCountSuccess": 8415,"totalRequestCountFailure": 93,"totalRequestDurationAverage": 85.36695,"totalRequestCountPerSecond": 28.254892,"totalTransactionCountSuccess": 405,"totalTransactionCountFailure": 93,"totalTransactionDurationAverage": 571.5201,"totalTransactionCountPerSecond": 1.6538477,"totalIterationCountSuccess": 77,"totalIterationCountFailure": 77,"totalGlobalDownloadedBytes": 115011235,"totalGlobalDownloadedBytesPerSecond": 381949.94,"totalGlobalCountFailure": 93}') displayer.print_result_summary(json_result, sla_json_global, sla_json_test, sla_json_interval, json_stats) ## when storing output to file ## with open("tests/resources/expected_summary_text_with_sla.txt", mode='w') as f: print(captured_output.getvalue(), file=f) comp = compare_texts("", "") # initialize default for scoping with open("tests/resources/expected_summary_text_with_sla.txt", "r") as expected: comp = compare_texts(expected.read(), captured_output.getvalue()) sys.stdout = sys.__stdout__ # Reset redirect. captured_output.close() assert comp["equivalent"], comp["details"] def test_print_result_junit(self, monkeypatch): json_result = json.loads( '{"id": "d30fdcc2-319e-4be5-818e-f1978907a3ce","name": "SLA test","description": "","author": "Anakin Skywalker","terminationReason": "POLICY","lgCount": 1,"project": "Sample_Project","scenario": "WANImpact Local","status": "TERMINATED","qualityStatus": "FAILED","startDate": 1517410739300,"endDate": 1517411040416,"duration": 301116}') sla_json_global = json.loads( '[{"kpi": "avg-request-resp-time","status": "PASSED","value": 0.085,"warningThreshold": {"operator": ">=","value": 0.1},"failedThreshold": {"operator": ">=","value": 0.5}}]') sla_json_test = json.loads( '[{"kpi": "error-rate","status": "FAILED","value": 6.097561,"warningThreshold": {"operator": ">=","value": 2},"failedThreshold": {"operator": ">=","value": 5},"element": {"elementId": "eb1cee2c-2f37-43f7-a2bd-92cc6990f92f","name": "submit","category": "TRANSACTION","userpath": "BrowserUser_Create_report","parent": "Try"}}, {"kpi": "avg-request-per-sec","status": "WARNING","value": 12.056263,"warningThreshold": {"operator": "<=","value": 25},"element": {"elementId": "fa450a25-8880-4263-8332-81999821711e","name": "/media/js/jquery.pngFix.pack.js","category": "REQUEST","userpath": "BrowserUser_Create_report","parent": "/"}}, {"kpi": "error-rate","status": "PASSED","value": 0,"warningThreshold": {"operator": ">=","value": 2},"failedThreshold": {"operator": ">=","value": 5},"element": {"elementId": "50e8a36f-2b86-45f7-8c9c-4b7af66051b6","name": "/media/js/ushahidi.js","category": "REQUEST","userpath": "BrowserUser_Create_report","parent": "/"}}]') sla_json_interval = json.loads( '[{"kpi": "avg-resp-time","status": "FAILED","warning": 100,"warningThreshold": {"operator": ">=","value": 0.05},"failed": 23.809525,"failedThreshold": {"operator": ">=","value": 0.5},"element": {"elementId": "03f084cd-b579-4284-97fc-8901cdb9f58c","name": "/media/js/OpenLayers.js","category": "REQUEST","userpath": "BrowserUser_Create_report","parent": "/"}}, {"kpi": "avg-resp-time","status": "WARNING","warning": 7.3170733,"warningThreshold": {"operator": ">=","value": 0.05},"failed": 0,"failedThreshold": {"operator": ">=","value": 0.5},"element": {"elementId": "269a00b9-25fa-4aa5-9481-d3ffde7b2ed7","name": "/media/img/colorpicker/colorpicker_rgb_g.png","category": "REQUEST","userpath": "BrowserUser_Create_report","parent": "/media/img/icon-calendar.gif"}}, {"kpi": "error-rate","status": "PASSED","warning": 0,"warningThreshold": {"operator": ">=","value": 5},"failed": 0,"failedThreshold": {"operator": ">=","value": 10},"element": {"elementId": "b8bfc48e-b7ed-48f8-b5ea-404d3faf15cb","name": "/media/js/jquery.js","category": "REQUEST","userpath": "BrowserUser_Create_report","parent": "/"}}]') try: result_file_path = "tests/resources/tmp_neoload_junit_slas.xml" displayer.print_result_junit(json_result, sla_json_test, sla_json_interval, sla_json_global, result_file_path) expected_file_path = "tests/resources/expected_neoload_junit_slas.xml" # equivalent = main.diff_files(result_file_path, expected_file_path) == [] diff_result = diff_file(result_file_path, expected_file_path) finally: os.unlink(result_file_path) sys.stdout = sys.__stdout__ # Reset redirect. print('\n'.join(diff_result)) assert list(diff_result) == [] def diff_file(file1, file2): text1 = open(file1).readlines() text2 = open(file2).readlines() return difflib.unified_diff(text1, text2) # created to handle color control characters; == equivalency is too strict def compare_texts(a, b): ret = { "equivalent": True, "details": "" } a_re = remove_color_indicators(a) b_re = remove_color_indicators(b) for i, s in enumerate(difflib.ndiff(a_re, b_re)): w = remove_control_characters(s[-1]).strip() if s[0] == ' ': continue elif s[0] == '-': ret["details"] += u'Delete "{}" from position {}'.format(s[-1], i) elif s[0] == '+': ret["details"] += u'Add "{}" to position {}'.format(s[-1], i) if s[0] in ['-', '+'] and len(w) > 0: ret["equivalent"] = False ret["details"] += w + ":" break return ret def remove_control_characters(s): return "".join(ch for ch in s if unicodedata.category(ch)[0] != "C") def remove_color_indicators(s): return re.sub(r'(\[[0123456789]{1,2}m)', '', s)
import difflib import io import os import re import sys import unicodedata import pytest from tests.helpers.test_utils import * from neoload_cli_lib import displayer @pytest.mark.results @pytest.mark.usefixtures("neoload_login") # it's like @Before on the neoload_login function class TestDisplayer: def test_print_result_summary_no_sla(self, monkeypatch): captured_output = io.StringIO() # Create StringIO object sys.stdout = captured_output # and redirect stdout. json_result = json.loads( '{"id": "d30fdcc2-319e-4be5-818e-f1978907a3ce","name": "SLA test","description": "","author": "Anakin Skywalker","terminationReason": "POLICY","lgCount": 1,"project": "Sample_Project","scenario": "WANImpact Local","status": "TERMINATED","qualityStatus": "FAILED","startDate": 1517410739300,"endDate": 1517411040416,"duration": 301116}') sla_json_global = json.loads('[]') sla_json_test = json.loads('[]') sla_json_interval = json.loads('[]') json_stats = json.loads( '{"totalRequestCountSuccess": 8415,"totalRequestCountFailure": 93,"totalRequestDurationAverage": 85.36695,"totalRequestCountPerSecond": 28.254892,"totalTransactionCountSuccess": 405,"totalTransactionCountFailure": 93,"totalTransactionDurationAverage": 571.5201,"totalTransactionCountPerSecond": 1.6538477,"totalIterationCountSuccess": 77,"totalIterationCountFailure": 77,"totalGlobalDownloadedBytes": 115011235,"totalGlobalDownloadedBytesPerSecond": 381949.94,"totalGlobalCountFailure": 93}') displayer.print_result_summary(json_result, sla_json_global, sla_json_test, sla_json_interval, json_stats) ## when storing output to file ## with open("tests/resources/expected_summary_text_no_sla.txt", mode='w') as f: print(captured_output.getvalue(), file=f) comp = compare_texts("", "") # initialize default for scoping with open("tests/resources/expected_summary_text_no_sla.txt", "r") as expected: comp = compare_texts(expected.read(), captured_output.getvalue()) sys.stdout = sys.__stdout__ # Reset redirect. captured_output.close() assert comp["equivalent"], comp["details"] def test_print_result_summary_with_sla(self, monkeypatch): captured_output = io.StringIO() # Create StringIO object sys.stdout = captured_output # and redirect stdout. json_result = json.loads( '{"id": "d30fdcc2-319e-4be5-818e-f1978907a3ce","name": "SLA test","description": "","author": "Anakin Skywalker","terminationReason": "POLICY","lgCount": 1,"project": "Sample_Project","scenario": "WANImpact Local","status": "TERMINATED","qualityStatus": "FAILED","startDate": 1517410739300,"endDate": 1517411040416,"duration": 301116}') sla_json_global = json.loads( '[{"kpi": "avg-request-resp-time","status": "PASSED","value": 0.085,"warningThreshold": {"operator": ">=","value": 0.1},"failedThreshold": {"operator": ">=","value": 0.5}}]') sla_json_test = json.loads( '[{"kpi": "error-rate","status": "FAILED","value": 6.097561,"warningThreshold": {"operator": ">=","value": 2},"failedThreshold": {"operator": ">=","value": 5},"element": {"elementId": "eb1cee2c-2f37-43f7-a2bd-92cc6990f92f","name": "submit","category": "TRANSACTION","userpath": "BrowserUser_Create_report","parent": "Try"}}, {"kpi": "avg-request-per-sec","status": "WARNING","value": 12.056263,"warningThreshold": {"operator": "<=","value": 25},"element": {"elementId": "fa450a25-8880-4263-8332-81999821711e","name": "/media/js/jquery.pngFix.pack.js","category": "REQUEST","userpath": "BrowserUser_Create_report","parent": "/"}}, {"kpi": "error-rate","status": "PASSED","value": 0,"warningThreshold": {"operator": ">=","value": 2},"failedThreshold": {"operator": ">=","value": 5},"element": {"elementId": "50e8a36f-2b86-45f7-8c9c-4b7af66051b6","name": "/media/js/ushahidi.js","category": "REQUEST","userpath": "BrowserUser_Create_report","parent": "/"}}]') sla_json_interval = json.loads( '[{"kpi": "avg-resp-time","status": "FAILED","warning": 100,"warningThreshold": {"operator": ">=","value": 0.05},"failed": 23.809525,"failedThreshold": {"operator": ">=","value": 0.5},"element": {"elementId": "03f084cd-b579-4284-97fc-8901cdb9f58c","name": "/media/js/OpenLayers.js","category": "REQUEST","userpath": "BrowserUser_Create_report","parent": "/"}}, {"kpi": "avg-resp-time","status": "WARNING","warning": 7.3170733,"warningThreshold": {"operator": ">=","value": 0.05},"failed": 0,"failedThreshold": {"operator": ">=","value": 0.5},"element": {"elementId": "269a00b9-25fa-4aa5-9481-d3ffde7b2ed7","name": "/media/img/colorpicker/colorpicker_rgb_g.png","category": "REQUEST","userpath": "BrowserUser_Create_report","parent": "/media/img/icon-calendar.gif"}}, {"kpi": "error-rate","status": "PASSED","warning": 0,"warningThreshold": {"operator": ">=","value": 5},"failed": 0,"failedThreshold": {"operator": ">=","value": 10},"element": {"elementId": "b8bfc48e-b7ed-48f8-b5ea-404d3faf15cb","name": "/media/js/jquery.js","category": "REQUEST","userpath": "BrowserUser_Create_report","parent": "/"}}]') json_stats = json.loads( '{"totalRequestCountSuccess": 8415,"totalRequestCountFailure": 93,"totalRequestDurationAverage": 85.36695,"totalRequestCountPerSecond": 28.254892,"totalTransactionCountSuccess": 405,"totalTransactionCountFailure": 93,"totalTransactionDurationAverage": 571.5201,"totalTransactionCountPerSecond": 1.6538477,"totalIterationCountSuccess": 77,"totalIterationCountFailure": 77,"totalGlobalDownloadedBytes": 115011235,"totalGlobalDownloadedBytesPerSecond": 381949.94,"totalGlobalCountFailure": 93}') displayer.print_result_summary(json_result, sla_json_global, sla_json_test, sla_json_interval, json_stats) ## when storing output to file ## with open("tests/resources/expected_summary_text_with_sla.txt", mode='w') as f: print(captured_output.getvalue(), file=f) comp = compare_texts("", "") # initialize default for scoping with open("tests/resources/expected_summary_text_with_sla.txt", "r") as expected: comp = compare_texts(expected.read(), captured_output.getvalue()) sys.stdout = sys.__stdout__ # Reset redirect. captured_output.close() assert comp["equivalent"], comp["details"] def test_print_result_junit(self, monkeypatch): json_result = json.loads( '{"id": "d30fdcc2-319e-4be5-818e-f1978907a3ce","name": "SLA test","description": "","author": "Anakin Skywalker","terminationReason": "POLICY","lgCount": 1,"project": "Sample_Project","scenario": "WANImpact Local","status": "TERMINATED","qualityStatus": "FAILED","startDate": 1517410739300,"endDate": 1517411040416,"duration": 301116}') sla_json_global = json.loads( '[{"kpi": "avg-request-resp-time","status": "PASSED","value": 0.085,"warningThreshold": {"operator": ">=","value": 0.1},"failedThreshold": {"operator": ">=","value": 0.5}}]') sla_json_test = json.loads( '[{"kpi": "error-rate","status": "FAILED","value": 6.097561,"warningThreshold": {"operator": ">=","value": 2},"failedThreshold": {"operator": ">=","value": 5},"element": {"elementId": "eb1cee2c-2f37-43f7-a2bd-92cc6990f92f","name": "submit","category": "TRANSACTION","userpath": "BrowserUser_Create_report","parent": "Try"}}, {"kpi": "avg-request-per-sec","status": "WARNING","value": 12.056263,"warningThreshold": {"operator": "<=","value": 25},"element": {"elementId": "fa450a25-8880-4263-8332-81999821711e","name": "/media/js/jquery.pngFix.pack.js","category": "REQUEST","userpath": "BrowserUser_Create_report","parent": "/"}}, {"kpi": "error-rate","status": "PASSED","value": 0,"warningThreshold": {"operator": ">=","value": 2},"failedThreshold": {"operator": ">=","value": 5},"element": {"elementId": "50e8a36f-2b86-45f7-8c9c-4b7af66051b6","name": "/media/js/ushahidi.js","category": "REQUEST","userpath": "BrowserUser_Create_report","parent": "/"}}]') sla_json_interval = json.loads( '[{"kpi": "avg-resp-time","status": "FAILED","warning": 100,"warningThreshold": {"operator": ">=","value": 0.05},"failed": 23.809525,"failedThreshold": {"operator": ">=","value": 0.5},"element": {"elementId": "03f084cd-b579-4284-97fc-8901cdb9f58c","name": "/media/js/OpenLayers.js","category": "REQUEST","userpath": "BrowserUser_Create_report","parent": "/"}}, {"kpi": "avg-resp-time","status": "WARNING","warning": 7.3170733,"warningThreshold": {"operator": ">=","value": 0.05},"failed": 0,"failedThreshold": {"operator": ">=","value": 0.5},"element": {"elementId": "269a00b9-25fa-4aa5-9481-d3ffde7b2ed7","name": "/media/img/colorpicker/colorpicker_rgb_g.png","category": "REQUEST","userpath": "BrowserUser_Create_report","parent": "/media/img/icon-calendar.gif"}}, {"kpi": "error-rate","status": "PASSED","warning": 0,"warningThreshold": {"operator": ">=","value": 5},"failed": 0,"failedThreshold": {"operator": ">=","value": 10},"element": {"elementId": "b8bfc48e-b7ed-48f8-b5ea-404d3faf15cb","name": "/media/js/jquery.js","category": "REQUEST","userpath": "BrowserUser_Create_report","parent": "/"}}]') try: result_file_path = "tests/resources/tmp_neoload_junit_slas.xml" displayer.print_result_junit(json_result, sla_json_test, sla_json_interval, sla_json_global, result_file_path) expected_file_path = "tests/resources/expected_neoload_junit_slas.xml" # equivalent = main.diff_files(result_file_path, expected_file_path) == [] diff_result = diff_file(result_file_path, expected_file_path) finally: os.unlink(result_file_path) sys.stdout = sys.__stdout__ # Reset redirect. print('\n'.join(diff_result)) assert list(diff_result) == [] def diff_file(file1, file2): text1 = open(file1).readlines() text2 = open(file2).readlines() return difflib.unified_diff(text1, text2) # created to handle color control characters; == equivalency is too strict def compare_texts(a, b): ret = { "equivalent": True, "details": "" } a_re = remove_color_indicators(a) b_re = remove_color_indicators(b) for i, s in enumerate(difflib.ndiff(a_re, b_re)): w = remove_control_characters(s[-1]).strip() if s[0] == ' ': continue elif s[0] == '-': ret["details"] += u'Delete "{}" from position {}'.format(s[-1], i) elif s[0] == '+': ret["details"] += u'Add "{}" to position {}'.format(s[-1], i) if s[0] in ['-', '+'] and len(w) > 0: ret["equivalent"] = False ret["details"] += w + ":" break return ret def remove_control_characters(s): return "".join(ch for ch in s if unicodedata.category(ch)[0] != "C") def remove_color_indicators(s): return re.sub(r'(\[[0123456789]{1,2}m)', '', s)
# -*- coding: utf-8 -*- import io import demjson import pandas as pd import requests from zvt.contract.api import df_to_db from zvt.contract.recorder import Recorder from zvt.utils.time_utils import to_pd_timestamp, now_pd_timestamp from zvt.api.quote import china_stock_code_to_id from zvt.domain import IndexStock, Index class ChinaIndexListSpider(Recorder): data_schema = IndexStock def __init__(self, batch_size=10, force_update=False, sleeping_time=2.0, provider='exchange') -> None: self.provider = provider super().__init__(batch_size, force_update, sleeping_time) def run(self): # 上证、中证 self.fetch_csi_index() # 深证 # self.fetch_szse_index() # 国证 # FIXME:已不可用 # self.fetch_cni_index() def fetch_csi_index(self) -> None: """ 抓取上证、中证指数列表 """ url = 'http://www.csindex.com.cn/zh-CN/indices/index' \ '?page={}&page_size={}&data_type=json&class_1=1&class_2=2&class_7=7&class_10=10' index_list = [] page = 1 page_size = 50 while True: query_url = url.format(page, page_size) response = requests.get(query_url) response_dict = demjson.decode(response.text) response_index_list = response_dict.get('list', []) if len(response_index_list) == 0: break index_list.extend(response_index_list) self.logger.info(f'上证、中证指数第 {page} 页抓取完成...') page += 1 self.sleep() df = pd.DataFrame(index_list) df = df[['base_date', 'base_point', 'index_code', 'indx_sname', 'online_date', 'class_eseries']].copy() df.columns = ['timestamp', 'base_point', 'code', 'name', 'list_date', 'class_eseries'] df['category'] = df['class_eseries'].apply(lambda x: x.split(' ')[0].lower()) df = df.drop('class_eseries', axis=1) df = df.loc[df['code'].str.contains(r'^\d{6}$')] self.persist_index(df) self.logger.info('上证、中证指数列表抓取完成...') # 抓取上证、中证指数成分股 self.fetch_csi_index_component(df) self.logger.info('上证、中证指数成分股抓取完成...') def fetch_csi_index_component(self, df: pd.DataFrame): """ 抓取上证、中证指数成分股 """ query_url = 'http://www.csindex.com.cn/uploads/file/autofile/cons/{}cons.xls' for _, index in df.iterrows(): index_code = index['code'] url = query_url.format(index_code) try: response = requests.get(url) response.raise_for_status() except requests.HTTPError as error: self.logger.error(f'{index['name']} - {index_code} 成分股抓取错误 ({error})') continue response_df = pd.read_excel(io.BytesIO(response.content)) response_df = response_df[['成分券代码Constituent Code', '成分券名称Constituent Name']].rename( columns={'成分券代码Constituent Code': 'stock_code', '成分券名称Constituent Name': 'stock_name'}) index_id = f'index_cn_{index_code}' response_df['entity_id'] = index_id response_df['entity_type'] = 'index' response_df['exchange'] = 'cn' response_df['code'] = index_code response_df['name'] = index['name'] response_df['timestamp'] = now_pd_timestamp() response_df['stock_id'] = response_df['stock_code'].apply(lambda x: china_stock_code_to_id(str(x))) response_df['id'] = response_df['stock_id'].apply( lambda x: f'{index_id}_{x}') df_to_db(data_schema=self.data_schema, df=response_df, provider=self.provider, force_update=True) self.logger.info(f'{index['name']} - {index_code} 成分股抓取完成...') self.sleep() def fetch_szse_index(self) -> None: """ 抓取深证指数列表 """ url = 'http://www.szse.cn/api/report/ShowReport?SHOWTYPE=xlsx&CATALOGID=1812_zs&TABKEY=tab1' response = requests.get(url) df = pd.read_excel(io.BytesIO(response.content), dtype='str') df.columns = ['code', 'name', 'timestamp', 'base_point', 'list_date'] df['category'] = 'szse' df = df.loc[df['code'].str.contains(r'^\d{6}$')] self.persist_index(df) self.logger.info('深证指数列表抓取完成...') # 抓取深证指数成分股 self.fetch_szse_index_component(df) self.logger.info('深证指数成分股抓取完成...') def fetch_szse_index_component(self, df: pd.DataFrame): """ 抓取深证指数成分股 """ query_url = 'http://www.szse.cn/api/report/ShowReport?SHOWTYPE=xlsx&CATALOGID=1747_zs&TABKEY=tab1&ZSDM={}' for _, index in df.iterrows(): index_code = index['code'] url = query_url.format(index_code) response = requests.get(url) response_df = pd.read_excel(io.BytesIO(response.content), dtype='str') index_id = f'index_cn_{index_code}' response_df['entity_id'] = index_id response_df['entity_type'] = 'index' response_df['exchange'] = 'cn' response_df['code'] = index_code response_df['name'] = index['name'] response_df['timestamp'] = now_pd_timestamp() response_df.rename(columns={'证券代码': 'stock_code', '证券简称': 'stock_name'}, inplace=True) response_df['stock_id'] = response_df['stock_code'].apply(lambda x: china_stock_code_to_id(str(x))) response_df['id'] = response_df['stock_id'].apply( lambda x: f'{index_id}_{x}') df_to_db(data_schema=self.data_schema, df=response_df, provider=self.provider) self.logger.info(f'{index['name']} - {index_code} 成分股抓取完成...') self.sleep() def fetch_cni_index(self) -> None: """ 抓取国证指数列表 """ url = 'http://www.cnindex.com.cn/zstx/jcxl/' response = requests.get(url) response.encoding = 'utf-8' dfs = pd.read_html(response.text) # 第 9 个 table 之后为非股票指数 dfs = dfs[1:9] result_df = pd.DataFrame() for df in dfs: header = df.iloc[0] df = df[1:] df.columns = header df.astype('str') result_df = pd.concat([result_df, df]) result_df = result_df.drop('样本股数量', axis=1) result_df.columns = ['name', 'code', 'timestamp', 'base_point', 'list_date'] result_df['timestamp'] = result_df['timestamp'].apply(lambda x: x.replace('-', '')) result_df['list_date'] = result_df['list_date'].apply(lambda x: x.replace('-', '')) result_df['category'] = 'csi' result_df = result_df.loc[result_df['code'].str.contains(r'^\d{6}$')] self.persist_index(result_df) self.logger.info('国证指数列表抓取完成...') # 抓取国证指数成分股 self.fetch_cni_index_component(result_df) self.logger.info('国证指数成分股抓取完成...') def fetch_cni_index_component(self, df: pd.DataFrame): """ 抓取国证指数成分股 """ query_url = 'http://www.cnindex.com.cn/docs/yb_{}.xls' for _, index in df.iterrows(): index_code = index['code'] url = query_url.format(index_code) try: response = requests.get(url) response.raise_for_status() except requests.HTTPError as error: self.logger.error(f'{index['name']} - {index_code} 成分股抓取错误 ({error})') continue response_df = pd.read_excel(io.BytesIO(response.content), dtype='str') index_id = f'index_cn_{index_code}' try: response_df = response_df[['样本股代码']] except KeyError: response_df = response_df[['证券代码']] response_df['entity_id'] = index_id response_df['entity_type'] = 'index' response_df['exchange'] = 'cn' response_df['code'] = index_code response_df['name'] = index['name'] response_df['timestamp'] = now_pd_timestamp() response_df.columns = ['stock_code'] response_df['stock_id'] = response_df['stock_code'].apply(lambda x: china_stock_code_to_id(str(x))) response_df['id'] = response_df['stock_id'].apply( lambda x: f'{index_id}_{x}') df_to_db(data_schema=self.data_schema, df=response_df, provider=self.provider) self.logger.info(f'{index['name']} - {index_code} 成分股抓取完成...') self.sleep() def persist_index(self, df) -> None: df['timestamp'] = df['timestamp'].apply(lambda x: to_pd_timestamp(x)) df['list_date'] = df['list_date'].apply(lambda x: to_pd_timestamp(x)) df['id'] = df['code'].apply(lambda code: f'index_cn_{code}') df['entity_id'] = df['id'] df['exchange'] = 'cn' df['entity_type'] = 'index' df = df.dropna(axis=0, how='any') df = df.drop_duplicates(subset='id', keep='last') df_to_db(df=df, data_schema=Index, provider=self.provider, force_update=False) __all__ = ['ChinaIndexListSpider'] if __name__ == '__main__': spider = ChinaIndexListSpider(provider='exchange') spider.run()
# -*- coding: utf-8 -*- import io import demjson import pandas as pd import requests from zvt.contract.api import df_to_db from zvt.contract.recorder import Recorder from zvt.utils.time_utils import to_pd_timestamp, now_pd_timestamp from zvt.api.quote import china_stock_code_to_id from zvt.domain import IndexStock, Index class ChinaIndexListSpider(Recorder): data_schema = IndexStock def __init__(self, batch_size=10, force_update=False, sleeping_time=2.0, provider='exchange') -> None: self.provider = provider super().__init__(batch_size, force_update, sleeping_time) def run(self): # 上证、中证 self.fetch_csi_index() # 深证 # self.fetch_szse_index() # 国证 # FIXME:已不可用 # self.fetch_cni_index() def fetch_csi_index(self) -> None: """ 抓取上证、中证指数列表 """ url = 'http://www.csindex.com.cn/zh-CN/indices/index' \ '?page={}&page_size={}&data_type=json&class_1=1&class_2=2&class_7=7&class_10=10' index_list = [] page = 1 page_size = 50 while True: query_url = url.format(page, page_size) response = requests.get(query_url) response_dict = demjson.decode(response.text) response_index_list = response_dict.get('list', []) if len(response_index_list) == 0: break index_list.extend(response_index_list) self.logger.info(f'上证、中证指数第 {page} 页抓取完成...') page += 1 self.sleep() df = pd.DataFrame(index_list) df = df[['base_date', 'base_point', 'index_code', 'indx_sname', 'online_date', 'class_eseries']].copy() df.columns = ['timestamp', 'base_point', 'code', 'name', 'list_date', 'class_eseries'] df['category'] = df['class_eseries'].apply(lambda x: x.split(' ')[0].lower()) df = df.drop('class_eseries', axis=1) df = df.loc[df['code'].str.contains(r'^\d{6}$')] self.persist_index(df) self.logger.info('上证、中证指数列表抓取完成...') # 抓取上证、中证指数成分股 self.fetch_csi_index_component(df) self.logger.info('上证、中证指数成分股抓取完成...') def fetch_csi_index_component(self, df: pd.DataFrame): """ 抓取上证、中证指数成分股 """ query_url = 'http://www.csindex.com.cn/uploads/file/autofile/cons/{}cons.xls' for _, index in df.iterrows(): index_code = index['code'] url = query_url.format(index_code) try: response = requests.get(url) response.raise_for_status() except requests.HTTPError as error: self.logger.error(f'{index["name"]} - {index_code} 成分股抓取错误 ({error})') continue response_df = pd.read_excel(io.BytesIO(response.content)) response_df = response_df[['成分券代码Constituent Code', '成分券名称Constituent Name']].rename( columns={'成分券代码Constituent Code': 'stock_code', '成分券名称Constituent Name': 'stock_name'}) index_id = f'index_cn_{index_code}' response_df['entity_id'] = index_id response_df['entity_type'] = 'index' response_df['exchange'] = 'cn' response_df['code'] = index_code response_df['name'] = index['name'] response_df['timestamp'] = now_pd_timestamp() response_df['stock_id'] = response_df['stock_code'].apply(lambda x: china_stock_code_to_id(str(x))) response_df['id'] = response_df['stock_id'].apply( lambda x: f'{index_id}_{x}') df_to_db(data_schema=self.data_schema, df=response_df, provider=self.provider, force_update=True) self.logger.info(f'{index["name"]} - {index_code} 成分股抓取完成...') self.sleep() def fetch_szse_index(self) -> None: """ 抓取深证指数列表 """ url = 'http://www.szse.cn/api/report/ShowReport?SHOWTYPE=xlsx&CATALOGID=1812_zs&TABKEY=tab1' response = requests.get(url) df = pd.read_excel(io.BytesIO(response.content), dtype='str') df.columns = ['code', 'name', 'timestamp', 'base_point', 'list_date'] df['category'] = 'szse' df = df.loc[df['code'].str.contains(r'^\d{6}$')] self.persist_index(df) self.logger.info('深证指数列表抓取完成...') # 抓取深证指数成分股 self.fetch_szse_index_component(df) self.logger.info('深证指数成分股抓取完成...') def fetch_szse_index_component(self, df: pd.DataFrame): """ 抓取深证指数成分股 """ query_url = 'http://www.szse.cn/api/report/ShowReport?SHOWTYPE=xlsx&CATALOGID=1747_zs&TABKEY=tab1&ZSDM={}' for _, index in df.iterrows(): index_code = index['code'] url = query_url.format(index_code) response = requests.get(url) response_df = pd.read_excel(io.BytesIO(response.content), dtype='str') index_id = f'index_cn_{index_code}' response_df['entity_id'] = index_id response_df['entity_type'] = 'index' response_df['exchange'] = 'cn' response_df['code'] = index_code response_df['name'] = index['name'] response_df['timestamp'] = now_pd_timestamp() response_df.rename(columns={'证券代码': 'stock_code', '证券简称': 'stock_name'}, inplace=True) response_df['stock_id'] = response_df['stock_code'].apply(lambda x: china_stock_code_to_id(str(x))) response_df['id'] = response_df['stock_id'].apply( lambda x: f'{index_id}_{x}') df_to_db(data_schema=self.data_schema, df=response_df, provider=self.provider) self.logger.info(f'{index["name"]} - {index_code} 成分股抓取完成...') self.sleep() def fetch_cni_index(self) -> None: """ 抓取国证指数列表 """ url = 'http://www.cnindex.com.cn/zstx/jcxl/' response = requests.get(url) response.encoding = 'utf-8' dfs = pd.read_html(response.text) # 第 9 个 table 之后为非股票指数 dfs = dfs[1:9] result_df = pd.DataFrame() for df in dfs: header = df.iloc[0] df = df[1:] df.columns = header df.astype('str') result_df = pd.concat([result_df, df]) result_df = result_df.drop('样本股数量', axis=1) result_df.columns = ['name', 'code', 'timestamp', 'base_point', 'list_date'] result_df['timestamp'] = result_df['timestamp'].apply(lambda x: x.replace('-', '')) result_df['list_date'] = result_df['list_date'].apply(lambda x: x.replace('-', '')) result_df['category'] = 'csi' result_df = result_df.loc[result_df['code'].str.contains(r'^\d{6}$')] self.persist_index(result_df) self.logger.info('国证指数列表抓取完成...') # 抓取国证指数成分股 self.fetch_cni_index_component(result_df) self.logger.info('国证指数成分股抓取完成...') def fetch_cni_index_component(self, df: pd.DataFrame): """ 抓取国证指数成分股 """ query_url = 'http://www.cnindex.com.cn/docs/yb_{}.xls' for _, index in df.iterrows(): index_code = index['code'] url = query_url.format(index_code) try: response = requests.get(url) response.raise_for_status() except requests.HTTPError as error: self.logger.error(f'{index["name"]} - {index_code} 成分股抓取错误 ({error})') continue response_df = pd.read_excel(io.BytesIO(response.content), dtype='str') index_id = f'index_cn_{index_code}' try: response_df = response_df[['样本股代码']] except KeyError: response_df = response_df[['证券代码']] response_df['entity_id'] = index_id response_df['entity_type'] = 'index' response_df['exchange'] = 'cn' response_df['code'] = index_code response_df['name'] = index['name'] response_df['timestamp'] = now_pd_timestamp() response_df.columns = ['stock_code'] response_df['stock_id'] = response_df['stock_code'].apply(lambda x: china_stock_code_to_id(str(x))) response_df['id'] = response_df['stock_id'].apply( lambda x: f'{index_id}_{x}') df_to_db(data_schema=self.data_schema, df=response_df, provider=self.provider) self.logger.info(f'{index["name"]} - {index_code} 成分股抓取完成...') self.sleep() def persist_index(self, df) -> None: df['timestamp'] = df['timestamp'].apply(lambda x: to_pd_timestamp(x)) df['list_date'] = df['list_date'].apply(lambda x: to_pd_timestamp(x)) df['id'] = df['code'].apply(lambda code: f'index_cn_{code}') df['entity_id'] = df['id'] df['exchange'] = 'cn' df['entity_type'] = 'index' df = df.dropna(axis=0, how='any') df = df.drop_duplicates(subset='id', keep='last') df_to_db(df=df, data_schema=Index, provider=self.provider, force_update=False) __all__ = ['ChinaIndexListSpider'] if __name__ == '__main__': spider = ChinaIndexListSpider(provider='exchange') spider.run()
import inspect import os from collections import defaultdict from keyword import iskeyword from os.path import join, exists from typing import Any, Union import inflect import sqlalchemy from sqlalchemy import ForeignKeyConstraint, CheckConstraint, ForeignKey, Column from sqlalchemy.util import OrderedDict from .utils import string_camelcase, string_lowercase_underscore inflect_engine = inflect.engine() class SqlToModelGenerator: def __init__(self, name, metadata, indent=4, bind=None): self.name = name self.metadata = metadata self.indent = ' ' * indent self.bind = bind self.collector = None many_to_many_tables = set() many_to_many_links = defaultdict(list) for table in metadata.tables.values(): fk_constraints = [i for i in table.constraints if isinstance(i, ForeignKeyConstraint)] if len(fk_constraints) == 2 and all(col.foreign_keys for col in table.columns): many_to_many_tables.add(table.name) tablename = sorted(fk_constraints, key=get_constraint_sort_key)[0].elements[0].column.table.name many_to_many_links[tablename].append(table) self.models = {} for table in metadata.sorted_tables: if table.name in many_to_many_tables: continue self.models[table.name] = Model(table, many_to_many_links[table.name]) # Add many-to-one relations for constraint in sorted(table.constraints, key=get_constraint_sort_key): if isinstance(constraint, ForeignKeyConstraint): self.models[constraint.elements[0].column.table.name].add_one_to_many_relation(constraint) self.models[constraint.table.name].add_many_to_one_relation(constraint) def render(self, path): if not exists(path): os.makedirs(path) model_modules = [] for model in self.models.values(): module_name = convert_to_valid_identifier(model.table.name) with open(join(path, module_name + '.py'), 'w', encoding='utf-8') as f: self.collector = ImportCollector() pending = [] tables_content = self.render_secondary_tables(model) if tables_content: pending.append('\n') pending.append(tables_content) pending.append('\n\n') pending.append(self.render_model(model)) f.write(self.render_imports()) for p in pending: f.write(p) model_modules.append({'module': module_name, 'class': model.class_name}) with open(join(path, '__init__.py'), 'w', encoding='utf-8') as f: for m in model_modules: f.write(f'from .{m['module']} import {m['class']}\n') def render_imports(self): self.collector.add_import('BaseModelMixin', 'guniflask.orm') imports = '' for k, vlist in self.collector.items(): for v in vlist: if isinstance(v, tuple): imports += f'from {k} import {v[0]} as {v[1]}\n' else: imports += f'from {k} import {v}\n' if len(self.collector) > 0: imports += '\n' imports += f'from {self.name}.app import db\n' return imports def render_model(self, model): header_str = f'class {model.class_name}(BaseModelMixin, db.Model):\n' header_str += f"{self.indent}__tablename__ = '{model.table.name}'\n" if self.bind: header_str += f"{self.indent}__bind_key__ = '{self.bind}'\n" header_str += '\n' columns_str = '' for col in model.table.columns: attr = convert_to_valid_identifier(col.name) show_name = attr != col.name columns_str += f'{self.indent}{attr} = {self.render_column(col, show_name=show_name)}\n' relationships_str = '' for r in model.relationships: relationships_str += self.indent + self.render_relationship(r) + '\n' return header_str + columns_str + relationships_str def render_secondary_tables(self, model): return '\n'.join([self.render_table(r.association_table) for r in model.relationships if isinstance(r, ManyToManyRelationship)]) def render_table(self, table): columns_str = ',\n'.join(self.indent + self.render_column(col, show_name=True) for col in table.columns) tablename = convert_to_valid_identifier(table.name) return f'{tablename} = db.Table({table.name!r},\n{columns_str}\n)\n' def render_column(self, column, show_name=False): if column.server_default: self.collector.add_import(('text', '_text'), 'sqlalchemy') self.collector.add_import(column.type) is_sole_pk = column.primary_key and len(column.table.primary_key) == 1 dedicated_fks = [c for c in column.foreign_keys if len(c.constraint.columns) == 1] is_unique = ColumnUtils.is_unique(column) has_index = ColumnUtils.has_index(column) server_default = None render_coltype = not dedicated_fks or any(fk.column is column for fk in dedicated_fks) kwargs = [] if column.key != column.name: kwargs.append('key') if column.primary_key: kwargs.append('primary_key') if column.autoincrement is True: kwargs.append('autoincrement') if not column.nullable and not is_sole_pk: kwargs.append('nullable') if is_unique: column.unique = True kwargs.append('unique') if has_index: column.index = True kwargs.append('index') if column.comment: kwargs.append('comment') if column.server_default: default_expr = self.get_compiled_expression(column.server_default.arg) if '\n' in default_expr: server_default = f'server_default=_text("""\\\n{default_expr}""")' else: default_expr = default_expr.replace('"', '\\"') server_default = f'server_default=_text("{default_expr}")' return "db.Column({})".format( ', '.join( ([repr(column.name)] if show_name else []) + ([self.render_column_type(column.type)] if render_coltype else []) + [self.render_constraint(x) for x in dedicated_fks] + [f'{i}={getattr(column, i)!r}' for i in kwargs] + ([server_default] if server_default else []) ) ) def render_column_type(self, coltype): argspec = inspect.getfullargspec(coltype.__class__.__init__) defaults = dict( zip( argspec.args[-len(argspec.defaults or ()):], argspec.defaults or (), ) ) args = [] kwargs = OrderedDict() use_kwargs = False missing = object() for attr in argspec.args[1:]: if attr.startswith('_'): continue value = getattr(coltype, attr, missing) default = defaults.get(attr, missing) if value is missing or value == default: use_kwargs = True else: if use_kwargs: kwargs[attr] = repr(value) else: args.append(repr(value)) self.collector.add_import(type(value)) if isinstance(coltype, sqlalchemy.Enum) and coltype.name is not None: kwargs['name'] = repr(coltype.name) for key, value in kwargs.items(): args.append('{}={}'.format(key, value)) rendered = coltype.__class__.__name__ if args: rendered += f'({', '.join(args)})' return rendered def render_constraint(self, constraint): def render_fk_options(*args): opts = [repr(i) for i in args] for attr in 'ondelete', 'onupdate': value = getattr(constraint, attr, None) if value: opts.append(f'{attr}={value!r}') return ', '.join(opts) if isinstance(constraint, ForeignKey): remote_column = f'{constraint.column.table.name}.{constraint.column.name}' return f'db.ForeignKey({render_fk_options(remote_column)})' def render_relationship(self, relationship): kwargs_str = ', '.join( [repr(table_name_to_class_name(relationship.target_tbl))] + [f'{i}={relationship.kwargs[i]}' for i in sorted(relationship.kwargs.keys())] ) return f'{relationship.preferred_name} = db.relationship({kwargs_str})' def get_compiled_expression(self, statement): return str(statement.compile( self.metadata.bind, compile_kwargs={"literal_binds": True})) def convert_to_valid_identifier(name): name = string_lowercase_underscore(name) if name[0].isdigit() or iskeyword(name): name = '_' + name return name def table_name_to_class_name(table_name): name = string_camelcase(table_name) if name[0].isdigit(): name = '_' + name return name def get_constraint_sort_key(constraint): if isinstance(constraint, CheckConstraint): return f'C{constraint.sqltext}' return constraint.__class__.__name__[0] + repr(list(constraint.columns.keys())) def is_one_to_one_relationship(constraint): if isinstance(constraint, ForeignKeyConstraint): if len(constraint.columns) == 1 and any(ColumnUtils.is_unique(col) for col in constraint.columns): return True return False class ColumnUtils: @staticmethod def is_unique(column: Column): return any(i.unique and set(i.columns) == {column} for i in column.table.indexes) @staticmethod def has_index(column: Column): return any(set(i.columns) == {column} for i in column.table.indexes) class Model: parent_name = 'db.Model' def __init__(self, table, association_tables): self.table = table self.class_name = table_name_to_class_name(table.name) self.relationships = [] # Add many-to-many relationships for association_table in association_tables: fk_constraints = [c for c in association_table.constraints if isinstance(c, ForeignKeyConstraint)] fk_constraints.sort(key=get_constraint_sort_key) target_tbl = fk_constraints[1].elements[0].column.table.name relationship = ManyToManyRelationship(self.table.name, target_tbl, association_table) self.relationships.append(relationship) def add_one_to_many_relation(self, constraint): relationship = OneToManyRelationship(self.table.name, constraint.table.name, constraint) self.relationships.append(relationship) def add_many_to_one_relation(self, constraint): relationship = ManyToOneRelationship(self.table.name, constraint.elements[0].column.table.name, constraint) self.relationships.append(relationship) class Relationship: def __init__(self, source_tbl, target_tbl): self.source_tbl = source_tbl self.target_tbl = target_tbl self.kwargs = {} self.preferred_name = None class ManyToOneRelationship(Relationship): def __init__(self, source_tbl, target_tbl, constraint): super().__init__(source_tbl, target_tbl) self.preferred_name = convert_to_valid_identifier(target_tbl) self.constraint = constraint self.kwargs['lazy'] = repr('joined') back_populates = convert_to_valid_identifier(source_tbl) if not is_one_to_one_relationship(constraint): back_populates = inflect_engine.plural(back_populates) self.kwargs['back_populates'] = repr(f'{back_populates}') class OneToManyRelationship(Relationship): def __init__(self, source_tbl, target_tbl, constraint): super().__init__(source_tbl, target_tbl) self.preferred_name = convert_to_valid_identifier(target_tbl) self.constraint = constraint # Add uselist=False to one-to-one relationships if is_one_to_one_relationship(constraint): self.kwargs['uselist'] = False self.kwargs['lazy'] = repr('joined') else: self.preferred_name = inflect_engine.plural(self.preferred_name) self.kwargs['lazy'] = repr('select') self.kwargs['back_populates'] = repr(f'{convert_to_valid_identifier(source_tbl)}') class ManyToManyRelationship(Relationship): def __init__(self, source_tbl, target_tbl, association_table): super().__init__(source_tbl, target_tbl) self.preferred_name = inflect_engine.plural(convert_to_valid_identifier(target_tbl)) self.association_table = association_table self.kwargs['secondary'] = convert_to_valid_identifier(association_table.name) self.kwargs['lazy'] = repr('select') self.kwargs['backref'] = "db.backref({}, lazy='select')".format( repr(inflect_engine.plural(convert_to_valid_identifier(source_tbl))) ) class ImportCollector(OrderedDict): def add_import(self, name: Any, pkg: Union[str, tuple] = None): if not isinstance(name, (str, tuple)): if inspect.isclass(name): obj_type = name else: obj_type = type(name) pkg = obj_type.__module__ name = obj_type.__name__ if pkg == 'builtins': return names = self.setdefault(pkg, set()) names.add(name)
import inspect import os from collections import defaultdict from keyword import iskeyword from os.path import join, exists from typing import Any, Union import inflect import sqlalchemy from sqlalchemy import ForeignKeyConstraint, CheckConstraint, ForeignKey, Column from sqlalchemy.util import OrderedDict from .utils import string_camelcase, string_lowercase_underscore inflect_engine = inflect.engine() class SqlToModelGenerator: def __init__(self, name, metadata, indent=4, bind=None): self.name = name self.metadata = metadata self.indent = ' ' * indent self.bind = bind self.collector = None many_to_many_tables = set() many_to_many_links = defaultdict(list) for table in metadata.tables.values(): fk_constraints = [i for i in table.constraints if isinstance(i, ForeignKeyConstraint)] if len(fk_constraints) == 2 and all(col.foreign_keys for col in table.columns): many_to_many_tables.add(table.name) tablename = sorted(fk_constraints, key=get_constraint_sort_key)[0].elements[0].column.table.name many_to_many_links[tablename].append(table) self.models = {} for table in metadata.sorted_tables: if table.name in many_to_many_tables: continue self.models[table.name] = Model(table, many_to_many_links[table.name]) # Add many-to-one relations for constraint in sorted(table.constraints, key=get_constraint_sort_key): if isinstance(constraint, ForeignKeyConstraint): self.models[constraint.elements[0].column.table.name].add_one_to_many_relation(constraint) self.models[constraint.table.name].add_many_to_one_relation(constraint) def render(self, path): if not exists(path): os.makedirs(path) model_modules = [] for model in self.models.values(): module_name = convert_to_valid_identifier(model.table.name) with open(join(path, module_name + '.py'), 'w', encoding='utf-8') as f: self.collector = ImportCollector() pending = [] tables_content = self.render_secondary_tables(model) if tables_content: pending.append('\n') pending.append(tables_content) pending.append('\n\n') pending.append(self.render_model(model)) f.write(self.render_imports()) for p in pending: f.write(p) model_modules.append({'module': module_name, 'class': model.class_name}) with open(join(path, '__init__.py'), 'w', encoding='utf-8') as f: for m in model_modules: f.write(f'from .{m["module"]} import {m["class"]}\n') def render_imports(self): self.collector.add_import('BaseModelMixin', 'guniflask.orm') imports = '' for k, vlist in self.collector.items(): for v in vlist: if isinstance(v, tuple): imports += f'from {k} import {v[0]} as {v[1]}\n' else: imports += f'from {k} import {v}\n' if len(self.collector) > 0: imports += '\n' imports += f'from {self.name}.app import db\n' return imports def render_model(self, model): header_str = f'class {model.class_name}(BaseModelMixin, db.Model):\n' header_str += f"{self.indent}__tablename__ = '{model.table.name}'\n" if self.bind: header_str += f"{self.indent}__bind_key__ = '{self.bind}'\n" header_str += '\n' columns_str = '' for col in model.table.columns: attr = convert_to_valid_identifier(col.name) show_name = attr != col.name columns_str += f'{self.indent}{attr} = {self.render_column(col, show_name=show_name)}\n' relationships_str = '' for r in model.relationships: relationships_str += self.indent + self.render_relationship(r) + '\n' return header_str + columns_str + relationships_str def render_secondary_tables(self, model): return '\n'.join([self.render_table(r.association_table) for r in model.relationships if isinstance(r, ManyToManyRelationship)]) def render_table(self, table): columns_str = ',\n'.join(self.indent + self.render_column(col, show_name=True) for col in table.columns) tablename = convert_to_valid_identifier(table.name) return f'{tablename} = db.Table({table.name!r},\n{columns_str}\n)\n' def render_column(self, column, show_name=False): if column.server_default: self.collector.add_import(('text', '_text'), 'sqlalchemy') self.collector.add_import(column.type) is_sole_pk = column.primary_key and len(column.table.primary_key) == 1 dedicated_fks = [c for c in column.foreign_keys if len(c.constraint.columns) == 1] is_unique = ColumnUtils.is_unique(column) has_index = ColumnUtils.has_index(column) server_default = None render_coltype = not dedicated_fks or any(fk.column is column for fk in dedicated_fks) kwargs = [] if column.key != column.name: kwargs.append('key') if column.primary_key: kwargs.append('primary_key') if column.autoincrement is True: kwargs.append('autoincrement') if not column.nullable and not is_sole_pk: kwargs.append('nullable') if is_unique: column.unique = True kwargs.append('unique') if has_index: column.index = True kwargs.append('index') if column.comment: kwargs.append('comment') if column.server_default: default_expr = self.get_compiled_expression(column.server_default.arg) if '\n' in default_expr: server_default = f'server_default=_text("""\\\n{default_expr}""")' else: default_expr = default_expr.replace('"', '\\"') server_default = f'server_default=_text("{default_expr}")' return "db.Column({})".format( ', '.join( ([repr(column.name)] if show_name else []) + ([self.render_column_type(column.type)] if render_coltype else []) + [self.render_constraint(x) for x in dedicated_fks] + [f'{i}={getattr(column, i)!r}' for i in kwargs] + ([server_default] if server_default else []) ) ) def render_column_type(self, coltype): argspec = inspect.getfullargspec(coltype.__class__.__init__) defaults = dict( zip( argspec.args[-len(argspec.defaults or ()):], argspec.defaults or (), ) ) args = [] kwargs = OrderedDict() use_kwargs = False missing = object() for attr in argspec.args[1:]: if attr.startswith('_'): continue value = getattr(coltype, attr, missing) default = defaults.get(attr, missing) if value is missing or value == default: use_kwargs = True else: if use_kwargs: kwargs[attr] = repr(value) else: args.append(repr(value)) self.collector.add_import(type(value)) if isinstance(coltype, sqlalchemy.Enum) and coltype.name is not None: kwargs['name'] = repr(coltype.name) for key, value in kwargs.items(): args.append('{}={}'.format(key, value)) rendered = coltype.__class__.__name__ if args: rendered += f'({", ".join(args)})' return rendered def render_constraint(self, constraint): def render_fk_options(*args): opts = [repr(i) for i in args] for attr in 'ondelete', 'onupdate': value = getattr(constraint, attr, None) if value: opts.append(f'{attr}={value!r}') return ', '.join(opts) if isinstance(constraint, ForeignKey): remote_column = f'{constraint.column.table.name}.{constraint.column.name}' return f'db.ForeignKey({render_fk_options(remote_column)})' def render_relationship(self, relationship): kwargs_str = ', '.join( [repr(table_name_to_class_name(relationship.target_tbl))] + [f'{i}={relationship.kwargs[i]}' for i in sorted(relationship.kwargs.keys())] ) return f'{relationship.preferred_name} = db.relationship({kwargs_str})' def get_compiled_expression(self, statement): return str(statement.compile( self.metadata.bind, compile_kwargs={"literal_binds": True})) def convert_to_valid_identifier(name): name = string_lowercase_underscore(name) if name[0].isdigit() or iskeyword(name): name = '_' + name return name def table_name_to_class_name(table_name): name = string_camelcase(table_name) if name[0].isdigit(): name = '_' + name return name def get_constraint_sort_key(constraint): if isinstance(constraint, CheckConstraint): return f'C{constraint.sqltext}' return constraint.__class__.__name__[0] + repr(list(constraint.columns.keys())) def is_one_to_one_relationship(constraint): if isinstance(constraint, ForeignKeyConstraint): if len(constraint.columns) == 1 and any(ColumnUtils.is_unique(col) for col in constraint.columns): return True return False class ColumnUtils: @staticmethod def is_unique(column: Column): return any(i.unique and set(i.columns) == {column} for i in column.table.indexes) @staticmethod def has_index(column: Column): return any(set(i.columns) == {column} for i in column.table.indexes) class Model: parent_name = 'db.Model' def __init__(self, table, association_tables): self.table = table self.class_name = table_name_to_class_name(table.name) self.relationships = [] # Add many-to-many relationships for association_table in association_tables: fk_constraints = [c for c in association_table.constraints if isinstance(c, ForeignKeyConstraint)] fk_constraints.sort(key=get_constraint_sort_key) target_tbl = fk_constraints[1].elements[0].column.table.name relationship = ManyToManyRelationship(self.table.name, target_tbl, association_table) self.relationships.append(relationship) def add_one_to_many_relation(self, constraint): relationship = OneToManyRelationship(self.table.name, constraint.table.name, constraint) self.relationships.append(relationship) def add_many_to_one_relation(self, constraint): relationship = ManyToOneRelationship(self.table.name, constraint.elements[0].column.table.name, constraint) self.relationships.append(relationship) class Relationship: def __init__(self, source_tbl, target_tbl): self.source_tbl = source_tbl self.target_tbl = target_tbl self.kwargs = {} self.preferred_name = None class ManyToOneRelationship(Relationship): def __init__(self, source_tbl, target_tbl, constraint): super().__init__(source_tbl, target_tbl) self.preferred_name = convert_to_valid_identifier(target_tbl) self.constraint = constraint self.kwargs['lazy'] = repr('joined') back_populates = convert_to_valid_identifier(source_tbl) if not is_one_to_one_relationship(constraint): back_populates = inflect_engine.plural(back_populates) self.kwargs['back_populates'] = repr(f'{back_populates}') class OneToManyRelationship(Relationship): def __init__(self, source_tbl, target_tbl, constraint): super().__init__(source_tbl, target_tbl) self.preferred_name = convert_to_valid_identifier(target_tbl) self.constraint = constraint # Add uselist=False to one-to-one relationships if is_one_to_one_relationship(constraint): self.kwargs['uselist'] = False self.kwargs['lazy'] = repr('joined') else: self.preferred_name = inflect_engine.plural(self.preferred_name) self.kwargs['lazy'] = repr('select') self.kwargs['back_populates'] = repr(f'{convert_to_valid_identifier(source_tbl)}') class ManyToManyRelationship(Relationship): def __init__(self, source_tbl, target_tbl, association_table): super().__init__(source_tbl, target_tbl) self.preferred_name = inflect_engine.plural(convert_to_valid_identifier(target_tbl)) self.association_table = association_table self.kwargs['secondary'] = convert_to_valid_identifier(association_table.name) self.kwargs['lazy'] = repr('select') self.kwargs['backref'] = "db.backref({}, lazy='select')".format( repr(inflect_engine.plural(convert_to_valid_identifier(source_tbl))) ) class ImportCollector(OrderedDict): def add_import(self, name: Any, pkg: Union[str, tuple] = None): if not isinstance(name, (str, tuple)): if inspect.isclass(name): obj_type = name else: obj_type = type(name) pkg = obj_type.__module__ name = obj_type.__name__ if pkg == 'builtins': return names = self.setdefault(pkg, set()) names.add(name)
import sys import json from pathlib import Path def main(): # parse command line arguments if (len(sys.argv) != 2): print(f'Usage: {Path(sys.argv[0]).name} <track_file_json>') exit(1) track_filepath = sys.argv[1] print(f'track_file: "{track_filepath}"') # parse track file with open(track_filepath, 'r', encoding='utf-8') as f: track_data = json.load(f) print(f'trackName: \'{track_data['trackName']}\'') print(f'trackBaseName: \'{track_data['trackBaseName']}\'') print(f'distance: {track_data['distance']}') print(f'numSegments: {track_data['numSegments']}') # modify track print('usage: <func> [<first=0> <last=n-1>] <value>') print('<func>: (t)emperature, (w)indSpeed, (s)ave, (q)uit') print('example: t 25.5 # set temperature to 25.5 for all segment') print('example: w 2 4 13 # set wind speed to 13 for segment 2~4') while True: print('> ', end='') try: input_line = input().strip().split() if len(input_line) == 0: continue func = input_line[0].lower() except EOFError: func = 'q' if func == 'q': break if func == 's': with open(track_filepath, 'w', encoding='utf-8') as f: json.dump(track_data, f, indent=2) continue key = {'t': 'temperature', 'w': 'windSpeed'}[func] value = float(input_line[-1]) first = int(input_line[1]) if len(input_line) > 2 else 0 last = int(input_line[2]) if len(input_line) > 2 else track_data['numSegments'] - 1 for i in range(first, last + 1): track_data['segments'][i][key] = value # save track data print('save...') with open(track_filepath, 'w', encoding='utf-8') as f: json.dump(track_data, f, indent=2) if __name__ == '__main__': main()
import sys import json from pathlib import Path def main(): # parse command line arguments if (len(sys.argv) != 2): print(f'Usage: {Path(sys.argv[0]).name} <track_file_json>') exit(1) track_filepath = sys.argv[1] print(f'track_file: "{track_filepath}"') # parse track file with open(track_filepath, 'r', encoding='utf-8') as f: track_data = json.load(f) print(f'trackName: \'{track_data["trackName"]}\'') print(f'trackBaseName: \'{track_data["trackBaseName"]}\'') print(f'distance: {track_data["distance"]}') print(f'numSegments: {track_data["numSegments"]}') # modify track print('usage: <func> [<first=0> <last=n-1>] <value>') print('<func>: (t)emperature, (w)indSpeed, (s)ave, (q)uit') print('example: t 25.5 # set temperature to 25.5 for all segment') print('example: w 2 4 13 # set wind speed to 13 for segment 2~4') while True: print('> ', end='') try: input_line = input().strip().split() if len(input_line) == 0: continue func = input_line[0].lower() except EOFError: func = 'q' if func == 'q': break if func == 's': with open(track_filepath, 'w', encoding='utf-8') as f: json.dump(track_data, f, indent=2) continue key = {'t': 'temperature', 'w': 'windSpeed'}[func] value = float(input_line[-1]) first = int(input_line[1]) if len(input_line) > 2 else 0 last = int(input_line[2]) if len(input_line) > 2 else track_data['numSegments'] - 1 for i in range(first, last + 1): track_data['segments'][i][key] = value # save track data print('save...') with open(track_filepath, 'w', encoding='utf-8') as f: json.dump(track_data, f, indent=2) if __name__ == '__main__': main()
from typing import Any, List from django.contrib.postgres.fields import JSONField, ArrayField from django.db import models as django_models from django.db.models import ( Q, BooleanField, DurationField, ) from django.db.models.fields.related import ManyToManyField, ForeignKey from baserow.core.registry import ( Instance, Registry, ModelInstanceMixin, ModelRegistryMixin, CustomFieldsInstanceMixin, CustomFieldsRegistryMixin, MapAPIExceptionsInstanceMixin, APIUrlsRegistryMixin, APIUrlsInstanceMixin, ImportExportMixin, ) from .dependencies.types import OptionalFieldDependencies from .exceptions import FieldTypeAlreadyRegistered, FieldTypeDoesNotExist from .models import SelectOption, Field class FieldType( MapAPIExceptionsInstanceMixin, APIUrlsInstanceMixin, CustomFieldsInstanceMixin, ModelInstanceMixin, ImportExportMixin, Instance, ): """ This abstract class represents a custom field type that can be added to the field type registry. It must be extended so customisation can be done. Each field type will have his own model that must extend the Field model, this is needed so that the user can set custom settings per field instance he has created. Example: from baserow.contrib.database.fields.models import Field from baserow.contrib.database.fields.registry import ( FieldType, field_type_registry ) class ExampleFieldModel(FieldType): pass class ExampleFieldType(FieldType): type = 'a-unique-field-type-name' model_class = ExampleFieldModel allowed_fields = ['text_default'] serializer_field_names = ['text_default'] serializer_field_overrides = { 'text_default': serializers.CharField() } field_type_registry.register(ExampleFieldType()) """ _can_order_by = True """Indicates whether it is possible to order by this field type.""" can_be_primary_field = True """Some field types cannot be the primary field.""" can_have_select_options = False """Indicates whether the field can have select options.""" can_be_in_form_view = True """Indicates whether the field is compatible with the form view.""" read_only = False """Indicates whether the field allows inserting/updating row values or if it is read only.""" def prepare_value_for_db(self, instance, value): """ When a row is created or updated all the values are going to be prepared for the database. The value for this field type will run through this method and the returned value will be used. It is also possible to raise validation errors if the value is incorrect. :param instance: The field instance. :type instance: Field :param value: The value that needs to be inserted or updated. :type value: str :return: The modified value that is going to be saved in the database. :rtype: str """ return value def enhance_queryset(self, queryset, field, name): """ This hook can be used to enhance a queryset when fetching multiple rows of a table. This is for example used by the grid view endpoint. Many rows can be requested there and if the table has a `link_row` field it can become slow because the .all() method of the ManyToMany field is called for every row. In case of the `link_row` field we could enhance the queryset by using the `prefetch_related` function in order to prevent many queries. Note that the enhance_queryset will be called for each field in the table. So this hook should only optimise the queryset for the provided field. :param queryset: The queryset that can be enhanced. :type: QuerySet :param field: The related field's instance. The queryset can optionally be enhanced based on the properties of the field. :type field: Field :param name: The name of the field. :type name: str :return: The enhanced queryset. :rtype: QuerySet """ return queryset def empty_query( self, field_name: str, model_field: django_models.Field, field: Field, ): """ Returns a Q filter which performs an empty filter over the provided field for this specific type of field. :param field_name: The name of the field. :type field_name: str :param model_field: The field's actual django field model instance. :type model_field: django_models.Field :param field: The related field's instance. :type field: Field :return: A Q filter. :rtype: Q """ fs = [ManyToManyField, ForeignKey, DurationField, ArrayField] # If the model_field is a ManyToMany field we only have to check if it is None. if any(isinstance(model_field, f) for f in fs): return Q(**{f"{field_name}": None}) if isinstance(model_field, BooleanField): return Q(**{f"{field_name}": False}) q = Q(**{f"{field_name}__isnull": True}) q = q | Q(**{f"{field_name}": None}) if isinstance(model_field, JSONField): q = q | Q(**{f"{field_name}": []}) | Q(**{f"{field_name}": {}}) # If the model field accepts an empty string as value we are going to add # that to the or statement. try: model_field.get_prep_value("") q = q | Q(**{f"{field_name}": ""}) return q except Exception: return q def contains_query(self, field_name, value, model_field, field): """ Returns a Q or AnnotatedQ filter which performs a contains filter over the provided field for this specific type of field. :param field_name: The name of the field. :type field_name: str :param value: The value to check if this field contains or not. :type value: str :param model_field: The field's actual django field model instance. :type model_field: models.Field :param field: The related field's instance. :type field: Field :return: A Q or AnnotatedQ filter. given value. :rtype: OptionallyAnnotatedQ """ return Q() def get_serializer_field(self, instance, **kwargs): """ Should return the serializer field based on the custom model instance attributes. It is common that the field is not required so that a user doesn't have to update the field each time another field in the same row changes. :param instance: The field instance for which to get the model field for. :type instance: Field :param kwargs: The kwargs that will be passed to the field. :type kwargs: dict :return: The serializer field that represents the field instance attributes. :rtype: serializer.Field """ raise NotImplementedError("Each must have his own get_serializer_field method.") def get_response_serializer_field(self, instance, **kwargs): """ The response serializer field can be overridden if the field's value should be represented in a different way when the value is included in a response. This will for example happen with a user lists all the rows in the grid view, but also in the response after creating a row. By default the serializer that also handles the validation and input is returned here. :param instance: The field instance for which to get the model field for. :type instance: Field :param kwargs: The kwargs that will be passed to the field. :type kwargs: dict :return: The serializer field that represents the field instance attributes. :rtype: serializer.Field """ return self.get_serializer_field(instance, **kwargs) def get_serializer_help_text(self, instance): """ If some additional information in the documentation related to the field's type is required then that can be returned here. It will be added to the `create_database_table_row` part. :param instance: :type: Struct :return: The additional field documentation. :rtype: str """ return "" def get_model_field(self, instance, **kwargs): """ Should return the model field based on the custom model instance attributes. It is common that the field can be blank because people are going to create a row without any data in it. :param instance: The field instance for which to get the model field for. :type instance: Field :param kwargs: The kwargs that will be passed to the field. :type kwargs: dict :return: The model field that represents the field instance attributes. :rtype: model.Field """ raise NotImplementedError("Each must have his own get_model_field method.") def after_model_generation(self, instance, model, field_name, manytomany_models): """ After the model is generated the after_model_generation method of each field is also called to make some additional changes when whole model is available. This is for example used by the LinkRow field so that the ManyToMany field can be added later. :param instance: The field instance object. :type instance: Field :param model: The generated model containing all fields. :type model: Model :param field_name: The given name of the field in the model. :type field_name: str :param manytomany_models: A dict containing cached related manytomany models in order to prevent model generation loop. :type manytomany_models: dict """ def random_value(self, instance, fake, cache): """ Should return a random value that can be used as value for the field. This is used by the fill_table management command which will add an N amount of rows to the table with random data. :param instance: The field instance for which to get the random value for. :type instance: Field :param fake: An instance of the Faker package. :type fake: Faker :param cache: A small in memory cache dict that can be used to store data that is needed for to generate a random value. :type dict: dict :return: The randomly generated value. :rtype: any """ return None def get_alter_column_prepare_old_value(self, connection, from_field, to_field): """ Can return an SQL statement to convert the `p_in` variable to a readable text format for the new field. This SQL will not be run when converting between two fields of the same baserow type which share the same underlying database column type. If you require this then implement force_same_type_alter_column. Example: return "p_in = lower(p_in);" :param connection: The used connection. This can for example be used to check the database engine type. :type connection: DatabaseWrapper :param from_field: The old field instance. :type to_field: Field :param to_field: The new field instance. :type to_field: Field :return: The SQL statement converting the value to text for the next field. The can for example be used to convert a select option to plain text. :rtype: None or str """ return None def get_alter_column_prepare_new_value(self, connection, from_field, to_field): """ Can return a SQL statement to convert the `p_in` variable from text to a desired format for the new field. This SQL will not be run when converting between two fields of the same baserow type which share the same underlying database column type. If you require this then implement force_same_type_alter_column. Example: when a string is converted to a number, to statement could be: `REGEXP_REPLACE(p_in, '[^0-9]', '', 'g')` which would remove all non numeric characters. The p_in variable is the old value as a string. :param connection: The used connection. This can for example be used to check the database engine type. :type connection: DatabaseWrapper :param from_field: The old field instance. :type to_field: Field :param to_field: The new field instance. :type to_field: Field :return: The SQL statement converting the old text value into the correct format. :rtype: None or str """ return None def prepare_values(self, values, user): """ The prepare_values hook gives the possibility to change the provided values that just before they are going to be used to create or update the instance. For example if an ID is provided, it can be converted to a model instance. Or to convert a certain date string to a date object. :param values: The provided values. :type values: dict :param user: The user on whose behalf the change is made. :type user: User :return: The updates values. :type: dict """ return values def before_create(self, table, primary, values, order, user): """ This cook is called just before the fields instance is created. Here some additional checks can be done based on the provided values. :param table: The table where the field is going to be added to. :type table: Table :param primary: Indicates whether the field is going to be a primary field. :type primary: bool :param values: The new values that are going to be passed when creating the field instance. :type values: dict :param order: The order that the field is going to get in the database. :type order: int :param user: The user on whose behalf the change is made. :type user: User """ def after_create(self, field, model, user, connection, before): """ This hook is called right after the has been created. The schema change has also been done so the provided model could optionally be used. :param field: The created field instance. :type field: Field :param model: The Django model that contains the newly created field. :type model: Model :param user: The user on whose behalf the change is made. :type user: User :param connection: The connection used to make the database schema change. :type connection: DatabaseWrapper :param before: The value returned by the before_created method. :type before: any """ def before_update(self, from_field, to_field_values, user): """ This hook is called just before updating the field instance. It is called on the to (new) field type if it changes. Here some additional checks can be done based on the provided values. :param from_field: The old field instance. :type from_field: Field :param to_field_values: The values that are going to be updated. :type to_field_values: dict :param user: The user on whose behalf the change is made. :type user: User """ def before_schema_change( self, from_field, to_field, from_model, to_model, from_model_field, to_model_field, user, ): """ This hook is called just before the database's schema change. In some cases some additional cleanup or creation of related instances has to happen if the field type changes. That can happen here. :param from_field: The old field instance. It is not recommended to call the save function as this will undo part of the changes that have been made. This is just for comparing values. :type from_field: Field :param to_field: The updated field instance. :type: to_field: Field :param from_model: The old generated model containing only the old field. :type from_model: Model :param to_model: The generated model containing only the new field. :type to_model: Model :param from_model_field: The old field extracted from the old model. :type from_model_field: models.Field :param to_model_field: The new field extracted from the new model. :type to_model_field: models.Field :param user: The user on whose behalf the change is made. :type user: User """ def after_update( self, from_field, to_field, from_model, to_model, user, connection, altered_column, before, ): """ This hook is called right after a field has been updated. In some cases data mutation still has to be done in order to maintain data integrity. For example when the only the allowing of negative values has been changed for the number field. :param from_field: The old field instance. It is not recommended to call the save function as this will undo part of the changes that have been made. This is just for comparing values. :type from_field: Field :param to_field: The updated field instance. :type: to_field: Field :param from_model: The old generated model containing only the old field. :type from_model: Model :param to_model: The generated model containing only the new field. :type to_model: Model :param user: The user on whose behalf the change is made. :type user: User :param connection: The connection used to make the database schema change. :type connection: DatabaseWrapper :param altered_column: Indicates whether the column has been altered in the table. Sometimes data has to be updated if the column hasn't been altered. :type altered_column: bool :param before: The value returned by the before_update method. :type before: any """ def after_delete(self, field, model, connection): """ This hook is called right after the field has been deleted and the schema change has been done. :param field: The deleted field instance. :type field: Field :param model: The Django model that contains the deleted field. :type model: Model :param connection: The connection used to make the database schema change. :type connection: DatabaseWrapper """ def get_order(self, field, field_name, order_direction): """ This hook can be called to generate a different order by expression. By default None is returned which means the normal field sorting will be applied. Optionally a different expression can be generated. This is for example used by the single select field generates a mapping achieve the correct sorting based on the select option value. Additionally an annotation can be returned which will get applied to the queryset. :param field: The related field object instance. :type field: Field :param field_name: The name of the field. :type field_name: str :param order_direction: The sort order direction. :type order_direction: str (Either "ASC" or "DESC") :return: Either the expression that is added directly to the model.objects.order(), an AnnotatedOrderBy class or None. :rtype: Optional[Expression, AnnotatedOrderBy, None] """ return None def force_same_type_alter_column(self, from_field, to_field): """ Defines whether the sql provided by the get_alter_column_prepare_{old,new}_value hooks should be forced to run when converting between two fields of this field type which have the same database column type. You only need to implement this when when you have validation and/or data manipulation running as part of your alter_column_prepare SQL which must be run even when from_field and to_field are the same Baserow field type and sql column type. If your field has the same baserow type but will convert into different sql column types then the alter sql will be run automatically and you do not need to use this override. :param from_field: The old field instance. It is not recommended to call the save function as this will undo part of the changes that have been made. This is just for comparing values. :type from_field: Field :param to_field: The updated field instance. :type: to_field: Field :return: Whether the alter column sql should be forced to run. :rtype: bool """ return False def export_serialized(self, field, include_allowed_fields=True): """ Exports the field to a serialized dict that can be imported by the `import_serialized` method. This dict is also JSON serializable. :param field: The field instance that must be exported. :type field: Field :param include_allowed_fields: Indicates whether or not the allowed fields should automatically be added to the serialized object. :type include_allowed_fields: bool :return: The exported field in as serialized dict. :rtype: dict """ serialized = { "id": field.id, "type": self.type, "name": field.name, "order": field.order, "primary": field.primary, } if include_allowed_fields: for field_name in self.allowed_fields: serialized[field_name] = getattr(field, field_name) if self.can_have_select_options: serialized["select_options"] = [ { "id": select_option.id, "value": select_option.value, "color": select_option.color, "order": select_option.order, } for select_option in field.select_options.all() ] return serialized def import_serialized(self, table, serialized_values, id_mapping): """ Imported an exported serialized field dict that was exported via the `export_serialized` method. :param table: The table where the field should be added to. :type table: Table :param serialized_values: The exported serialized field values that need to be imported. :type serialized_values: dict :param id_mapping: The map of exported ids to newly created ids that must be updated when a new instance has been created. :type id_mapping: dict :return: The newly created field instance. :rtype: Field """ if "database_fields" not in id_mapping: id_mapping["database_fields"] = {} id_mapping["database_field_select_options"] = {} serialized_copy = serialized_values.copy() field_id = serialized_copy.pop("id") serialized_copy.pop("type") select_options = ( serialized_copy.pop("select_options") if self.can_have_select_options else [] ) field = self.model_class(table=table, **serialized_copy) field.save() id_mapping["database_fields"][field_id] = field.id if self.can_have_select_options: for select_option in select_options: select_option_copy = select_option.copy() select_option_id = select_option_copy.pop("id") select_option_object = SelectOption.objects.create( field=field, **select_option_copy ) id_mapping["database_field_select_options"][ select_option_id ] = select_option_object.id return field def after_import_serialized(self, field, field_cache): """ Called on fields in dependency order after all fields for an application have been created for any final tasks that require the field graph to be present. :param field: A field instance of this field type. :param field_cache: A cache should be used to lookup fields. """ from baserow.contrib.database.fields.dependencies.handler import ( FieldDependencyHandler, ) FieldDependencyHandler.rebuild_dependencies(field, field_cache) for ( dependant_field, dependant_field_type, _, ) in field.dependant_fields_with_types(field_cache): dependant_field_type.after_import_serialized(dependant_field, field_cache) def after_rows_imported(self, field, via_path_to_starting_table, update_collector): """ Called on fields in dependency order after all of its rows have been inserted after an import for any row updates required once all rows in all imported tables exist. :param field: A field instance of this field type. :param via_path_to_starting_table: A list of link row fields if any leading back to the starting table where the first rows were imported. :param update_collector: Any row update statements should be registered into this collector. """ for ( dependant_field, dependant_field_type, dependency_path, ) in field.dependant_fields_with_types( update_collector, via_path_to_starting_table ): dependant_field_type.after_rows_imported( dependant_field, dependency_path, update_collector ) def get_export_serialized_value(self, row, field_name, cache, files_zip, storage): """ Exports the value to a the value of a row to serialized value that is also JSON serializable. :param row: The row instance that the value must be exported from. :type row: Object :param field_name: The name of the field that must be exported. :type field_name: str :param cache: An in memory dictionary that is shared between all fields while exporting the table. This is for example used by the link row field type to prefetch all relations. :type cache: dict :param files_zip: A zip file buffer where the files related to the template must be copied into. :type files_zip: ZipFile :param storage: The storage where the files can be loaded from. :type storage: Storage or None :return: The exported value. :rtype: Object """ return getattr(row, field_name) def set_import_serialized_value( self, row, field_name, value, id_mapping, files_zip, storage ): """ Sets an imported and serialized value on a row instance. :param row: The row instance where the value be set on. :type row: Object :param field_name: The name of the field that must be set. :type field_name: str :param value: The value that must be set. :type value: Object :param files_zip: A zip file buffer where files related to the template can be extracted from. :type files_zip: ZipFile :param storage: The storage where the files can be copied to. :type storage: Storage or None :param id_mapping: The map of exported ids to newly created ids that must be updated when a new instance has been created. :type id_mapping: dict """ setattr(row, field_name, value) def get_export_value(self, value, field_object): """ Should convert this field type's internal baserow value to a form suitable for exporting to a standalone file. :param value: The internal value to convert to a suitable export format :type value: Object :param field_object: The field object for the field to extract :type field_object: FieldObject :return: A value suitable to be serialized and stored in a file format for users. """ return value def get_human_readable_value(self, value: Any, field_object) -> str: """ Should convert the value of the provided field to a human readable string for display purposes. :param value: The value of the field extracted from a row to convert to human readable form. :param field_object: The field object for the field to extract :type field_object: FieldObject :return A human readable string. """ human_readable_value = self.get_export_value(value, field_object) if human_readable_value is None: return "" else: return str(human_readable_value) # noinspection PyMethodMayBeStatic def get_other_fields_to_trash_restore_always_together(self, field) -> List[Any]: """ When a field of this type is trashed/restored, or the table it is in trashed/restored, this method should return any other trashable fields that must always be trashed or restored in tandem with this field. For example, a link field has an opposing link field in the other table that should also be trashed when it is trashed. And so for link fields this method is overridden to return the related field so it is trashed/restored correctly. :param field: The specific instance of the field that is being trashed or whose table is being trashed. :return: A list of related fields that should be trashed or restored in tandem with this field or it's table. """ return [] def to_baserow_formula_type(self, field): """ Should return the Baserow Formula Type to use when referencing a field of this type in a formula. :param field: The specific instance of the field that a formula type should be created for. :return: The Baserow Formula Type that represents this field in a formula. """ from baserow.contrib.database.formula import BaserowFormulaInvalidType return BaserowFormulaInvalidType( f"A field of type {self.type} cannot be referenced in a Baserow formula." ) def from_baserow_formula_type(self, formula_type) -> Field: """ Should return the Baserow Field Type when converting a formula type back to a field type. :param formula_type: The specific instance of a formula type that a field type model should be created for. :return: A Baserow Field Type model instance that represents this formula type. """ raise NotImplementedError( f"A field of type {self.type} cannot be referenced in a Baserow formula." ) def to_baserow_formula_expression(self, field): """ Should return a Typed Baserow Formula Expression to use when referencing the field in a formula. :param field: The specific instance of the field that a typed formula expression should be created for. :return: A typed baserow formula expression which when evaluated represents a reference to field. """ from baserow.contrib.database.formula import FormulaHandler return FormulaHandler.get_normal_field_reference_expression( field, self.to_baserow_formula_type(field) ) def get_field_dependencies( self, field_instance, field_lookup_cache ) -> OptionalFieldDependencies: """ Should return a list of field dependencies that field_instance has. A field dependency can either be the name of a field in the same table as field_instance, or a tuple where the first value is the name of a link row field in the same table and the second is the name of a field in the linked table. If instead None is returned this field_type will be treated as if it cannot have dependencies on other fields. :param field_instance: The field_instance to get field dependencies for. :type field_instance: Field :param field_lookup_cache: A cache that can be used to lookup fields. :type field_lookup_cache: FieldCache """ return None def restore_failed(self, field_instance, restore_exception): """ Called when restoring field_instance has caused an exception. Return True if the exception should be swallowed and the restore operation should succeed or False if it should fail and rollback. :param field_instance: The instance of the field which caused restore_exception on field restore. :type field_instance: Field :param restore_exception: The exception that was raised when restoring the field. :type restore_exception: :return: True to swallow the exception and succeed the restore, false to re-raise and fail the restore. :rtype: bool """ return False def row_of_dependency_created( self, field, starting_row, update_collector, via_path_to_starting_table, ): """ Called when a row is created in a dependency field (a field that the field instance parameter depends on). If as a result row value changes are required by this field type an update expression should be provided to the update_collector. Ensure super is called if this fields rows also change so dependants of this field also get notified. :param field: The field whose dependency has had a row created. :param starting_row: The row which was created in the dependency field. :param update_collector: Any update statements should be passed to this collector so they are run correctly at the right time. You should not be manually updating row values yourself in this method. :param via_path_to_starting_table: A list of link row fields if any leading back to the starting table where the row was created. """ self.row_of_dependency_updated( field, starting_row, update_collector, via_path_to_starting_table, ) def row_of_dependency_updated( self, field, starting_row, update_collector, via_path_to_starting_table, ): """ Called when a row or rows are updated in a dependency field (a field that the field instance parameter depends on). If as a result row value changes are required by this field type an update expression should be provided to the update_collector. Ensure super is called if this fields rows also change so dependants of this field also get notified. :param field: The field whose dependency has had a row or rows updated. :param starting_row: The very first row which changed triggering this eventual update notification, might not be in the same table as field or a direct dependency row of field. :param update_collector: Any update statements should be passed to this collector so they are run correctly at the right time. You should not be manually updating row values yourself in this method. :param via_path_to_starting_table: A list of link row fields if any leading back to the starting table where the first row was changed. """ for ( dependant_field, dependant_field_type, dependant_path_to_starting_table, ) in field.dependant_fields_with_types( update_collector, via_path_to_starting_table ): dependant_field_type.row_of_dependency_updated( dependant_field, starting_row, update_collector, dependant_path_to_starting_table, ) def row_of_dependency_deleted( self, field, starting_row, update_collector, via_path_to_starting_table, ): """ Called when a row is deleted in a dependency field (a field that the field instance parameter depends on). If as a result row value changes are required by this field type an update expression should be provided to the update_collector. Ensure super is called if this fields rows also change so dependants of this field also get notified. :param field: The field whose dependency has had a row deleted. :param starting_row: The very row which was deleted. :param update_collector: Any update statements should be passed to this collector so they are run correctly at the right time. You should not be manually updating row values yourself in this method. :param via_path_to_starting_table: A list of link row fields if any leading back to the starting table where the row was deleted. """ self.row_of_dependency_updated( field, starting_row, update_collector, via_path_to_starting_table, ) def row_of_dependency_moved( self, field, starting_row, update_collector, via_path_to_starting_table, ): """ Called when a row is moved in a dependency field (a field that the field instance parameter depends on). If as a result row value changes are required by this field type an update expression should be provided to the update_collector. Ensure super is called if this fields rows also change so dependants of this field also get notified. :param field: The field whose dependency has had a row deleted. :param starting_row: The row which was moved. :param update_collector: Any update statements should be passed to this collector so they are run correctly at the right time. You should not be manually updating row values yourself in this method. :param via_path_to_starting_table: A list of link row fields if any leading back to the starting table where the row was moved. """ self.row_of_dependency_updated( field, starting_row, update_collector, via_path_to_starting_table, ) def field_dependency_created( self, field, created_field, via_path_to_starting_table, update_collector ): """ Called when a field is created which the field parameter depends on. If as a result row value changes are required by this field type an update expression should be provided to the update_collector. Ensure super is called if this field also changes so dependants of this field also get notified. :param field: The field who has had a new dependency field created. :param created_field: The dependency field which was created. :param update_collector: If this field changes the resulting field should be passed to the update_collector. Additionally if this fields row values should also change has a result an update statement should be passed to this collector which will be run correctly at the right time. You should not be manually updating row values yourself in this method. :param via_path_to_starting_table: A list of link row fields if any leading back to the starting table where field was created. """ self.field_dependency_updated( field, field, field, via_path_to_starting_table, update_collector ) def field_dependency_updated( self, field, updated_field, updated_old_field, via_path_to_starting_table, update_collector, ): """ Called when a field is updated which the field parameter depends on. If as a result row value changes are required by this field type an update expression should be provided to the update_collector. Ensure super is called if this field also changes so dependants of this field also get notified. :param field: The field who has had a new dependency field created. :param updated_field: The dependency field which was updated. :param updated_old_field: The instance of the updated field before the update. :param update_collector: If this field changes the resulting field should be passed to the update_collector. Additionally if this fields row values should also change has a result an update statement should be passed to this collector which will be run correctly at the right time. You should not be manually updating row values yourself in this method. :param via_path_to_starting_table: A list of link row fields if any leading back to the starting table the first field change occurred. """ from baserow.contrib.database.fields.dependencies.handler import ( FieldDependencyHandler, ) FieldDependencyHandler.rebuild_dependencies(field, update_collector) for ( dependant_field, dependant_field_type, dependant_path_to_starting_table, ) in field.dependant_fields_with_types( update_collector, via_path_to_starting_table ): dependant_field_type.field_dependency_updated( dependant_field, field, field, dependant_path_to_starting_table, update_collector, ) def field_dependency_deleted( self, field, deleted_field, via_path_to_starting_table, update_collector ): """ Called when a field is deleted which the field parameter depends on. If as a result row value changes are required by this field type an update expression should be provided to the update_collector. Ensure super is called if this field also changes so dependants of this field also get notified. :param field: The field who has had a new dependency field created. :param deleted_field: The dependency field which was deleted. :param update_collector: If this field changes the resulting field should be passed to the update_collector. Additionally if this fields row values should also change has a result an update statement should be passed to this collector which will be run correctly at the right time. You should not be manually updating row values yourself in this method. :param via_path_to_starting_table: A list of link row fields if any leading back to the starting table the field was deleted. """ self.field_dependency_updated( field, field, field, via_path_to_starting_table, update_collector ) def check_can_order_by(self, field): """ Override this method if this field type can sometimes be ordered or sometimes cannot be ordered depending on the individual field state. By default will just return the bool property _can_order_by so if your field type doesn't depend on the field state and is always just True or False just set _can_order_by to the desired value. :param field: The field to check to see if it can be ordered by or not. :return: True if a view can be ordered by this field, False otherwise. """ return self._can_order_by def before_field_options_update( self, field: Field, to_create: List[int] = None, to_update: List[dict] = None, to_delete: List[int] = None, ): """ Called from `FieldHandler.update_field_select_options()` just before the select options of a field are updated in database. :param field: The field instance whose options are updated. :param to_create: A list of dict containing data for each new option added to the field. :param to_update: A list of option ids that already exists and are going to be associated with this field. :param to_delete: A list of option ids that are removed from the field option list. """ # noinspection PyMethodMayBeStatic def before_table_model_invalidated( self, field: Field, ): """ Called before the table the field is in is invalidated in the model cache. Usually this method should be overridden to also invalidate the cache of other tables models which would be affected by this tables cache being invalidated. """ class FieldTypeRegistry( APIUrlsRegistryMixin, CustomFieldsRegistryMixin, ModelRegistryMixin, Registry ): """ With the field type registry it is possible to register new field types. A field type is an abstraction made specifically for Baserow. If added to the registry a user can create new fields based on this type. """ name = "field" does_not_exist_exception_class = FieldTypeDoesNotExist already_registered_exception_class = FieldTypeAlreadyRegistered class FieldConverter(Instance): """ By default when changing a field the lenient schema editor is used to alter the field to make the schema changes. If for whatever reason this does not suffice then a converter can be used to change field and the related data. This is for example used by the link_row field because it is not possible to change a ManyToManyField to another field. Example: from baserow.contrib.database.fields.field_types import ( TextFieldType, DateFieldType ) from baserow.contrib.database.fields.registries import ( FieldConverter, field_converter_registry ) class TextToDateFieldConverter(FieldConverter): type = 'text-to-date' def is_applicable(self, from_model, from_field, to_field): return ( isinstance(from_field, TextFieldType) and isinstance(to_field, DateFieldType) ) def alter_field(self, from_field, to_field, from_model, to_model, from_model_field, to_model_field, user, connection): # This is just for example purposes, but it will delete the old text # field field and create a new date field. You can be very creative # here in how you want to convert field and the data. It is for example # possible to load all the old data in memory, convert it and then # update the new data. Performance should always be kept in mind # though. with safe_django_schema_editor() as schema_editor: schema_editor.remove_field(from_model, from_model_field) schema_editor.add_field(to_model, to_model_field) field_converter_registry.register(TextToDateFieldConverter()) """ def is_applicable(self, from_model, from_field, to_field): """ Decides whether the converter is applicable for the alteration of the provided fields. Before conversion all converters are checked to see if they are applicable. The first one that is will be used. :param from_model: The old model containing only the old field. :type from_model: Model :param from_field: The old field instance. It should only be used for type and property comparison with the the to_field because else things might break. :type from_field: Field :param to_field: The new field instance. It should only be used for type and property comparison with the the from_field because else things might break. :type to_field: Field :return: If True then the alter_field method of this converter will be used to alter the field instead of the lenient schema editor. :rtype: bool """ raise NotImplementedError( "Each field converter must have an is_applicable " "method." ) def alter_field( self, from_field, to_field, from_model, to_model, from_model_field, to_model_field, user, connection, ): """ Should perform the schema change and changes related to the field change. It must bring the field's schema into the desired state. :param from_field: The old field's instance. This should be used for getting the type and properties. Making changes can override things. :type from_field: Field :param to_field: The new field's instance. This should be used for getting the type and properties. It already is in a correct state. :type to_field: Field :param from_model: The old generated model containing only the old field. :type from_model: Model :param to_model: The generated model containing only the new field. :type to_model: Model :param from_model_field: The old field extracted from the old model. :type from_model_field: models.Field :param to_model_field: The new field extracted from the new model. :type to_model_field: models.Field :param user: The user on whose behalf the change is made. :type user: User :param connection: The connection used to make the database schema change. :type connection: DatabaseWrapper """ raise NotImplementedError( "Each field converter must have an alter_field " "method." ) class FieldConverterRegistry(Registry): """ The registry that holds all the available field converters. A field converter can be used to convert a field to another type in a custom way. It can also be used the data related to the field needs a specific conversion. It should be used when the default lenient schema editor does not work. """ name = "field_converter" def find_applicable_converter(self, *args, **kwargs): """ Finds the first applicable converter that is in the register based on the provided arguments. Note that is might be possible for other converters to be applicable also. This only returns the first match, not the best match. Might be an idea to implement something with a priority system once we have lots of converters. :return: The applicable field converter or None if no converter has been found. :rtype: None or FieldConverter """ for converter in self.registry.values(): if converter.is_applicable(*args, **kwargs): return converter return None # A default field type registry is created here, this is the one that is used # throughout the whole Baserow application to add a new field type. field_type_registry = FieldTypeRegistry() field_converter_registry = FieldConverterRegistry()
from typing import Any, List from django.contrib.postgres.fields import JSONField, ArrayField from django.db import models as django_models from django.db.models import ( Q, BooleanField, DurationField, ) from django.db.models.fields.related import ManyToManyField, ForeignKey from baserow.core.registry import ( Instance, Registry, ModelInstanceMixin, ModelRegistryMixin, CustomFieldsInstanceMixin, CustomFieldsRegistryMixin, MapAPIExceptionsInstanceMixin, APIUrlsRegistryMixin, APIUrlsInstanceMixin, ImportExportMixin, ) from .dependencies.types import OptionalFieldDependencies from .exceptions import FieldTypeAlreadyRegistered, FieldTypeDoesNotExist from .models import SelectOption, Field class FieldType( MapAPIExceptionsInstanceMixin, APIUrlsInstanceMixin, CustomFieldsInstanceMixin, ModelInstanceMixin, ImportExportMixin, Instance, ): """ This abstract class represents a custom field type that can be added to the field type registry. It must be extended so customisation can be done. Each field type will have his own model that must extend the Field model, this is needed so that the user can set custom settings per field instance he has created. Example: from baserow.contrib.database.fields.models import Field from baserow.contrib.database.fields.registry import ( FieldType, field_type_registry ) class ExampleFieldModel(FieldType): pass class ExampleFieldType(FieldType): type = 'a-unique-field-type-name' model_class = ExampleFieldModel allowed_fields = ['text_default'] serializer_field_names = ['text_default'] serializer_field_overrides = { 'text_default': serializers.CharField() } field_type_registry.register(ExampleFieldType()) """ _can_order_by = True """Indicates whether it is possible to order by this field type.""" can_be_primary_field = True """Some field types cannot be the primary field.""" can_have_select_options = False """Indicates whether the field can have select options.""" can_be_in_form_view = True """Indicates whether the field is compatible with the form view.""" read_only = False """Indicates whether the field allows inserting/updating row values or if it is read only.""" def prepare_value_for_db(self, instance, value): """ When a row is created or updated all the values are going to be prepared for the database. The value for this field type will run through this method and the returned value will be used. It is also possible to raise validation errors if the value is incorrect. :param instance: The field instance. :type instance: Field :param value: The value that needs to be inserted or updated. :type value: str :return: The modified value that is going to be saved in the database. :rtype: str """ return value def enhance_queryset(self, queryset, field, name): """ This hook can be used to enhance a queryset when fetching multiple rows of a table. This is for example used by the grid view endpoint. Many rows can be requested there and if the table has a `link_row` field it can become slow because the .all() method of the ManyToMany field is called for every row. In case of the `link_row` field we could enhance the queryset by using the `prefetch_related` function in order to prevent many queries. Note that the enhance_queryset will be called for each field in the table. So this hook should only optimise the queryset for the provided field. :param queryset: The queryset that can be enhanced. :type: QuerySet :param field: The related field's instance. The queryset can optionally be enhanced based on the properties of the field. :type field: Field :param name: The name of the field. :type name: str :return: The enhanced queryset. :rtype: QuerySet """ return queryset def empty_query( self, field_name: str, model_field: django_models.Field, field: Field, ): """ Returns a Q filter which performs an empty filter over the provided field for this specific type of field. :param field_name: The name of the field. :type field_name: str :param model_field: The field's actual django field model instance. :type model_field: django_models.Field :param field: The related field's instance. :type field: Field :return: A Q filter. :rtype: Q """ fs = [ManyToManyField, ForeignKey, DurationField, ArrayField] # If the model_field is a ManyToMany field we only have to check if it is None. if any(isinstance(model_field, f) for f in fs): return Q(**{f"{field_name}": None}) if isinstance(model_field, BooleanField): return Q(**{f"{field_name}": False}) q = Q(**{f"{field_name}__isnull": True}) q = q | Q(**{f"{field_name}": None}) if isinstance(model_field, JSONField): q = q | Q(**{f"{field_name}": []}) | Q(**{f"{field_name}": {}}) # If the model field accepts an empty string as value we are going to add # that to the or statement. try: model_field.get_prep_value("") q = q | Q(**{f"{field_name}": ""}) return q except Exception: return q def contains_query(self, field_name, value, model_field, field): """ Returns a Q or AnnotatedQ filter which performs a contains filter over the provided field for this specific type of field. :param field_name: The name of the field. :type field_name: str :param value: The value to check if this field contains or not. :type value: str :param model_field: The field's actual django field model instance. :type model_field: models.Field :param field: The related field's instance. :type field: Field :return: A Q or AnnotatedQ filter. given value. :rtype: OptionallyAnnotatedQ """ return Q() def get_serializer_field(self, instance, **kwargs): """ Should return the serializer field based on the custom model instance attributes. It is common that the field is not required so that a user doesn't have to update the field each time another field in the same row changes. :param instance: The field instance for which to get the model field for. :type instance: Field :param kwargs: The kwargs that will be passed to the field. :type kwargs: dict :return: The serializer field that represents the field instance attributes. :rtype: serializer.Field """ raise NotImplementedError("Each must have his own get_serializer_field method.") def get_response_serializer_field(self, instance, **kwargs): """ The response serializer field can be overridden if the field's value should be represented in a different way when the value is included in a response. This will for example happen with a user lists all the rows in the grid view, but also in the response after creating a row. By default the serializer that also handles the validation and input is returned here. :param instance: The field instance for which to get the model field for. :type instance: Field :param kwargs: The kwargs that will be passed to the field. :type kwargs: dict :return: The serializer field that represents the field instance attributes. :rtype: serializer.Field """ return self.get_serializer_field(instance, **kwargs) def get_serializer_help_text(self, instance): """ If some additional information in the documentation related to the field's type is required then that can be returned here. It will be added to the `create_database_table_row` part. :param instance: :type: Struct :return: The additional field documentation. :rtype: str """ return "" def get_model_field(self, instance, **kwargs): """ Should return the model field based on the custom model instance attributes. It is common that the field can be blank because people are going to create a row without any data in it. :param instance: The field instance for which to get the model field for. :type instance: Field :param kwargs: The kwargs that will be passed to the field. :type kwargs: dict :return: The model field that represents the field instance attributes. :rtype: model.Field """ raise NotImplementedError("Each must have his own get_model_field method.") def after_model_generation(self, instance, model, field_name, manytomany_models): """ After the model is generated the after_model_generation method of each field is also called to make some additional changes when whole model is available. This is for example used by the LinkRow field so that the ManyToMany field can be added later. :param instance: The field instance object. :type instance: Field :param model: The generated model containing all fields. :type model: Model :param field_name: The given name of the field in the model. :type field_name: str :param manytomany_models: A dict containing cached related manytomany models in order to prevent model generation loop. :type manytomany_models: dict """ def random_value(self, instance, fake, cache): """ Should return a random value that can be used as value for the field. This is used by the fill_table management command which will add an N amount of rows to the table with random data. :param instance: The field instance for which to get the random value for. :type instance: Field :param fake: An instance of the Faker package. :type fake: Faker :param cache: A small in memory cache dict that can be used to store data that is needed for to generate a random value. :type dict: dict :return: The randomly generated value. :rtype: any """ return None def get_alter_column_prepare_old_value(self, connection, from_field, to_field): """ Can return an SQL statement to convert the `p_in` variable to a readable text format for the new field. This SQL will not be run when converting between two fields of the same baserow type which share the same underlying database column type. If you require this then implement force_same_type_alter_column. Example: return "p_in = lower(p_in);" :param connection: The used connection. This can for example be used to check the database engine type. :type connection: DatabaseWrapper :param from_field: The old field instance. :type to_field: Field :param to_field: The new field instance. :type to_field: Field :return: The SQL statement converting the value to text for the next field. The can for example be used to convert a select option to plain text. :rtype: None or str """ return None def get_alter_column_prepare_new_value(self, connection, from_field, to_field): """ Can return a SQL statement to convert the `p_in` variable from text to a desired format for the new field. This SQL will not be run when converting between two fields of the same baserow type which share the same underlying database column type. If you require this then implement force_same_type_alter_column. Example: when a string is converted to a number, to statement could be: `REGEXP_REPLACE(p_in, '[^0-9]', '', 'g')` which would remove all non numeric characters. The p_in variable is the old value as a string. :param connection: The used connection. This can for example be used to check the database engine type. :type connection: DatabaseWrapper :param from_field: The old field instance. :type to_field: Field :param to_field: The new field instance. :type to_field: Field :return: The SQL statement converting the old text value into the correct format. :rtype: None or str """ return None def prepare_values(self, values, user): """ The prepare_values hook gives the possibility to change the provided values that just before they are going to be used to create or update the instance. For example if an ID is provided, it can be converted to a model instance. Or to convert a certain date string to a date object. :param values: The provided values. :type values: dict :param user: The user on whose behalf the change is made. :type user: User :return: The updates values. :type: dict """ return values def before_create(self, table, primary, values, order, user): """ This cook is called just before the fields instance is created. Here some additional checks can be done based on the provided values. :param table: The table where the field is going to be added to. :type table: Table :param primary: Indicates whether the field is going to be a primary field. :type primary: bool :param values: The new values that are going to be passed when creating the field instance. :type values: dict :param order: The order that the field is going to get in the database. :type order: int :param user: The user on whose behalf the change is made. :type user: User """ def after_create(self, field, model, user, connection, before): """ This hook is called right after the has been created. The schema change has also been done so the provided model could optionally be used. :param field: The created field instance. :type field: Field :param model: The Django model that contains the newly created field. :type model: Model :param user: The user on whose behalf the change is made. :type user: User :param connection: The connection used to make the database schema change. :type connection: DatabaseWrapper :param before: The value returned by the before_created method. :type before: any """ def before_update(self, from_field, to_field_values, user): """ This hook is called just before updating the field instance. It is called on the to (new) field type if it changes. Here some additional checks can be done based on the provided values. :param from_field: The old field instance. :type from_field: Field :param to_field_values: The values that are going to be updated. :type to_field_values: dict :param user: The user on whose behalf the change is made. :type user: User """ def before_schema_change( self, from_field, to_field, from_model, to_model, from_model_field, to_model_field, user, ): """ This hook is called just before the database's schema change. In some cases some additional cleanup or creation of related instances has to happen if the field type changes. That can happen here. :param from_field: The old field instance. It is not recommended to call the save function as this will undo part of the changes that have been made. This is just for comparing values. :type from_field: Field :param to_field: The updated field instance. :type: to_field: Field :param from_model: The old generated model containing only the old field. :type from_model: Model :param to_model: The generated model containing only the new field. :type to_model: Model :param from_model_field: The old field extracted from the old model. :type from_model_field: models.Field :param to_model_field: The new field extracted from the new model. :type to_model_field: models.Field :param user: The user on whose behalf the change is made. :type user: User """ def after_update( self, from_field, to_field, from_model, to_model, user, connection, altered_column, before, ): """ This hook is called right after a field has been updated. In some cases data mutation still has to be done in order to maintain data integrity. For example when the only the allowing of negative values has been changed for the number field. :param from_field: The old field instance. It is not recommended to call the save function as this will undo part of the changes that have been made. This is just for comparing values. :type from_field: Field :param to_field: The updated field instance. :type: to_field: Field :param from_model: The old generated model containing only the old field. :type from_model: Model :param to_model: The generated model containing only the new field. :type to_model: Model :param user: The user on whose behalf the change is made. :type user: User :param connection: The connection used to make the database schema change. :type connection: DatabaseWrapper :param altered_column: Indicates whether the column has been altered in the table. Sometimes data has to be updated if the column hasn't been altered. :type altered_column: bool :param before: The value returned by the before_update method. :type before: any """ def after_delete(self, field, model, connection): """ This hook is called right after the field has been deleted and the schema change has been done. :param field: The deleted field instance. :type field: Field :param model: The Django model that contains the deleted field. :type model: Model :param connection: The connection used to make the database schema change. :type connection: DatabaseWrapper """ def get_order(self, field, field_name, order_direction): """ This hook can be called to generate a different order by expression. By default None is returned which means the normal field sorting will be applied. Optionally a different expression can be generated. This is for example used by the single select field generates a mapping achieve the correct sorting based on the select option value. Additionally an annotation can be returned which will get applied to the queryset. :param field: The related field object instance. :type field: Field :param field_name: The name of the field. :type field_name: str :param order_direction: The sort order direction. :type order_direction: str (Either "ASC" or "DESC") :return: Either the expression that is added directly to the model.objects.order(), an AnnotatedOrderBy class or None. :rtype: Optional[Expression, AnnotatedOrderBy, None] """ return None def force_same_type_alter_column(self, from_field, to_field): """ Defines whether the sql provided by the get_alter_column_prepare_{old,new}_value hooks should be forced to run when converting between two fields of this field type which have the same database column type. You only need to implement this when when you have validation and/or data manipulation running as part of your alter_column_prepare SQL which must be run even when from_field and to_field are the same Baserow field type and sql column type. If your field has the same baserow type but will convert into different sql column types then the alter sql will be run automatically and you do not need to use this override. :param from_field: The old field instance. It is not recommended to call the save function as this will undo part of the changes that have been made. This is just for comparing values. :type from_field: Field :param to_field: The updated field instance. :type: to_field: Field :return: Whether the alter column sql should be forced to run. :rtype: bool """ return False def export_serialized(self, field, include_allowed_fields=True): """ Exports the field to a serialized dict that can be imported by the `import_serialized` method. This dict is also JSON serializable. :param field: The field instance that must be exported. :type field: Field :param include_allowed_fields: Indicates whether or not the allowed fields should automatically be added to the serialized object. :type include_allowed_fields: bool :return: The exported field in as serialized dict. :rtype: dict """ serialized = { "id": field.id, "type": self.type, "name": field.name, "order": field.order, "primary": field.primary, } if include_allowed_fields: for field_name in self.allowed_fields: serialized[field_name] = getattr(field, field_name) if self.can_have_select_options: serialized["select_options"] = [ { "id": select_option.id, "value": select_option.value, "color": select_option.color, "order": select_option.order, } for select_option in field.select_options.all() ] return serialized def import_serialized(self, table, serialized_values, id_mapping): """ Imported an exported serialized field dict that was exported via the `export_serialized` method. :param table: The table where the field should be added to. :type table: Table :param serialized_values: The exported serialized field values that need to be imported. :type serialized_values: dict :param id_mapping: The map of exported ids to newly created ids that must be updated when a new instance has been created. :type id_mapping: dict :return: The newly created field instance. :rtype: Field """ if "database_fields" not in id_mapping: id_mapping["database_fields"] = {} id_mapping["database_field_select_options"] = {} serialized_copy = serialized_values.copy() field_id = serialized_copy.pop("id") serialized_copy.pop("type") select_options = ( serialized_copy.pop("select_options") if self.can_have_select_options else [] ) field = self.model_class(table=table, **serialized_copy) field.save() id_mapping["database_fields"][field_id] = field.id if self.can_have_select_options: for select_option in select_options: select_option_copy = select_option.copy() select_option_id = select_option_copy.pop("id") select_option_object = SelectOption.objects.create( field=field, **select_option_copy ) id_mapping["database_field_select_options"][ select_option_id ] = select_option_object.id return field def after_import_serialized(self, field, field_cache): """ Called on fields in dependency order after all fields for an application have been created for any final tasks that require the field graph to be present. :param field: A field instance of this field type. :param field_cache: A cache should be used to lookup fields. """ from baserow.contrib.database.fields.dependencies.handler import ( FieldDependencyHandler, ) FieldDependencyHandler.rebuild_dependencies(field, field_cache) for ( dependant_field, dependant_field_type, _, ) in field.dependant_fields_with_types(field_cache): dependant_field_type.after_import_serialized(dependant_field, field_cache) def after_rows_imported(self, field, via_path_to_starting_table, update_collector): """ Called on fields in dependency order after all of its rows have been inserted after an import for any row updates required once all rows in all imported tables exist. :param field: A field instance of this field type. :param via_path_to_starting_table: A list of link row fields if any leading back to the starting table where the first rows were imported. :param update_collector: Any row update statements should be registered into this collector. """ for ( dependant_field, dependant_field_type, dependency_path, ) in field.dependant_fields_with_types( update_collector, via_path_to_starting_table ): dependant_field_type.after_rows_imported( dependant_field, dependency_path, update_collector ) def get_export_serialized_value(self, row, field_name, cache, files_zip, storage): """ Exports the value to a the value of a row to serialized value that is also JSON serializable. :param row: The row instance that the value must be exported from. :type row: Object :param field_name: The name of the field that must be exported. :type field_name: str :param cache: An in memory dictionary that is shared between all fields while exporting the table. This is for example used by the link row field type to prefetch all relations. :type cache: dict :param files_zip: A zip file buffer where the files related to the template must be copied into. :type files_zip: ZipFile :param storage: The storage where the files can be loaded from. :type storage: Storage or None :return: The exported value. :rtype: Object """ return getattr(row, field_name) def set_import_serialized_value( self, row, field_name, value, id_mapping, files_zip, storage ): """ Sets an imported and serialized value on a row instance. :param row: The row instance where the value be set on. :type row: Object :param field_name: The name of the field that must be set. :type field_name: str :param value: The value that must be set. :type value: Object :param files_zip: A zip file buffer where files related to the template can be extracted from. :type files_zip: ZipFile :param storage: The storage where the files can be copied to. :type storage: Storage or None :param id_mapping: The map of exported ids to newly created ids that must be updated when a new instance has been created. :type id_mapping: dict """ setattr(row, field_name, value) def get_export_value(self, value, field_object): """ Should convert this field type's internal baserow value to a form suitable for exporting to a standalone file. :param value: The internal value to convert to a suitable export format :type value: Object :param field_object: The field object for the field to extract :type field_object: FieldObject :return: A value suitable to be serialized and stored in a file format for users. """ return value def get_human_readable_value(self, value: Any, field_object) -> str: """ Should convert the value of the provided field to a human readable string for display purposes. :param value: The value of the field extracted from a row to convert to human readable form. :param field_object: The field object for the field to extract :type field_object: FieldObject :return A human readable string. """ human_readable_value = self.get_export_value(value, field_object) if human_readable_value is None: return "" else: return str(human_readable_value) # noinspection PyMethodMayBeStatic def get_other_fields_to_trash_restore_always_together(self, field) -> List[Any]: """ When a field of this type is trashed/restored, or the table it is in trashed/restored, this method should return any other trashable fields that must always be trashed or restored in tandem with this field. For example, a link field has an opposing link field in the other table that should also be trashed when it is trashed. And so for link fields this method is overridden to return the related field so it is trashed/restored correctly. :param field: The specific instance of the field that is being trashed or whose table is being trashed. :return: A list of related fields that should be trashed or restored in tandem with this field or it's table. """ return [] def to_baserow_formula_type(self, field): """ Should return the Baserow Formula Type to use when referencing a field of this type in a formula. :param field: The specific instance of the field that a formula type should be created for. :return: The Baserow Formula Type that represents this field in a formula. """ from baserow.contrib.database.formula import BaserowFormulaInvalidType return BaserowFormulaInvalidType( f"A field of type {self.type} cannot be referenced in a Baserow formula." ) def from_baserow_formula_type(self, formula_type) -> Field: """ Should return the Baserow Field Type when converting a formula type back to a field type. :param formula_type: The specific instance of a formula type that a field type model should be created for. :return: A Baserow Field Type model instance that represents this formula type. """ raise NotImplementedError( f"A field of type {self.type} cannot be referenced in a Baserow formula." ) def to_baserow_formula_expression(self, field): """ Should return a Typed Baserow Formula Expression to use when referencing the field in a formula. :param field: The specific instance of the field that a typed formula expression should be created for. :return: A typed baserow formula expression which when evaluated represents a reference to field. """ from baserow.contrib.database.formula import FormulaHandler return FormulaHandler.get_normal_field_reference_expression( field, self.to_baserow_formula_type(field) ) def get_field_dependencies( self, field_instance, field_lookup_cache ) -> OptionalFieldDependencies: """ Should return a list of field dependencies that field_instance has. A field dependency can either be the name of a field in the same table as field_instance, or a tuple where the first value is the name of a link row field in the same table and the second is the name of a field in the linked table. If instead None is returned this field_type will be treated as if it cannot have dependencies on other fields. :param field_instance: The field_instance to get field dependencies for. :type field_instance: Field :param field_lookup_cache: A cache that can be used to lookup fields. :type field_lookup_cache: FieldCache """ return None def restore_failed(self, field_instance, restore_exception): """ Called when restoring field_instance has caused an exception. Return True if the exception should be swallowed and the restore operation should succeed or False if it should fail and rollback. :param field_instance: The instance of the field which caused restore_exception on field restore. :type field_instance: Field :param restore_exception: The exception that was raised when restoring the field. :type restore_exception: :return: True to swallow the exception and succeed the restore, false to re-raise and fail the restore. :rtype: bool """ return False def row_of_dependency_created( self, field, starting_row, update_collector, via_path_to_starting_table, ): """ Called when a row is created in a dependency field (a field that the field instance parameter depends on). If as a result row value changes are required by this field type an update expression should be provided to the update_collector. Ensure super is called if this fields rows also change so dependants of this field also get notified. :param field: The field whose dependency has had a row created. :param starting_row: The row which was created in the dependency field. :param update_collector: Any update statements should be passed to this collector so they are run correctly at the right time. You should not be manually updating row values yourself in this method. :param via_path_to_starting_table: A list of link row fields if any leading back to the starting table where the row was created. """ self.row_of_dependency_updated( field, starting_row, update_collector, via_path_to_starting_table, ) def row_of_dependency_updated( self, field, starting_row, update_collector, via_path_to_starting_table, ): """ Called when a row or rows are updated in a dependency field (a field that the field instance parameter depends on). If as a result row value changes are required by this field type an update expression should be provided to the update_collector. Ensure super is called if this fields rows also change so dependants of this field also get notified. :param field: The field whose dependency has had a row or rows updated. :param starting_row: The very first row which changed triggering this eventual update notification, might not be in the same table as field or a direct dependency row of field. :param update_collector: Any update statements should be passed to this collector so they are run correctly at the right time. You should not be manually updating row values yourself in this method. :param via_path_to_starting_table: A list of link row fields if any leading back to the starting table where the first row was changed. """ for ( dependant_field, dependant_field_type, dependant_path_to_starting_table, ) in field.dependant_fields_with_types( update_collector, via_path_to_starting_table ): dependant_field_type.row_of_dependency_updated( dependant_field, starting_row, update_collector, dependant_path_to_starting_table, ) def row_of_dependency_deleted( self, field, starting_row, update_collector, via_path_to_starting_table, ): """ Called when a row is deleted in a dependency field (a field that the field instance parameter depends on). If as a result row value changes are required by this field type an update expression should be provided to the update_collector. Ensure super is called if this fields rows also change so dependants of this field also get notified. :param field: The field whose dependency has had a row deleted. :param starting_row: The very row which was deleted. :param update_collector: Any update statements should be passed to this collector so they are run correctly at the right time. You should not be manually updating row values yourself in this method. :param via_path_to_starting_table: A list of link row fields if any leading back to the starting table where the row was deleted. """ self.row_of_dependency_updated( field, starting_row, update_collector, via_path_to_starting_table, ) def row_of_dependency_moved( self, field, starting_row, update_collector, via_path_to_starting_table, ): """ Called when a row is moved in a dependency field (a field that the field instance parameter depends on). If as a result row value changes are required by this field type an update expression should be provided to the update_collector. Ensure super is called if this fields rows also change so dependants of this field also get notified. :param field: The field whose dependency has had a row deleted. :param starting_row: The row which was moved. :param update_collector: Any update statements should be passed to this collector so they are run correctly at the right time. You should not be manually updating row values yourself in this method. :param via_path_to_starting_table: A list of link row fields if any leading back to the starting table where the row was moved. """ self.row_of_dependency_updated( field, starting_row, update_collector, via_path_to_starting_table, ) def field_dependency_created( self, field, created_field, via_path_to_starting_table, update_collector ): """ Called when a field is created which the field parameter depends on. If as a result row value changes are required by this field type an update expression should be provided to the update_collector. Ensure super is called if this field also changes so dependants of this field also get notified. :param field: The field who has had a new dependency field created. :param created_field: The dependency field which was created. :param update_collector: If this field changes the resulting field should be passed to the update_collector. Additionally if this fields row values should also change has a result an update statement should be passed to this collector which will be run correctly at the right time. You should not be manually updating row values yourself in this method. :param via_path_to_starting_table: A list of link row fields if any leading back to the starting table where field was created. """ self.field_dependency_updated( field, field, field, via_path_to_starting_table, update_collector ) def field_dependency_updated( self, field, updated_field, updated_old_field, via_path_to_starting_table, update_collector, ): """ Called when a field is updated which the field parameter depends on. If as a result row value changes are required by this field type an update expression should be provided to the update_collector. Ensure super is called if this field also changes so dependants of this field also get notified. :param field: The field who has had a new dependency field created. :param updated_field: The dependency field which was updated. :param updated_old_field: The instance of the updated field before the update. :param update_collector: If this field changes the resulting field should be passed to the update_collector. Additionally if this fields row values should also change has a result an update statement should be passed to this collector which will be run correctly at the right time. You should not be manually updating row values yourself in this method. :param via_path_to_starting_table: A list of link row fields if any leading back to the starting table the first field change occurred. """ from baserow.contrib.database.fields.dependencies.handler import ( FieldDependencyHandler, ) FieldDependencyHandler.rebuild_dependencies(field, update_collector) for ( dependant_field, dependant_field_type, dependant_path_to_starting_table, ) in field.dependant_fields_with_types( update_collector, via_path_to_starting_table ): dependant_field_type.field_dependency_updated( dependant_field, field, field, dependant_path_to_starting_table, update_collector, ) def field_dependency_deleted( self, field, deleted_field, via_path_to_starting_table, update_collector ): """ Called when a field is deleted which the field parameter depends on. If as a result row value changes are required by this field type an update expression should be provided to the update_collector. Ensure super is called if this field also changes so dependants of this field also get notified. :param field: The field who has had a new dependency field created. :param deleted_field: The dependency field which was deleted. :param update_collector: If this field changes the resulting field should be passed to the update_collector. Additionally if this fields row values should also change has a result an update statement should be passed to this collector which will be run correctly at the right time. You should not be manually updating row values yourself in this method. :param via_path_to_starting_table: A list of link row fields if any leading back to the starting table the field was deleted. """ self.field_dependency_updated( field, field, field, via_path_to_starting_table, update_collector ) def check_can_order_by(self, field): """ Override this method if this field type can sometimes be ordered or sometimes cannot be ordered depending on the individual field state. By default will just return the bool property _can_order_by so if your field type doesn't depend on the field state and is always just True or False just set _can_order_by to the desired value. :param field: The field to check to see if it can be ordered by or not. :return: True if a view can be ordered by this field, False otherwise. """ return self._can_order_by def before_field_options_update( self, field: Field, to_create: List[int] = None, to_update: List[dict] = None, to_delete: List[int] = None, ): """ Called from `FieldHandler.update_field_select_options()` just before the select options of a field are updated in database. :param field: The field instance whose options are updated. :param to_create: A list of dict containing data for each new option added to the field. :param to_update: A list of option ids that already exists and are going to be associated with this field. :param to_delete: A list of option ids that are removed from the field option list. """ # noinspection PyMethodMayBeStatic def before_table_model_invalidated( self, field: Field, ): """ Called before the table the field is in is invalidated in the model cache. Usually this method should be overridden to also invalidate the cache of other tables models which would be affected by this tables cache being invalidated. """ class FieldTypeRegistry( APIUrlsRegistryMixin, CustomFieldsRegistryMixin, ModelRegistryMixin, Registry ): """ With the field type registry it is possible to register new field types. A field type is an abstraction made specifically for Baserow. If added to the registry a user can create new fields based on this type. """ name = "field" does_not_exist_exception_class = FieldTypeDoesNotExist already_registered_exception_class = FieldTypeAlreadyRegistered class FieldConverter(Instance): """ By default when changing a field the lenient schema editor is used to alter the field to make the schema changes. If for whatever reason this does not suffice then a converter can be used to change field and the related data. This is for example used by the link_row field because it is not possible to change a ManyToManyField to another field. Example: from baserow.contrib.database.fields.field_types import ( TextFieldType, DateFieldType ) from baserow.contrib.database.fields.registries import ( FieldConverter, field_converter_registry ) class TextToDateFieldConverter(FieldConverter): type = 'text-to-date' def is_applicable(self, from_model, from_field, to_field): return ( isinstance(from_field, TextFieldType) and isinstance(to_field, DateFieldType) ) def alter_field(self, from_field, to_field, from_model, to_model, from_model_field, to_model_field, user, connection): # This is just for example purposes, but it will delete the old text # field field and create a new date field. You can be very creative # here in how you want to convert field and the data. It is for example # possible to load all the old data in memory, convert it and then # update the new data. Performance should always be kept in mind # though. with safe_django_schema_editor() as schema_editor: schema_editor.remove_field(from_model, from_model_field) schema_editor.add_field(to_model, to_model_field) field_converter_registry.register(TextToDateFieldConverter()) """ def is_applicable(self, from_model, from_field, to_field): """ Decides whether the converter is applicable for the alteration of the provided fields. Before conversion all converters are checked to see if they are applicable. The first one that is will be used. :param from_model: The old model containing only the old field. :type from_model: Model :param from_field: The old field instance. It should only be used for type and property comparison with the the to_field because else things might break. :type from_field: Field :param to_field: The new field instance. It should only be used for type and property comparison with the the from_field because else things might break. :type to_field: Field :return: If True then the alter_field method of this converter will be used to alter the field instead of the lenient schema editor. :rtype: bool """ raise NotImplementedError( "Each field converter must have an is_applicable " "method." ) def alter_field( self, from_field, to_field, from_model, to_model, from_model_field, to_model_field, user, connection, ): """ Should perform the schema change and changes related to the field change. It must bring the field's schema into the desired state. :param from_field: The old field's instance. This should be used for getting the type and properties. Making changes can override things. :type from_field: Field :param to_field: The new field's instance. This should be used for getting the type and properties. It already is in a correct state. :type to_field: Field :param from_model: The old generated model containing only the old field. :type from_model: Model :param to_model: The generated model containing only the new field. :type to_model: Model :param from_model_field: The old field extracted from the old model. :type from_model_field: models.Field :param to_model_field: The new field extracted from the new model. :type to_model_field: models.Field :param user: The user on whose behalf the change is made. :type user: User :param connection: The connection used to make the database schema change. :type connection: DatabaseWrapper """ raise NotImplementedError( "Each field converter must have an alter_field " "method." ) class FieldConverterRegistry(Registry): """ The registry that holds all the available field converters. A field converter can be used to convert a field to another type in a custom way. It can also be used the data related to the field needs a specific conversion. It should be used when the default lenient schema editor does not work. """ name = "field_converter" def find_applicable_converter(self, *args, **kwargs): """ Finds the first applicable converter that is in the register based on the provided arguments. Note that is might be possible for other converters to be applicable also. This only returns the first match, not the best match. Might be an idea to implement something with a priority system once we have lots of converters. :return: The applicable field converter or None if no converter has been found. :rtype: None or FieldConverter """ for converter in self.registry.values(): if converter.is_applicable(*args, **kwargs): return converter return None # A default field type registry is created here, this is the one that is used # throughout the whole Baserow application to add a new field type. field_type_registry = FieldTypeRegistry() field_converter_registry = FieldConverterRegistry()
import attr import struct import msprime import tskit import kastore import json from collections import OrderedDict import warnings import numpy as np from ._version import * from .slim_metadata import * from .provenance import * from .util import * from .slim_metadata import _decode_mutation_pre_nucleotides, _set_metadata_schemas INDIVIDUAL_ALIVE = 2**16 INDIVIDUAL_REMEMBERED = 2**17 # no longer used but keep for a while INDIVIDUAL_FIRST_GEN = 2**18 # A nucleotide k in mutation metadata actually means # something that in reference_sequence is NUCLEOTIDES[k] NUCLEOTIDES = ['A', 'C', 'G', 'T'] def load(path, legacy_metadata=False): ''' Load the SLiM-compatible tree sequence found in the .trees file at ``path``. :param string path: The path to a .trees file. :param bool legacy_metadata: If True, then the resulting tree sequence will provide old-style metadata: as objects instead of dictionaries. This option is deprecated and will dissappear at some point in the future. ''' ts = SlimTreeSequence.load(path) return ts def load_tables(tables, **kwargs): ''' See :func:`SlimTreeSequence.load_tables`. :param TableCollection tables: A set of tables. ''' ts = SlimTreeSequence.load_tables(tables, **kwargs) return ts def annotate_defaults(ts, model_type, slim_generation, reference_sequence=None): ''' Takes a tree sequence (as produced by msprime, for instance), and adds in the information necessary for SLiM to use it as an initial state, filling in mostly default values. Returns a :class:`SlimTreeSequence`. :param TreeSequence ts: A :class:`TreeSequence`. :param string model_type: SLiM model type: either "WF" or "nonWF". :param int slim_generation: What generation number in SLiM correponds to ``time=0`` in the tree sequence. ''' tables = ts.dump_tables() annotate_defaults_tables(tables, model_type, slim_generation) return SlimTreeSequence.load_tables(tables, reference_sequence=reference_sequence) def annotate_defaults_tables(tables, model_type, slim_generation): ''' Does the work of :func:`annotate_defaults()`, but modifies the tables in place: so, takes tables as produced by ``msprime``, and makes them look like the tables as output by SLiM. See :func:`annotate_defaults` for details. ''' if (type(slim_generation) is not int) or (slim_generation < 1): raise ValueError("SLiM generation must be an integer and at least 1.") # set_nodes must come before set_populations if model_type == "WF": default_ages = -1 elif model_type == "nonWF": default_ages = 0 else: raise ValueError("Model type must be 'WF' or 'nonWF'") set_tree_sequence_metadata(tables, **default_slim_metadata['tree_sequence']['SLiM']) _set_nodes_individuals(tables, age=default_ages) _set_populations(tables) _set_sites_mutations(tables) class MetadataDictWrapper(dict): ''' A simple wrapper around metadata dicts that will throw an informative error message if ``md.X`` is used instead of ``md["X"]``, and (for mutation metadata) if ``md[k]`` is used instead of ``md["mutation_list"][k]``. ''' def __getattr__(self, name): if name in self.keys(): raise AttributeError( f"'dict' object has no attribute '{name}'. " "It looks like you're trying to use the legacy " "metadata interface: see " "`the documentation <https://pyslim.readthedocs.io/en/latest/metadata.html#legacy-metadata>`_ " "for how to switch over your script") else: raise AttributeError(f"'dict' object has no attribute '{name}'") def __getitem__(self, key): try: return super().__getitem__(key) except KeyError as e: if isinstance(key, int): msg = e.args[0] e.args = (f"{msg}: It looks like you're trying to use the legacy " "metadata interface: see " "`the documentation <https://pyslim.readthedocs.io/en/latest/metadata.html#legacy-metadata>`_ " "for how to switch over your script",) raise e class SlimTreeSequence(tskit.TreeSequence): ''' This is just like a :class:`tskit.TreeSequence`, with a few more properties and methods, including: - :attr:`.slim_generation` - the SLiM "generation" at the end of the simulation - :attr:`.reference_sequence` - if using a nucleotide model, the reference sequence - :attr:`.individual_locations` - numpy array of individual locations - :attr:`.individual_ages` - numpy array of individiual ages - :attr:`.individual_times` - numpy array of how long ago each individual was born - :attr:`.individual_populations` - numpy array of individual's populations All mutable properties of individuals (e.g., age) is as it was recorded during the individual's last time step alive (or at the end of the simulation, if they are still alive). You can create a :class:`.SlimTreeSequence` using one of - :meth:`.SlimTreeSequence.load_tables` :meth:`.SlimTreeSequence.load`, - :func:`.load`, or :func:`.load_tables`. :ivar slim_generation: The generation that the SLiM simulation was at upon writing; will be read from metadata if not provided. :ivar reference_sequence: None, or an string of length equal to the sequence length that gives the entire reference sequence for nucleotide models. :ivar legacy_metadata: Whether this tree sequence returns metadata in objects (as in older versions of pyslim) rather than dicts: see `the documentation <https://pyslim.readthedocs.io/en/latest/metadata.html#legacy-metadata>`_. This option is deprecated and will disappear at some point. :vartype slim_generation: int :vartype reference_sequence: string ''' def __init__(self, ts, reference_sequence=None, legacy_metadata=False): self.legacy_metadata = legacy_metadata if not (isinstance(ts.metadata, dict) and 'SLiM' in ts.metadata and ts.metadata['SLiM']['file_version'] == slim_file_version): tables = ts.dump_tables() if not (isinstance(tables.metadata, dict) and 'SLiM' in tables.metadata): _set_metadata_from_provenance(tables) if tables.metadata['SLiM']['file_version'] != slim_file_version: _upgrade_old_tables(tables) # cannot assign directly to keys of metadata md = tables.metadata md['SLiM']['file_version'] = slim_file_version tables.metadata = md ts = tables.tree_sequence() slim_generation = ts.metadata['SLiM']['generation'] self.model_type = ts.metadata['SLiM']['model_type'] super().__init__(ts._ll_tree_sequence) self.slim_generation = slim_generation self.reference_sequence = reference_sequence # pre-extract individual metadata self.individual_locations = ts.tables.individuals.location self.individual_locations.shape = (int(len(self.individual_locations)/3), 3) self.individual_ages = np.zeros(ts.num_individuals, dtype='int') if self.model_type != "WF": self.individual_ages = np.fromiter(map(lambda ind: ind.metadata['age'], ts.individuals()), dtype='int64') self.individual_times = np.zeros(ts.num_individuals) self.individual_populations = np.repeat(np.int32(-1), ts.num_individuals) if not np.all(unique_labels_by_group(ts.tables.nodes.individual, ts.tables.nodes.population)): raise ValueError("Individual has nodes from more than one population.") if not np.all(unique_labels_by_group(ts.tables.nodes.individual, ts.tables.nodes.time)): raise ValueError("Individual has nodes from more than one time.") has_indiv = (ts.tables.nodes.individual >= 0) which_indiv = ts.tables.nodes.individual[has_indiv] # if we did not do the sanity check above then an individual with nodes in more than one pop # would get the pop of their last node in the list self.individual_populations[which_indiv] = ts.tables.nodes.population[has_indiv] self.individual_times[which_indiv] = ts.tables.nodes.time[has_indiv] @classmethod def load(cls, path, legacy_metadata=False): ''' Load a :class:`SlimTreeSequence` from a .trees file on disk. :param string path: The path to a .trees file. :rtype SlimTreeSequence: ''' ts = tskit.load(path) # extract the reference sequence from the kastore kas = kastore.load(path) if 'reference_sequence/data' in kas: int_rs = kas['reference_sequence/data'] reference_sequence = int_rs.tostring().decode('ascii') else: reference_sequence = None return cls(ts, reference_sequence=reference_sequence, legacy_metadata=legacy_metadata) @classmethod def load_tables(cls, tables, **kwargs): ''' Creates the :class:`SlimTreeSequence` defined by the tables. :param TableCollection tables: A set of tables, as produced by SLiM or by annotate_defaults(). :param TableCollection reference_sequence: An optional string of ACGT giving the reference sequence. :rtype SlimTreeSequence: ''' # a roundabout way to copy the tables ts = tables.tree_sequence() return cls(ts, **kwargs) def dump(self, path, **kwargs): ''' Dumps the tree sequence to the path specified. This is mostly just a wrapper for tskit.TreeSequence.dump(), but also writes out the reference sequence. :param str path: The file path to write the TreeSequence to. :param kwargs: Additional keyword args to pass to tskit.TreeSequence.dump ''' super(SlimTreeSequence, self).dump(path, **kwargs) if self.reference_sequence is not None: # to convert to a kastore store we need to reload from a file, # and for it to be mutable we need to make it a dict kas = dict(kastore.load(path)) kas['reference_sequence/data'] = np.frombuffer(self.reference_sequence.encode(), dtype=np.int8) kastore.dump(kas, path) def simplify(self, *args, **kwargs): ''' This is a wrapper for :meth:`tskit.TreeSequence.simplify`. The only difference is that this method returns the derived class :class:`.SlimTreeSequence`. If you have not yet recapitated your SlimTreeSequence, you probably want to pass ``keep_input_roots=True``, so that recapitation is possible in the future. :rtype SlimTreeSequence: ''' sts = super(SlimTreeSequence, self).simplify(*args, **kwargs) if (type(sts) == tuple): ret = (SlimTreeSequence(sts[0]), sts[1]) ret[0].reference_sequence = self.reference_sequence else: ret = SlimTreeSequence(sts) ret.reference_sequence = self.reference_sequence return ret def population(self, id_): ''' Returns the population whose ID is given by `id_`, as documented in :meth:`tskit.TreeSequence.population`, but with additional attributes:: slim_id, selfing_fraction, female_cloning_fraction, male_cloning_fraction, sex_ratio, bounds_x0, bounds_x1, bounds_y0, bounds_y1, bounds_z0, bounds_z1, migration_records. These are all recorded by SLiM in the metadata. Note that SLiM populations are usually indexed starting from 1, but in tskit from zero, so there may be populations (e.g., with id_=0) that have no metadata and are not used by SLiM. :param int id_: The ID of the population (i.e., its index). ''' pop = super(SlimTreeSequence, self).population(id_) if self.legacy_metadata: try: pop.metadata = PopulationMetadata.fromdict(pop.metadata) except: pass else: if pop.metadata is not None: pop.metadata = MetadataDictWrapper(pop.metadata) return pop def individual(self, id_): ''' Returns the individual whose ID is given by `id_`, as documented in :meth:`tskit.TreeSequence.individual`, but with additional attributes:: time, pedigree_id, age, slim_population, sex, slim_flags. The `time` and `population` properties are extracted from the nodes, and an error will be thrown if the individual's nodes derive from more than one population or more than one time. :param int id_: The ID of the individual (i.e., its index). ''' ind = super(SlimTreeSequence, self).individual(id_) ind.population = self.individual_populations[id_] ind.time = self.individual_times[id_] if self.legacy_metadata: try: ind.metadata = IndividualMetadata.fromdict(ind.metadata) except: pass else: ind.metadata = MetadataDictWrapper(ind.metadata) return ind def node(self, id_): ''' Returns the node whose ID is given by `id_`, as documented in :meth:`tskit.TreeSequence.node`, but with additional attributes:: slim_id, is_null, genome_type. These are all recorded by SLiM in the metadata. :param int id_: The ID of the node (i.e., its index). ''' node = super(SlimTreeSequence, self).node(id_) if self.legacy_metadata: try: node.metadata = NodeMetadata.fromdict(node.metadata) except: pass else: if node.metadata is not None: node.metadata = MetadataDictWrapper(node.metadata) return node def mutation(self, id_): ''' Returns the mutation whose ID is given by `id_`, as documented in :meth:`tskit.TreeSequence.mutation`, but with additional attributes:: mutation_type, selection_coeff, population, slim_time, nucleotide. These are all recorded by SLiM in the metadata. :param int id_: The ID of the mutation (i.e., its index). ''' mut = super(SlimTreeSequence, self).mutation(id_) if self.legacy_metadata: try: mut.metadata = [MutationMetadata.fromdict(x) for x in mut.metadata['mutation_list']] except: pass else: mut.metadata = MetadataDictWrapper(mut.metadata) return mut def recapitate(self, recombination_rate=None, population_configurations=None, recombination_map=None, **kwargs): ''' Returns a "recapitated" tree sequence, by using msprime to run a coalescent simulation from the "top" of this tree sequence, i.e., allowing any uncoalesced lineages to coalesce. To allow recapitation to be done correctly, the nodes of the first generation of the SLiM simulation from whom all samples inherit are still present in the tree sequence, but are not marked as samples. If you simplify the tree sequence before recapitating you must ensure these are not removed, which you do by passing the argument ``keep_input_roots=True`` to :meth:`.simplify()`. Note that ``Ne`` is not set automatically, so defaults to ``1.0``; you probably want to set it explicitly. Similarly, migration is not set up automatically, so that if there are uncoalesced lineages in more than one population, you will need to pass in a migration matrix to allow coalescence. In both cases, remember that population IDs in ``tskit`` begin with 0, so that if your SLiM simulation has populations ``p1`` and ``p2``, then the tree sequence will have three populations (but with no nodes assigned to population 0), so that migration rate of 1.0 between ``p1`` and ``p2`` needs a migration matrix of:: [[0.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 1.0, 0.0]] In general, all defaults are whatever the defaults of ``msprime.simulate`` are; this includes recombination rate, so that if neither ``recombination_rate`` or a ``recombination_map`` are provided, there will be *no* recombination. However, if ``recombination_rate`` *is* provided, then recapitation will use a constant rate of recombination on a discretized map -- in other words, recombinations in the coalescent portion of the simulation will only occur at integer locations, just as in SLiM. If you do not want this to happen, you need to construct a ``recombination_map`` explicitly. :param float recombination_rate: A (constant) recombination rate, in units of crossovers per nucleotide per unit of time. :param list population_configurations: See :meth:`msprime.simulate` for this argument; if not provided, each population will have zero growth rate and the same effective population size. :type recombination_map: :class`msprime.RecombinationMap` :param recombination_map: The recombination map, or None, if recombination_rate is specified. :param dict kwargs: Any other arguments to :meth:`msprime.simulate`. ''' if "keep_first_generation" in kwargs: raise ValueError("The keep_first_generation argument is deprecated:" "the FIRST_GEN flag is no longer used.") # toggle for hacks below to deal with old msprime discrete_msprime = hasattr(msprime, "RateMap") if recombination_rate is not None: if recombination_map is not None: raise ValueError("Cannot specify length/recombination_rate along with a recombination map") if discrete_msprime: recombination_map = msprime.RecombinationMap(positions = [0.0, self.sequence_length], rates = [recombination_rate, 0.0]) else: recombination_map = msprime.RecombinationMap(positions = [0.0, self.sequence_length], rates = [recombination_rate, 0.0], num_loci = int(self.sequence_length)) if discrete_msprime and ('discrete_genome' not in kwargs): kwargs['discrete_genome'] = True if population_configurations is None: population_configurations = [msprime.PopulationConfiguration() for _ in range(self.num_populations)] recap = msprime.simulate( from_ts = self, population_configurations = population_configurations, recombination_map = recombination_map, start_time = self.slim_generation, **kwargs) # HACK to deal with older msprime that doesn't retain metadata # by copying over the metadata if recap.metadata == b'': tables = recap.tables tables.metadata = self._ll_tree_sequence.get_metadata() tables.metadata_schema = self.metadata_schema _set_metadata_schemas(tables) recap = tables.tree_sequence() return SlimTreeSequence(recap, reference_sequence=self.reference_sequence) def mutation_at(self, node, position, time=None): ''' Finds the mutation present in the genome of ``node`` at ``position``, returning -1 if there is no such mutation recorded in the tree sequence. Warning: if ``node`` is not actually in the tree sequence (e.g., not ancestral to any samples) at ``position``, then this function will return -1, possibly erroneously. If `time` is provided, returns the last mutation at ``position`` inherited by ``node`` that occurred at or before ``time`` ago. :param int node: The index of a node in the tree sequence. :param float position: A position along the genome. :param int time: The time ago that we want the nucleotide, or None, in which case the ``time`` of ``node`` is used. :returns: Index of the mutation in question, or -1 if none. ''' if position < 0 or position >= self.sequence_length: raise ValueError("Position {} not valid.".format(position)) if node < 0 or node >= self.num_nodes: raise ValueError("Node {} not valid.".format(node)) if time is None: time = self.node(node).time tree = self.at(position) site_pos = self.tables.sites.position out = tskit.NULL if position in site_pos: site_index = np.where(site_pos == position)[0][0] site = self.site(site_index) mut_nodes = [] # look for only mutations that occurred before `time` # not strictly necessary if time was None for mut in site.mutations: if mut.time >= time: mut_nodes.append(mut.node) n = node while n > -1 and n not in mut_nodes: n = tree.parent(n) if n >= 0: # do careful error checking here for mut in site.mutations: if mut.node == n: assert(out == tskit.NULL or out == mut.parent) out = mut.id return out def nucleotide_at(self, node, position, time=None): ''' Finds the nucleotide present in the genome of ``node`` at ``position``. Warning: if ``node`` is not actually in the tree sequence (e.g., not ancestral to any samples) at ``position``, then this function will return the reference sequence nucleotide, possibly erroneously. If `time` is provided, returns the last nucletide produced by a mutation at ``position`` inherited by ``node`` that occurred at or before ``time`` ago. :param int node: The index of a node in the tree sequence. :param float position: A position along the genome. :param int time: The time ago that we want the nucleotide, or None, in which case the ``time`` of ``node`` is used. :returns: Index of the nucleotide in ``NUCLEOTIDES`` (0=A, 1=C, 2=G, 3=T). ''' if self.reference_sequence is None: raise ValueError("This tree sequence has no reference sequence.") mut_id = self.mutation_at(node, position, time) if mut_id == tskit.NULL: out = NUCLEOTIDES.index(self.reference_sequence[int(position)]) else: mut = self.mutation(mut_id) k = np.argmax([u["slim_time"] for u in mut.metadata["mutation_list"]]) out = mut.metadata["mutation_list"][k]["nucleotide"] return out @property def slim_provenance(self): ''' Returns model type, slim generation, and remembered node count from the last entry in the provenance table that is tagged with "program"="SLiM". NOTE: you probably want to use the ``.metadata`` property instead. :rtype ProvenanceMetadata: ''' warnings.warn("This is deprecated: get information from " "ts.metadata['SLiM'] instead.", DeprecationWarning) return get_provenance(self, only_last=True) @property def slim_provenances(self): ''' Returns model type, slim generation, and remembered node count from *all* entries in the provenance table that is tagged with "program"="SLiM" :rtype ProvenanceMetadata: ''' return get_provenance(self, only_last=False) def _mark_first_generation(self): ''' Mark all 'first generation' individuals' nodes as samples, and return the corresponding tree sequence. DEPRECATED ''' tables = self.dump_tables() first_gen_nodes = ((tables.nodes.individual > 0) & ((tables.individuals.flags[tables.nodes.individual] & INDIVIDUAL_FIRST_GEN) > 0)) if sum(first_gen_nodes) == 0: warnings.warn("Tree sequence does not have the initial generation; " + " did you simplify it after output from SLiM?") flags = tables.nodes.flags flags[first_gen_nodes] = (flags[first_gen_nodes] | tskit.NODE_IS_SAMPLE) tables.nodes.set_columns(flags=flags, population=tables.nodes.population, individual=tables.nodes.individual, time=tables.nodes.time, metadata=tables.nodes.metadata, metadata_offset=tables.nodes.metadata_offset) ts = load_tables(tables) ts.reference_sequence = self.reference_sequence return ts def individuals_alive_at(self, time, stage='late', remembered_stage=None): """ Returns an array giving the IDs of all individuals that are known to be alive at the given time ago. This is determined using their birth time ago (given by their `time` attribute) and, for nonWF models, their `age` attribute (which is equal to their age at the last time they were Remembered). See also :meth:`.individual_ages_at`. In WF models, birth occurs after "early()", so that individuals are only alive during "late()" for the time step when they have age zero, while in nonWF models, birth occurs before "early()", so they are alive for both stages. In both WF and nonWF models, mortality occurs between "early()" and "late()", so that individuals are last alive during the "early()" stage of the time step of their final age, and if individuals are alive during "late()" they will also be alive during "early()" of the next time step. This means it is important to know during which stage individuals were Remembered - for instance, if the call to sim.treeSeqRememberIndividuals() was made during "early()" of a given time step, then those individuals might not have survived until "late()" of that time step. Since SLiM does not record the stage at which individuals were Remembered, you can specify this by setting ``remembered_stages``: it should be the stage during which *all* calls to sim.treeSeqRememberIndividuals, as well as to sim.treeSeqOutput(), were made. Note also that in nonWF models, birth occurs before "early()", so the possible parents in a given time step are those that are alive in "early()" and have age greater than zero, or, equivalently, are alive in "late()" during the previous time step. In WF models, birth occurs after "early()", so possible parents in a given time step are those that are alive during "early()" of that time step or are alive during "late()" of the previous time step. :param float time: The number of time steps ago. :param str stage: The stage in the SLiM life cycle that we are inquiring about (either "early" or "late"; defaults to "late"). :param str remembered_stage: The stage in the SLiM life cycle that individuals were Remembered during (defaults to the stage the tree sequence was recorded at, stored in metadata). """ if stage not in ("late", "early"): raise ValueError(f"Unknown stage '{stage}': " "should be either 'early' or 'late'.") if remembered_stage is None: remembered_stage = self.metadata['SLiM']['stage'] if remembered_stage not in ("late", "early"): raise ValueError(f"Unknown remembered_stage '{remembered_stage}': " "should be either 'early' or 'late'.") if remembered_stage != self.metadata['SLiM']['stage']: warnings.warn(f"Provided remembered_stage '{remembered_stage}' does not" " match the stage at which the tree sequence was saved" f" ('{self.metadata["SLiM"]["stage"]}'). This is not necessarily" " an error, but mismatched stages will lead to inconsistencies:" " make sure you know what you're doing.") # birth_time is the time ago that they were first alive in 'late' # in a nonWF model they are alive for the same time step's 'early' # but in a WF model the first 'early' they were alive for is one more recent birth_time = self.individual_times # birth_time - birth_offset is the first time ago they were alive # during stage 'stage' if stage == "early" and self.metadata['SLiM']['model_type'] == "WF": birth_offset = 1 else: birth_offset = 0 # ages is the number of complete life cycles they are known to have lived through, # and so individuals have lived through at least 'age + 1' of both stages. # In nonWF models, they live for one more 'early' than 'late', # but this is only reflected in their age if Remembered in 'early'. ages = self.individual_ages # ages + age_offset + 1 is the number of 'stage' stages they are known # to have lived through if (self.metadata['SLiM']['model_type'] == "WF" or stage == remembered_stage): age_offset = 0 else: if (remembered_stage == "early" and stage == "late"): age_offset = -1 else: age_offset = 1 # if adjusted age=0 then they are be alive at exactly one time step alive_bool = np.logical_and( birth_time >= time + birth_offset, birth_time - ages <= time + birth_offset + age_offset) return np.where(alive_bool)[0] def individual_ages_at(self, time, stage="late", remembered_stage="late"): """ Returns the *ages* of each individual at the corresponding time ago, which will be `nan` if the individual is either not born yet or dead. This is computed as the time ago the individual was born (found by the `time` associated with the the individual's nodes) minus the `time` argument; while "death" is inferred from the individual's `age`, recorded in metadata. These values are the same as what would be shown in SLiM during the corresponding time step and stage. Since age increments at the end of each time step, the age is the number of time steps ends the individual has lived through, so if they were born in time step `time`, then their age will be zero. In a WF model, this method does not provide any more information than does :meth:`.individuals_alive_at`, but for consistency, non-nan ages will be 0 in "late" and 1 in "early". See :meth:`.individuals_alive_at` for further discussion. :param float time: The reference time ago. :param str stage: The stage in the SLiM life cycle used to determine who is alive (either "early" or "late"; defaults to "late"). :param str remembered_stage: The stage in the SLiM life cycle that individuals were Remembered during. """ ages = np.repeat(np.nan, self.num_individuals) alive = self.individuals_alive_at(time, stage=stage, remembered_stage=remembered_stage) ages[alive] = self.individual_times[alive] - time return ages def first_generation_individuals(self): """ Returns the IDs of the individuals remembered as part of the first SLiM generation, as determined by their flags. .. warning:: This method is deprecated, because from SLiM version 3.5 the first generation individuals are no longer marked as such: only tree sequences from older versions of SLiM will have these individuals. """ return np.where(self.tables.individuals.flags & INDIVIDUAL_FIRST_GEN > 0)[0] def has_individual_parents(self): ''' Finds which individuals have both their parent individuals also present in the tree sequence, as far as we can tell. To do this, we return the IDs of individuals for which: - all edges terminating in that individual's nodes are in individuals, - each of the individual's nodes inherit from a single individual only, - those parental individuals were alive when the individual was born, - the parental individuals account for two whole genomes. This returns a boolean array indicating for each individual whether all these are true. See :meth:`.individuals_alive_at` for further discussion about how this is determined based on when the individuals were Remembered. :return: A boolean array of length equal to ``targets``. ''' edges = self.tables.edges nodes = self.tables.nodes edge_parent_indiv = nodes.individual[edges.parent] edge_child_indiv = nodes.individual[edges.child] # nodes whose parent nodes are all in the same individual unique_parent_nodes = unique_labels_by_group( edges.child, edge_parent_indiv, minlength=nodes.num_rows) unique_parent_edges = unique_parent_nodes[edges.child] # edges describing relationships between individuals indiv_edges = np.logical_and( np.logical_and(edge_parent_indiv != tskit.NULL, edge_child_indiv != tskit.NULL), unique_parent_edges) # individual edges where the parent was alive during "late" # of the time step before the child is born child_births = self.individual_times[edge_child_indiv[indiv_edges]] parent_births = self.individual_times[edge_parent_indiv[indiv_edges]] alive_edges = indiv_edges.copy() if self.metadata['SLiM']['model_type'] == "WF": alive_edges[indiv_edges] = (child_births + 1 == parent_births) else: parent_deaths = parent_births - self.individual_ages[edge_parent_indiv[indiv_edges]] alive_edges[indiv_edges] = (child_births + 1 >= parent_deaths) # total genome inherited from parents edge_spans = edges.right - edges.left parental_span = np.bincount(edge_child_indiv[alive_edges], weights=edge_spans[alive_edges], minlength=self.num_individuals) # we could also check for edges without individual parents terminating # in this individual, but this is unnecessary as the entire genome is # accounted for has_all_parents = (parental_span == 2 * self.sequence_length) return has_all_parents def _set_metadata_from_provenance(tables): # note this uses defaults on keys not present in provenance, # which prior to 0.5 was everything but generation and model_type values = default_slim_metadata['tree_sequence']['SLiM'] prov = None file_version = 'unknown' # use only the last SLiM provenance for p in tables.provenances: is_slim, this_file_version = slim_provenance_version(p) if is_slim: prov = p file_version = this_file_version values['file_version'] = file_version try: record = json.loads(prov.record) if file_version == "0.1": values['model_type'] = record['model_type'] values['generation'] = record['generation'] else: for k in values: if k in record['parameters']: values[k] = record['parameters'][k] values['generation'] = record['slim']['generation'] except: raise ValueError("Failed to obtain metadata from provenance.") set_tree_sequence_metadata(tables, **values) def _upgrade_old_tables(tables): with warnings.catch_warnings(): warnings.simplefilter("ignore") provenance = get_provenance(tables) file_version = provenance.file_version slim_generation = provenance.slim_generation warnings.warn("This is an version {} SLiM tree sequence.".format(file_version) + " When you write this out, " + "it will be converted to version {}.".format(slim_file_version)) if file_version == "0.1" or file_version == "0.2": # add empty nucleotide slots to metadata mut_bytes = tskit.unpack_bytes(tables.mutations.metadata, tables.mutations.metadata_offset) mut_metadata = [_decode_mutation_pre_nucleotides(md) for md in mut_bytes] metadata, metadata_offset = tskit.pack_bytes(mut_metadata) tables.mutations.set_columns( site=tables.mutations.site, node=tables.mutations.node, parent=tables.mutations.parent, derived_state=tables.mutations.derived_state, derived_state_offset=tables.mutations.derived_state_offset, metadata=metadata, metadata_offset=metadata_offset) if file_version == "0.1": # shift times node_times = tables.nodes.time + slim_generation tables.nodes.set_columns( flags=tables.nodes.flags, time=node_times, population=tables.nodes.population, individual=tables.nodes.individual, metadata=tables.nodes.metadata, metadata_offset=tables.nodes.metadata_offset) migration_times = tables.migrations.time + slim_generation tables.migrations.set_columns( left=tables.migrations.left, right=tables.migrations.right, node=tables.migrations.node, source=tables.migrations.source, dest=tables.migrations.dest, time=migration_times) new_record = { "schema_version": "1.0.0", "software": { "name": "pyslim", "version": pyslim_version, }, "parameters": { "command": ["_upgrade_old_tables"], "old_file_version": file_version, "new_file_version": slim_file_version, }, "environment": get_environment(), } tskit.validate_provenance(new_record) tables.provenances.add_row(json.dumps(new_record)) def _set_nodes_individuals( tables, node_ind=None, location=(0, 0, 0), age=0, ind_id=None, ind_population=None, ind_sex=INDIVIDUAL_TYPE_HERMAPHRODITE, ind_flags=INDIVIDUAL_ALIVE, slim_ind_flags=0, node_id=None, node_is_null=False, node_type=GENOME_TYPE_AUTOSOME): ''' Adds to a TableCollection the information relevant to individuals required for SLiM to load in a tree sequence, that is found in Node and Individual tables. This will replace any existing Individual table, and will replace any information already in the individual, metadata, and population columns of the Node table. This is designed to make it easy to assign default values: - (node_ind) the 2*j-th and (2*j+1)-st `sample` nodes to individual j - (location) individual locations to (0, 0, 0) - (age) individual age to 0 - (ind_id) SLiM individual pedigree IDs to sequential integers starting from 0 - (ind_population) individual populations to 0 - (node_id) SLiM genome IDs to sequential integers starting with samples from 0 - (node_is_null) genomes to be non-null - (node_type) genome type to 0 (= autosome) - (ind_flags) INDIVIDUAL_ALIVE If you have other situations, like non-alive "remembered" individuals, you will need to edit the tables by hand, afterwards. ''' samples = list(filter(lambda j: tables.nodes.flags[j] & tskit.NODE_IS_SAMPLE, range(tables.nodes.num_rows))) if (len(samples) % 2) != 0: raise ValueError("There must be an even number of sampled nodes,"\ + "since organisms are diploid.") if node_ind is None: node_ind = [tskit.NULL for _ in range(tables.nodes.num_rows)] for j, k in enumerate(samples): node_ind[j] = int(k/2) num_individuals = max(node_ind) + 1 num_nodes = tables.nodes.num_rows if type(location) is tuple: location = [location for _ in range(num_individuals)] assert(len(location) == num_individuals) if type(age) is int or type(age) is float: age = [age for _ in range(num_individuals)] assert(len(age) == num_individuals) if ind_id is None: ind_id = list(range(num_individuals)) assert(len(ind_id) == num_individuals) if type(ind_sex) is int: ind_sex = [ind_sex for _ in range(num_individuals)] assert(len(ind_sex) == num_individuals) if type(slim_ind_flags) is int: slim_ind_flags = [slim_ind_flags for _ in range(num_individuals)] assert(len(slim_ind_flags) == num_individuals) if type(ind_flags) is int: ind_flags = [ind_flags for _ in range(num_individuals)] assert(len(ind_flags) == num_individuals) if node_id is None: node_id = [-1 for _ in range(num_nodes)] for j, k in enumerate(list(samples) + sorted(list(set(range(num_nodes)) - set(samples)))): node_id[k] = j assert(len(node_id) == num_nodes) if type(node_is_null) is bool: node_is_null = [node_is_null for _ in range(num_nodes)] assert(len(node_is_null) == num_nodes) if type(node_type) is int: node_type = [node_type for _ in range(num_nodes)] assert(len(node_type) == tables.nodes.num_rows) if ind_population is None: # set the individual populations based on what's in the nodes ind_population = [tskit.NULL for _ in range(num_individuals)] for j, u in enumerate(node_ind): if u >= 0: ind_population[u] = tables.nodes.population[j] assert(len(ind_population) == num_individuals) # check for consistency: every individual has two nodes, and populations agree ploidy = [0 for _ in range(num_individuals)] for j in samples: u = node_ind[j] assert(u >= 0) ploidy[u] += 1 if tables.nodes.population[j] != ind_population[u]: raise ValueError("Inconsistent populations: nodes and individuals do not agree.") if any([p != 2 for p in ploidy]): raise ValueError("Not all individuals have two assigned nodes.") loc_vec, loc_off = tskit.pack_bytes(location) ims = tables.individuals.metadata_schema individual_metadata = [ {'pedigree_id': iid, 'age': a, 'subpopulation': int(pop), 'sex': sex, 'flags': f} for (iid, a, pop, sex, f) in zip(ind_id, age, ind_population, ind_sex, slim_ind_flags)] assert(len(individual_metadata) == num_individuals) individual_metadata, individual_metadata_offset = tskit.pack_bytes( [ims.encode_row(r) for r in individual_metadata]) tables.individuals.set_columns( flags=ind_flags, location=loc_vec, location_offset=loc_off, metadata=individual_metadata, metadata_offset=individual_metadata_offset) assert(tables.individuals.num_rows == num_individuals) node_metadata = [None for _ in range(num_nodes)] for j in samples: node_metadata[j] = {'slim_id': node_id[j], 'is_null': node_is_null[j], 'genome_type': node_type[j] } nms = tables.nodes.metadata_schema node_metadata, node_metadata_offset = tskit.pack_bytes( [nms.encode_row(r) for r in node_metadata]) tables.nodes.set_columns(flags=tables.nodes.flags, time=tables.nodes.time, population=tables.nodes.population, individual=node_ind, metadata=node_metadata, metadata_offset=node_metadata_offset) def _set_populations( tables, pop_id=None, selfing_fraction=0.0, female_cloning_fraction=0.0, male_cloning_fraction=0.0, sex_ratio=0.5, bounds_x0=0.0, bounds_x1=0.0, bounds_y0=0.0, bounds_y1=0.0, bounds_z0=0.0, bounds_z1=0.0, migration_records=None): ''' Adds to a TableCollection the information about populations required for SLiM to load a tree sequence. This will replace anything already in the Population table. ''' num_pops = max(tables.nodes.population) + 1 for ind in tables.individuals: md = ind.metadata if not (isinstance(md, dict) and 'subpopulation' in md): raise ValueError("Individuals do not have valid metadata: " "need to run set_nodes_individuals() first?") if md['subpopulation'] >= num_pops: raise ValueError("Bad population in individual metadata.") if pop_id is None: pop_id = list(range(num_pops)) assert(len(pop_id) == num_pops) if type(selfing_fraction) is float: selfing_fraction = [selfing_fraction for _ in range(num_pops)] assert(len(selfing_fraction) == num_pops) if type(female_cloning_fraction) is float: female_cloning_fraction = [female_cloning_fraction for _ in range(num_pops)] assert(len(female_cloning_fraction) == num_pops) if type(male_cloning_fraction) is float: male_cloning_fraction = [male_cloning_fraction for _ in range(num_pops)] assert(len(male_cloning_fraction) == num_pops) if type(sex_ratio) is float: sex_ratio = [sex_ratio for _ in range(num_pops)] assert(len(sex_ratio) == num_pops) if type(bounds_x0) is float: bounds_x0 = [bounds_x0 for _ in range(num_pops)] assert(len(bounds_x0) == num_pops) if type(bounds_x1) is float: bounds_x1 = [bounds_x1 for _ in range(num_pops)] assert(len(bounds_x1) == num_pops) if type(bounds_y0) is float: bounds_y0 = [bounds_y0 for _ in range(num_pops)] assert(len(bounds_y0) == num_pops) if type(bounds_y1) is float: bounds_y1 = [bounds_y1 for _ in range(num_pops)] assert(len(bounds_y1) == num_pops) if type(bounds_z0) is float: bounds_z0 = [bounds_z0 for _ in range(num_pops)] assert(len(bounds_z0) == num_pops) if type(bounds_z1) is float: bounds_z1 = [bounds_z1 for _ in range(num_pops)] assert(len(bounds_z1) == num_pops) if migration_records is None: migration_records = [[] for _ in range(num_pops)] assert(len(migration_records) == num_pops) for mrl in migration_records: for mr in mrl: assert(isinstance(mr, dict)) population_metadata = [ { "slim_id" : pid, "selfing_fraction" : sf, "female_cloning_fraction" : fcf, "male_cloning_fraction" : mcf, "sex_ratio" : sr, "bounds_x0" : x0, "bounds_x1" : x1, "bounds_y0" : y0, "bounds_y1" : y1, "bounds_z0" : z0, "bounds_z1" : z1, "migration_records" : mr, } for (pid, sf, fcf, mcf, sr, x0, x1, y0, y1, z0, z1, mr) in zip(pop_id, selfing_fraction, female_cloning_fraction, male_cloning_fraction, sex_ratio, bounds_x0, bounds_x1, bounds_y0, bounds_y1, bounds_z0, bounds_z1, migration_records)] ms = tables.populations.metadata_schema tables.populations.packset_metadata( [ms.encode_row(r) for r in population_metadata]) def _set_sites_mutations( tables, mutation_id=None, mutation_type=1, selection_coeff=0.0, population=tskit.NULL, slim_time=None): ''' Adds to a TableCollection the information relevant to mutations required for SLiM to load in a tree sequence. This means adding to the metadata column of the Mutation table, It will also - give SLiM IDs to each mutation - round Site positions to integer values - stack any mutations that end up at the same position as a result - replace ancestral states with "" This will replace any information already in the metadata or derived state columns of the Mutation table. ''' num_mutations = tables.mutations.num_rows if mutation_id is None: mutation_id = list(range(num_mutations)) assert(len(mutation_id) == num_mutations) if type(mutation_type) is int: mutation_type = [mutation_type for _ in range(num_mutations)] assert(len(mutation_type) == num_mutations) if type(selection_coeff) is float: selection_coeff = [selection_coeff for _ in range(num_mutations)] assert(len(selection_coeff) == num_mutations) if type(population) is int: population = [population for _ in range(num_mutations)] assert(len(population) == num_mutations) if slim_time is None: ## This may *not* make sense because we have to round: # slim_time = [(-1) * int(tables.nodes.time[u]) for u in tables.mutations.node] slim_time = [0 for _ in range(num_mutations)] assert(len(slim_time) == num_mutations) mutation_metadata = [ {"mutation_list": [{"mutation_type": mt, "selection_coeff": sc, "subpopulation": pop, "slim_time": st, "nucleotide": -1 }] } for (mt, sc, pop, st) in zip(mutation_type, selection_coeff, population, slim_time)] ms = tables.mutations.metadata_schema tables.mutations.packset_metadata( [ms.encode_row(r) for r in mutation_metadata])
import attr import struct import msprime import tskit import kastore import json from collections import OrderedDict import warnings import numpy as np from ._version import * from .slim_metadata import * from .provenance import * from .util import * from .slim_metadata import _decode_mutation_pre_nucleotides, _set_metadata_schemas INDIVIDUAL_ALIVE = 2**16 INDIVIDUAL_REMEMBERED = 2**17 # no longer used but keep for a while INDIVIDUAL_FIRST_GEN = 2**18 # A nucleotide k in mutation metadata actually means # something that in reference_sequence is NUCLEOTIDES[k] NUCLEOTIDES = ['A', 'C', 'G', 'T'] def load(path, legacy_metadata=False): ''' Load the SLiM-compatible tree sequence found in the .trees file at ``path``. :param string path: The path to a .trees file. :param bool legacy_metadata: If True, then the resulting tree sequence will provide old-style metadata: as objects instead of dictionaries. This option is deprecated and will dissappear at some point in the future. ''' ts = SlimTreeSequence.load(path) return ts def load_tables(tables, **kwargs): ''' See :func:`SlimTreeSequence.load_tables`. :param TableCollection tables: A set of tables. ''' ts = SlimTreeSequence.load_tables(tables, **kwargs) return ts def annotate_defaults(ts, model_type, slim_generation, reference_sequence=None): ''' Takes a tree sequence (as produced by msprime, for instance), and adds in the information necessary for SLiM to use it as an initial state, filling in mostly default values. Returns a :class:`SlimTreeSequence`. :param TreeSequence ts: A :class:`TreeSequence`. :param string model_type: SLiM model type: either "WF" or "nonWF". :param int slim_generation: What generation number in SLiM correponds to ``time=0`` in the tree sequence. ''' tables = ts.dump_tables() annotate_defaults_tables(tables, model_type, slim_generation) return SlimTreeSequence.load_tables(tables, reference_sequence=reference_sequence) def annotate_defaults_tables(tables, model_type, slim_generation): ''' Does the work of :func:`annotate_defaults()`, but modifies the tables in place: so, takes tables as produced by ``msprime``, and makes them look like the tables as output by SLiM. See :func:`annotate_defaults` for details. ''' if (type(slim_generation) is not int) or (slim_generation < 1): raise ValueError("SLiM generation must be an integer and at least 1.") # set_nodes must come before set_populations if model_type == "WF": default_ages = -1 elif model_type == "nonWF": default_ages = 0 else: raise ValueError("Model type must be 'WF' or 'nonWF'") set_tree_sequence_metadata(tables, **default_slim_metadata['tree_sequence']['SLiM']) _set_nodes_individuals(tables, age=default_ages) _set_populations(tables) _set_sites_mutations(tables) class MetadataDictWrapper(dict): ''' A simple wrapper around metadata dicts that will throw an informative error message if ``md.X`` is used instead of ``md["X"]``, and (for mutation metadata) if ``md[k]`` is used instead of ``md["mutation_list"][k]``. ''' def __getattr__(self, name): if name in self.keys(): raise AttributeError( f"'dict' object has no attribute '{name}'. " "It looks like you're trying to use the legacy " "metadata interface: see " "`the documentation <https://pyslim.readthedocs.io/en/latest/metadata.html#legacy-metadata>`_ " "for how to switch over your script") else: raise AttributeError(f"'dict' object has no attribute '{name}'") def __getitem__(self, key): try: return super().__getitem__(key) except KeyError as e: if isinstance(key, int): msg = e.args[0] e.args = (f"{msg}: It looks like you're trying to use the legacy " "metadata interface: see " "`the documentation <https://pyslim.readthedocs.io/en/latest/metadata.html#legacy-metadata>`_ " "for how to switch over your script",) raise e class SlimTreeSequence(tskit.TreeSequence): ''' This is just like a :class:`tskit.TreeSequence`, with a few more properties and methods, including: - :attr:`.slim_generation` - the SLiM "generation" at the end of the simulation - :attr:`.reference_sequence` - if using a nucleotide model, the reference sequence - :attr:`.individual_locations` - numpy array of individual locations - :attr:`.individual_ages` - numpy array of individiual ages - :attr:`.individual_times` - numpy array of how long ago each individual was born - :attr:`.individual_populations` - numpy array of individual's populations All mutable properties of individuals (e.g., age) is as it was recorded during the individual's last time step alive (or at the end of the simulation, if they are still alive). You can create a :class:`.SlimTreeSequence` using one of - :meth:`.SlimTreeSequence.load_tables` :meth:`.SlimTreeSequence.load`, - :func:`.load`, or :func:`.load_tables`. :ivar slim_generation: The generation that the SLiM simulation was at upon writing; will be read from metadata if not provided. :ivar reference_sequence: None, or an string of length equal to the sequence length that gives the entire reference sequence for nucleotide models. :ivar legacy_metadata: Whether this tree sequence returns metadata in objects (as in older versions of pyslim) rather than dicts: see `the documentation <https://pyslim.readthedocs.io/en/latest/metadata.html#legacy-metadata>`_. This option is deprecated and will disappear at some point. :vartype slim_generation: int :vartype reference_sequence: string ''' def __init__(self, ts, reference_sequence=None, legacy_metadata=False): self.legacy_metadata = legacy_metadata if not (isinstance(ts.metadata, dict) and 'SLiM' in ts.metadata and ts.metadata['SLiM']['file_version'] == slim_file_version): tables = ts.dump_tables() if not (isinstance(tables.metadata, dict) and 'SLiM' in tables.metadata): _set_metadata_from_provenance(tables) if tables.metadata['SLiM']['file_version'] != slim_file_version: _upgrade_old_tables(tables) # cannot assign directly to keys of metadata md = tables.metadata md['SLiM']['file_version'] = slim_file_version tables.metadata = md ts = tables.tree_sequence() slim_generation = ts.metadata['SLiM']['generation'] self.model_type = ts.metadata['SLiM']['model_type'] super().__init__(ts._ll_tree_sequence) self.slim_generation = slim_generation self.reference_sequence = reference_sequence # pre-extract individual metadata self.individual_locations = ts.tables.individuals.location self.individual_locations.shape = (int(len(self.individual_locations)/3), 3) self.individual_ages = np.zeros(ts.num_individuals, dtype='int') if self.model_type != "WF": self.individual_ages = np.fromiter(map(lambda ind: ind.metadata['age'], ts.individuals()), dtype='int64') self.individual_times = np.zeros(ts.num_individuals) self.individual_populations = np.repeat(np.int32(-1), ts.num_individuals) if not np.all(unique_labels_by_group(ts.tables.nodes.individual, ts.tables.nodes.population)): raise ValueError("Individual has nodes from more than one population.") if not np.all(unique_labels_by_group(ts.tables.nodes.individual, ts.tables.nodes.time)): raise ValueError("Individual has nodes from more than one time.") has_indiv = (ts.tables.nodes.individual >= 0) which_indiv = ts.tables.nodes.individual[has_indiv] # if we did not do the sanity check above then an individual with nodes in more than one pop # would get the pop of their last node in the list self.individual_populations[which_indiv] = ts.tables.nodes.population[has_indiv] self.individual_times[which_indiv] = ts.tables.nodes.time[has_indiv] @classmethod def load(cls, path, legacy_metadata=False): ''' Load a :class:`SlimTreeSequence` from a .trees file on disk. :param string path: The path to a .trees file. :rtype SlimTreeSequence: ''' ts = tskit.load(path) # extract the reference sequence from the kastore kas = kastore.load(path) if 'reference_sequence/data' in kas: int_rs = kas['reference_sequence/data'] reference_sequence = int_rs.tostring().decode('ascii') else: reference_sequence = None return cls(ts, reference_sequence=reference_sequence, legacy_metadata=legacy_metadata) @classmethod def load_tables(cls, tables, **kwargs): ''' Creates the :class:`SlimTreeSequence` defined by the tables. :param TableCollection tables: A set of tables, as produced by SLiM or by annotate_defaults(). :param TableCollection reference_sequence: An optional string of ACGT giving the reference sequence. :rtype SlimTreeSequence: ''' # a roundabout way to copy the tables ts = tables.tree_sequence() return cls(ts, **kwargs) def dump(self, path, **kwargs): ''' Dumps the tree sequence to the path specified. This is mostly just a wrapper for tskit.TreeSequence.dump(), but also writes out the reference sequence. :param str path: The file path to write the TreeSequence to. :param kwargs: Additional keyword args to pass to tskit.TreeSequence.dump ''' super(SlimTreeSequence, self).dump(path, **kwargs) if self.reference_sequence is not None: # to convert to a kastore store we need to reload from a file, # and for it to be mutable we need to make it a dict kas = dict(kastore.load(path)) kas['reference_sequence/data'] = np.frombuffer(self.reference_sequence.encode(), dtype=np.int8) kastore.dump(kas, path) def simplify(self, *args, **kwargs): ''' This is a wrapper for :meth:`tskit.TreeSequence.simplify`. The only difference is that this method returns the derived class :class:`.SlimTreeSequence`. If you have not yet recapitated your SlimTreeSequence, you probably want to pass ``keep_input_roots=True``, so that recapitation is possible in the future. :rtype SlimTreeSequence: ''' sts = super(SlimTreeSequence, self).simplify(*args, **kwargs) if (type(sts) == tuple): ret = (SlimTreeSequence(sts[0]), sts[1]) ret[0].reference_sequence = self.reference_sequence else: ret = SlimTreeSequence(sts) ret.reference_sequence = self.reference_sequence return ret def population(self, id_): ''' Returns the population whose ID is given by `id_`, as documented in :meth:`tskit.TreeSequence.population`, but with additional attributes:: slim_id, selfing_fraction, female_cloning_fraction, male_cloning_fraction, sex_ratio, bounds_x0, bounds_x1, bounds_y0, bounds_y1, bounds_z0, bounds_z1, migration_records. These are all recorded by SLiM in the metadata. Note that SLiM populations are usually indexed starting from 1, but in tskit from zero, so there may be populations (e.g., with id_=0) that have no metadata and are not used by SLiM. :param int id_: The ID of the population (i.e., its index). ''' pop = super(SlimTreeSequence, self).population(id_) if self.legacy_metadata: try: pop.metadata = PopulationMetadata.fromdict(pop.metadata) except: pass else: if pop.metadata is not None: pop.metadata = MetadataDictWrapper(pop.metadata) return pop def individual(self, id_): ''' Returns the individual whose ID is given by `id_`, as documented in :meth:`tskit.TreeSequence.individual`, but with additional attributes:: time, pedigree_id, age, slim_population, sex, slim_flags. The `time` and `population` properties are extracted from the nodes, and an error will be thrown if the individual's nodes derive from more than one population or more than one time. :param int id_: The ID of the individual (i.e., its index). ''' ind = super(SlimTreeSequence, self).individual(id_) ind.population = self.individual_populations[id_] ind.time = self.individual_times[id_] if self.legacy_metadata: try: ind.metadata = IndividualMetadata.fromdict(ind.metadata) except: pass else: ind.metadata = MetadataDictWrapper(ind.metadata) return ind def node(self, id_): ''' Returns the node whose ID is given by `id_`, as documented in :meth:`tskit.TreeSequence.node`, but with additional attributes:: slim_id, is_null, genome_type. These are all recorded by SLiM in the metadata. :param int id_: The ID of the node (i.e., its index). ''' node = super(SlimTreeSequence, self).node(id_) if self.legacy_metadata: try: node.metadata = NodeMetadata.fromdict(node.metadata) except: pass else: if node.metadata is not None: node.metadata = MetadataDictWrapper(node.metadata) return node def mutation(self, id_): ''' Returns the mutation whose ID is given by `id_`, as documented in :meth:`tskit.TreeSequence.mutation`, but with additional attributes:: mutation_type, selection_coeff, population, slim_time, nucleotide. These are all recorded by SLiM in the metadata. :param int id_: The ID of the mutation (i.e., its index). ''' mut = super(SlimTreeSequence, self).mutation(id_) if self.legacy_metadata: try: mut.metadata = [MutationMetadata.fromdict(x) for x in mut.metadata['mutation_list']] except: pass else: mut.metadata = MetadataDictWrapper(mut.metadata) return mut def recapitate(self, recombination_rate=None, population_configurations=None, recombination_map=None, **kwargs): ''' Returns a "recapitated" tree sequence, by using msprime to run a coalescent simulation from the "top" of this tree sequence, i.e., allowing any uncoalesced lineages to coalesce. To allow recapitation to be done correctly, the nodes of the first generation of the SLiM simulation from whom all samples inherit are still present in the tree sequence, but are not marked as samples. If you simplify the tree sequence before recapitating you must ensure these are not removed, which you do by passing the argument ``keep_input_roots=True`` to :meth:`.simplify()`. Note that ``Ne`` is not set automatically, so defaults to ``1.0``; you probably want to set it explicitly. Similarly, migration is not set up automatically, so that if there are uncoalesced lineages in more than one population, you will need to pass in a migration matrix to allow coalescence. In both cases, remember that population IDs in ``tskit`` begin with 0, so that if your SLiM simulation has populations ``p1`` and ``p2``, then the tree sequence will have three populations (but with no nodes assigned to population 0), so that migration rate of 1.0 between ``p1`` and ``p2`` needs a migration matrix of:: [[0.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 1.0, 0.0]] In general, all defaults are whatever the defaults of ``msprime.simulate`` are; this includes recombination rate, so that if neither ``recombination_rate`` or a ``recombination_map`` are provided, there will be *no* recombination. However, if ``recombination_rate`` *is* provided, then recapitation will use a constant rate of recombination on a discretized map -- in other words, recombinations in the coalescent portion of the simulation will only occur at integer locations, just as in SLiM. If you do not want this to happen, you need to construct a ``recombination_map`` explicitly. :param float recombination_rate: A (constant) recombination rate, in units of crossovers per nucleotide per unit of time. :param list population_configurations: See :meth:`msprime.simulate` for this argument; if not provided, each population will have zero growth rate and the same effective population size. :type recombination_map: :class`msprime.RecombinationMap` :param recombination_map: The recombination map, or None, if recombination_rate is specified. :param dict kwargs: Any other arguments to :meth:`msprime.simulate`. ''' if "keep_first_generation" in kwargs: raise ValueError("The keep_first_generation argument is deprecated:" "the FIRST_GEN flag is no longer used.") # toggle for hacks below to deal with old msprime discrete_msprime = hasattr(msprime, "RateMap") if recombination_rate is not None: if recombination_map is not None: raise ValueError("Cannot specify length/recombination_rate along with a recombination map") if discrete_msprime: recombination_map = msprime.RecombinationMap(positions = [0.0, self.sequence_length], rates = [recombination_rate, 0.0]) else: recombination_map = msprime.RecombinationMap(positions = [0.0, self.sequence_length], rates = [recombination_rate, 0.0], num_loci = int(self.sequence_length)) if discrete_msprime and ('discrete_genome' not in kwargs): kwargs['discrete_genome'] = True if population_configurations is None: population_configurations = [msprime.PopulationConfiguration() for _ in range(self.num_populations)] recap = msprime.simulate( from_ts = self, population_configurations = population_configurations, recombination_map = recombination_map, start_time = self.slim_generation, **kwargs) # HACK to deal with older msprime that doesn't retain metadata # by copying over the metadata if recap.metadata == b'': tables = recap.tables tables.metadata = self._ll_tree_sequence.get_metadata() tables.metadata_schema = self.metadata_schema _set_metadata_schemas(tables) recap = tables.tree_sequence() return SlimTreeSequence(recap, reference_sequence=self.reference_sequence) def mutation_at(self, node, position, time=None): ''' Finds the mutation present in the genome of ``node`` at ``position``, returning -1 if there is no such mutation recorded in the tree sequence. Warning: if ``node`` is not actually in the tree sequence (e.g., not ancestral to any samples) at ``position``, then this function will return -1, possibly erroneously. If `time` is provided, returns the last mutation at ``position`` inherited by ``node`` that occurred at or before ``time`` ago. :param int node: The index of a node in the tree sequence. :param float position: A position along the genome. :param int time: The time ago that we want the nucleotide, or None, in which case the ``time`` of ``node`` is used. :returns: Index of the mutation in question, or -1 if none. ''' if position < 0 or position >= self.sequence_length: raise ValueError("Position {} not valid.".format(position)) if node < 0 or node >= self.num_nodes: raise ValueError("Node {} not valid.".format(node)) if time is None: time = self.node(node).time tree = self.at(position) site_pos = self.tables.sites.position out = tskit.NULL if position in site_pos: site_index = np.where(site_pos == position)[0][0] site = self.site(site_index) mut_nodes = [] # look for only mutations that occurred before `time` # not strictly necessary if time was None for mut in site.mutations: if mut.time >= time: mut_nodes.append(mut.node) n = node while n > -1 and n not in mut_nodes: n = tree.parent(n) if n >= 0: # do careful error checking here for mut in site.mutations: if mut.node == n: assert(out == tskit.NULL or out == mut.parent) out = mut.id return out def nucleotide_at(self, node, position, time=None): ''' Finds the nucleotide present in the genome of ``node`` at ``position``. Warning: if ``node`` is not actually in the tree sequence (e.g., not ancestral to any samples) at ``position``, then this function will return the reference sequence nucleotide, possibly erroneously. If `time` is provided, returns the last nucletide produced by a mutation at ``position`` inherited by ``node`` that occurred at or before ``time`` ago. :param int node: The index of a node in the tree sequence. :param float position: A position along the genome. :param int time: The time ago that we want the nucleotide, or None, in which case the ``time`` of ``node`` is used. :returns: Index of the nucleotide in ``NUCLEOTIDES`` (0=A, 1=C, 2=G, 3=T). ''' if self.reference_sequence is None: raise ValueError("This tree sequence has no reference sequence.") mut_id = self.mutation_at(node, position, time) if mut_id == tskit.NULL: out = NUCLEOTIDES.index(self.reference_sequence[int(position)]) else: mut = self.mutation(mut_id) k = np.argmax([u["slim_time"] for u in mut.metadata["mutation_list"]]) out = mut.metadata["mutation_list"][k]["nucleotide"] return out @property def slim_provenance(self): ''' Returns model type, slim generation, and remembered node count from the last entry in the provenance table that is tagged with "program"="SLiM". NOTE: you probably want to use the ``.metadata`` property instead. :rtype ProvenanceMetadata: ''' warnings.warn("This is deprecated: get information from " "ts.metadata['SLiM'] instead.", DeprecationWarning) return get_provenance(self, only_last=True) @property def slim_provenances(self): ''' Returns model type, slim generation, and remembered node count from *all* entries in the provenance table that is tagged with "program"="SLiM" :rtype ProvenanceMetadata: ''' return get_provenance(self, only_last=False) def _mark_first_generation(self): ''' Mark all 'first generation' individuals' nodes as samples, and return the corresponding tree sequence. DEPRECATED ''' tables = self.dump_tables() first_gen_nodes = ((tables.nodes.individual > 0) & ((tables.individuals.flags[tables.nodes.individual] & INDIVIDUAL_FIRST_GEN) > 0)) if sum(first_gen_nodes) == 0: warnings.warn("Tree sequence does not have the initial generation; " + " did you simplify it after output from SLiM?") flags = tables.nodes.flags flags[first_gen_nodes] = (flags[first_gen_nodes] | tskit.NODE_IS_SAMPLE) tables.nodes.set_columns(flags=flags, population=tables.nodes.population, individual=tables.nodes.individual, time=tables.nodes.time, metadata=tables.nodes.metadata, metadata_offset=tables.nodes.metadata_offset) ts = load_tables(tables) ts.reference_sequence = self.reference_sequence return ts def individuals_alive_at(self, time, stage='late', remembered_stage=None): """ Returns an array giving the IDs of all individuals that are known to be alive at the given time ago. This is determined using their birth time ago (given by their `time` attribute) and, for nonWF models, their `age` attribute (which is equal to their age at the last time they were Remembered). See also :meth:`.individual_ages_at`. In WF models, birth occurs after "early()", so that individuals are only alive during "late()" for the time step when they have age zero, while in nonWF models, birth occurs before "early()", so they are alive for both stages. In both WF and nonWF models, mortality occurs between "early()" and "late()", so that individuals are last alive during the "early()" stage of the time step of their final age, and if individuals are alive during "late()" they will also be alive during "early()" of the next time step. This means it is important to know during which stage individuals were Remembered - for instance, if the call to sim.treeSeqRememberIndividuals() was made during "early()" of a given time step, then those individuals might not have survived until "late()" of that time step. Since SLiM does not record the stage at which individuals were Remembered, you can specify this by setting ``remembered_stages``: it should be the stage during which *all* calls to sim.treeSeqRememberIndividuals, as well as to sim.treeSeqOutput(), were made. Note also that in nonWF models, birth occurs before "early()", so the possible parents in a given time step are those that are alive in "early()" and have age greater than zero, or, equivalently, are alive in "late()" during the previous time step. In WF models, birth occurs after "early()", so possible parents in a given time step are those that are alive during "early()" of that time step or are alive during "late()" of the previous time step. :param float time: The number of time steps ago. :param str stage: The stage in the SLiM life cycle that we are inquiring about (either "early" or "late"; defaults to "late"). :param str remembered_stage: The stage in the SLiM life cycle that individuals were Remembered during (defaults to the stage the tree sequence was recorded at, stored in metadata). """ if stage not in ("late", "early"): raise ValueError(f"Unknown stage '{stage}': " "should be either 'early' or 'late'.") if remembered_stage is None: remembered_stage = self.metadata['SLiM']['stage'] if remembered_stage not in ("late", "early"): raise ValueError(f"Unknown remembered_stage '{remembered_stage}': " "should be either 'early' or 'late'.") if remembered_stage != self.metadata['SLiM']['stage']: warnings.warn(f"Provided remembered_stage '{remembered_stage}' does not" " match the stage at which the tree sequence was saved" f" ('{self.metadata['SLiM']['stage']}'). This is not necessarily" " an error, but mismatched stages will lead to inconsistencies:" " make sure you know what you're doing.") # birth_time is the time ago that they were first alive in 'late' # in a nonWF model they are alive for the same time step's 'early' # but in a WF model the first 'early' they were alive for is one more recent birth_time = self.individual_times # birth_time - birth_offset is the first time ago they were alive # during stage 'stage' if stage == "early" and self.metadata['SLiM']['model_type'] == "WF": birth_offset = 1 else: birth_offset = 0 # ages is the number of complete life cycles they are known to have lived through, # and so individuals have lived through at least 'age + 1' of both stages. # In nonWF models, they live for one more 'early' than 'late', # but this is only reflected in their age if Remembered in 'early'. ages = self.individual_ages # ages + age_offset + 1 is the number of 'stage' stages they are known # to have lived through if (self.metadata['SLiM']['model_type'] == "WF" or stage == remembered_stage): age_offset = 0 else: if (remembered_stage == "early" and stage == "late"): age_offset = -1 else: age_offset = 1 # if adjusted age=0 then they are be alive at exactly one time step alive_bool = np.logical_and( birth_time >= time + birth_offset, birth_time - ages <= time + birth_offset + age_offset) return np.where(alive_bool)[0] def individual_ages_at(self, time, stage="late", remembered_stage="late"): """ Returns the *ages* of each individual at the corresponding time ago, which will be `nan` if the individual is either not born yet or dead. This is computed as the time ago the individual was born (found by the `time` associated with the the individual's nodes) minus the `time` argument; while "death" is inferred from the individual's `age`, recorded in metadata. These values are the same as what would be shown in SLiM during the corresponding time step and stage. Since age increments at the end of each time step, the age is the number of time steps ends the individual has lived through, so if they were born in time step `time`, then their age will be zero. In a WF model, this method does not provide any more information than does :meth:`.individuals_alive_at`, but for consistency, non-nan ages will be 0 in "late" and 1 in "early". See :meth:`.individuals_alive_at` for further discussion. :param float time: The reference time ago. :param str stage: The stage in the SLiM life cycle used to determine who is alive (either "early" or "late"; defaults to "late"). :param str remembered_stage: The stage in the SLiM life cycle that individuals were Remembered during. """ ages = np.repeat(np.nan, self.num_individuals) alive = self.individuals_alive_at(time, stage=stage, remembered_stage=remembered_stage) ages[alive] = self.individual_times[alive] - time return ages def first_generation_individuals(self): """ Returns the IDs of the individuals remembered as part of the first SLiM generation, as determined by their flags. .. warning:: This method is deprecated, because from SLiM version 3.5 the first generation individuals are no longer marked as such: only tree sequences from older versions of SLiM will have these individuals. """ return np.where(self.tables.individuals.flags & INDIVIDUAL_FIRST_GEN > 0)[0] def has_individual_parents(self): ''' Finds which individuals have both their parent individuals also present in the tree sequence, as far as we can tell. To do this, we return the IDs of individuals for which: - all edges terminating in that individual's nodes are in individuals, - each of the individual's nodes inherit from a single individual only, - those parental individuals were alive when the individual was born, - the parental individuals account for two whole genomes. This returns a boolean array indicating for each individual whether all these are true. See :meth:`.individuals_alive_at` for further discussion about how this is determined based on when the individuals were Remembered. :return: A boolean array of length equal to ``targets``. ''' edges = self.tables.edges nodes = self.tables.nodes edge_parent_indiv = nodes.individual[edges.parent] edge_child_indiv = nodes.individual[edges.child] # nodes whose parent nodes are all in the same individual unique_parent_nodes = unique_labels_by_group( edges.child, edge_parent_indiv, minlength=nodes.num_rows) unique_parent_edges = unique_parent_nodes[edges.child] # edges describing relationships between individuals indiv_edges = np.logical_and( np.logical_and(edge_parent_indiv != tskit.NULL, edge_child_indiv != tskit.NULL), unique_parent_edges) # individual edges where the parent was alive during "late" # of the time step before the child is born child_births = self.individual_times[edge_child_indiv[indiv_edges]] parent_births = self.individual_times[edge_parent_indiv[indiv_edges]] alive_edges = indiv_edges.copy() if self.metadata['SLiM']['model_type'] == "WF": alive_edges[indiv_edges] = (child_births + 1 == parent_births) else: parent_deaths = parent_births - self.individual_ages[edge_parent_indiv[indiv_edges]] alive_edges[indiv_edges] = (child_births + 1 >= parent_deaths) # total genome inherited from parents edge_spans = edges.right - edges.left parental_span = np.bincount(edge_child_indiv[alive_edges], weights=edge_spans[alive_edges], minlength=self.num_individuals) # we could also check for edges without individual parents terminating # in this individual, but this is unnecessary as the entire genome is # accounted for has_all_parents = (parental_span == 2 * self.sequence_length) return has_all_parents def _set_metadata_from_provenance(tables): # note this uses defaults on keys not present in provenance, # which prior to 0.5 was everything but generation and model_type values = default_slim_metadata['tree_sequence']['SLiM'] prov = None file_version = 'unknown' # use only the last SLiM provenance for p in tables.provenances: is_slim, this_file_version = slim_provenance_version(p) if is_slim: prov = p file_version = this_file_version values['file_version'] = file_version try: record = json.loads(prov.record) if file_version == "0.1": values['model_type'] = record['model_type'] values['generation'] = record['generation'] else: for k in values: if k in record['parameters']: values[k] = record['parameters'][k] values['generation'] = record['slim']['generation'] except: raise ValueError("Failed to obtain metadata from provenance.") set_tree_sequence_metadata(tables, **values) def _upgrade_old_tables(tables): with warnings.catch_warnings(): warnings.simplefilter("ignore") provenance = get_provenance(tables) file_version = provenance.file_version slim_generation = provenance.slim_generation warnings.warn("This is an version {} SLiM tree sequence.".format(file_version) + " When you write this out, " + "it will be converted to version {}.".format(slim_file_version)) if file_version == "0.1" or file_version == "0.2": # add empty nucleotide slots to metadata mut_bytes = tskit.unpack_bytes(tables.mutations.metadata, tables.mutations.metadata_offset) mut_metadata = [_decode_mutation_pre_nucleotides(md) for md in mut_bytes] metadata, metadata_offset = tskit.pack_bytes(mut_metadata) tables.mutations.set_columns( site=tables.mutations.site, node=tables.mutations.node, parent=tables.mutations.parent, derived_state=tables.mutations.derived_state, derived_state_offset=tables.mutations.derived_state_offset, metadata=metadata, metadata_offset=metadata_offset) if file_version == "0.1": # shift times node_times = tables.nodes.time + slim_generation tables.nodes.set_columns( flags=tables.nodes.flags, time=node_times, population=tables.nodes.population, individual=tables.nodes.individual, metadata=tables.nodes.metadata, metadata_offset=tables.nodes.metadata_offset) migration_times = tables.migrations.time + slim_generation tables.migrations.set_columns( left=tables.migrations.left, right=tables.migrations.right, node=tables.migrations.node, source=tables.migrations.source, dest=tables.migrations.dest, time=migration_times) new_record = { "schema_version": "1.0.0", "software": { "name": "pyslim", "version": pyslim_version, }, "parameters": { "command": ["_upgrade_old_tables"], "old_file_version": file_version, "new_file_version": slim_file_version, }, "environment": get_environment(), } tskit.validate_provenance(new_record) tables.provenances.add_row(json.dumps(new_record)) def _set_nodes_individuals( tables, node_ind=None, location=(0, 0, 0), age=0, ind_id=None, ind_population=None, ind_sex=INDIVIDUAL_TYPE_HERMAPHRODITE, ind_flags=INDIVIDUAL_ALIVE, slim_ind_flags=0, node_id=None, node_is_null=False, node_type=GENOME_TYPE_AUTOSOME): ''' Adds to a TableCollection the information relevant to individuals required for SLiM to load in a tree sequence, that is found in Node and Individual tables. This will replace any existing Individual table, and will replace any information already in the individual, metadata, and population columns of the Node table. This is designed to make it easy to assign default values: - (node_ind) the 2*j-th and (2*j+1)-st `sample` nodes to individual j - (location) individual locations to (0, 0, 0) - (age) individual age to 0 - (ind_id) SLiM individual pedigree IDs to sequential integers starting from 0 - (ind_population) individual populations to 0 - (node_id) SLiM genome IDs to sequential integers starting with samples from 0 - (node_is_null) genomes to be non-null - (node_type) genome type to 0 (= autosome) - (ind_flags) INDIVIDUAL_ALIVE If you have other situations, like non-alive "remembered" individuals, you will need to edit the tables by hand, afterwards. ''' samples = list(filter(lambda j: tables.nodes.flags[j] & tskit.NODE_IS_SAMPLE, range(tables.nodes.num_rows))) if (len(samples) % 2) != 0: raise ValueError("There must be an even number of sampled nodes,"\ + "since organisms are diploid.") if node_ind is None: node_ind = [tskit.NULL for _ in range(tables.nodes.num_rows)] for j, k in enumerate(samples): node_ind[j] = int(k/2) num_individuals = max(node_ind) + 1 num_nodes = tables.nodes.num_rows if type(location) is tuple: location = [location for _ in range(num_individuals)] assert(len(location) == num_individuals) if type(age) is int or type(age) is float: age = [age for _ in range(num_individuals)] assert(len(age) == num_individuals) if ind_id is None: ind_id = list(range(num_individuals)) assert(len(ind_id) == num_individuals) if type(ind_sex) is int: ind_sex = [ind_sex for _ in range(num_individuals)] assert(len(ind_sex) == num_individuals) if type(slim_ind_flags) is int: slim_ind_flags = [slim_ind_flags for _ in range(num_individuals)] assert(len(slim_ind_flags) == num_individuals) if type(ind_flags) is int: ind_flags = [ind_flags for _ in range(num_individuals)] assert(len(ind_flags) == num_individuals) if node_id is None: node_id = [-1 for _ in range(num_nodes)] for j, k in enumerate(list(samples) + sorted(list(set(range(num_nodes)) - set(samples)))): node_id[k] = j assert(len(node_id) == num_nodes) if type(node_is_null) is bool: node_is_null = [node_is_null for _ in range(num_nodes)] assert(len(node_is_null) == num_nodes) if type(node_type) is int: node_type = [node_type for _ in range(num_nodes)] assert(len(node_type) == tables.nodes.num_rows) if ind_population is None: # set the individual populations based on what's in the nodes ind_population = [tskit.NULL for _ in range(num_individuals)] for j, u in enumerate(node_ind): if u >= 0: ind_population[u] = tables.nodes.population[j] assert(len(ind_population) == num_individuals) # check for consistency: every individual has two nodes, and populations agree ploidy = [0 for _ in range(num_individuals)] for j in samples: u = node_ind[j] assert(u >= 0) ploidy[u] += 1 if tables.nodes.population[j] != ind_population[u]: raise ValueError("Inconsistent populations: nodes and individuals do not agree.") if any([p != 2 for p in ploidy]): raise ValueError("Not all individuals have two assigned nodes.") loc_vec, loc_off = tskit.pack_bytes(location) ims = tables.individuals.metadata_schema individual_metadata = [ {'pedigree_id': iid, 'age': a, 'subpopulation': int(pop), 'sex': sex, 'flags': f} for (iid, a, pop, sex, f) in zip(ind_id, age, ind_population, ind_sex, slim_ind_flags)] assert(len(individual_metadata) == num_individuals) individual_metadata, individual_metadata_offset = tskit.pack_bytes( [ims.encode_row(r) for r in individual_metadata]) tables.individuals.set_columns( flags=ind_flags, location=loc_vec, location_offset=loc_off, metadata=individual_metadata, metadata_offset=individual_metadata_offset) assert(tables.individuals.num_rows == num_individuals) node_metadata = [None for _ in range(num_nodes)] for j in samples: node_metadata[j] = {'slim_id': node_id[j], 'is_null': node_is_null[j], 'genome_type': node_type[j] } nms = tables.nodes.metadata_schema node_metadata, node_metadata_offset = tskit.pack_bytes( [nms.encode_row(r) for r in node_metadata]) tables.nodes.set_columns(flags=tables.nodes.flags, time=tables.nodes.time, population=tables.nodes.population, individual=node_ind, metadata=node_metadata, metadata_offset=node_metadata_offset) def _set_populations( tables, pop_id=None, selfing_fraction=0.0, female_cloning_fraction=0.0, male_cloning_fraction=0.0, sex_ratio=0.5, bounds_x0=0.0, bounds_x1=0.0, bounds_y0=0.0, bounds_y1=0.0, bounds_z0=0.0, bounds_z1=0.0, migration_records=None): ''' Adds to a TableCollection the information about populations required for SLiM to load a tree sequence. This will replace anything already in the Population table. ''' num_pops = max(tables.nodes.population) + 1 for ind in tables.individuals: md = ind.metadata if not (isinstance(md, dict) and 'subpopulation' in md): raise ValueError("Individuals do not have valid metadata: " "need to run set_nodes_individuals() first?") if md['subpopulation'] >= num_pops: raise ValueError("Bad population in individual metadata.") if pop_id is None: pop_id = list(range(num_pops)) assert(len(pop_id) == num_pops) if type(selfing_fraction) is float: selfing_fraction = [selfing_fraction for _ in range(num_pops)] assert(len(selfing_fraction) == num_pops) if type(female_cloning_fraction) is float: female_cloning_fraction = [female_cloning_fraction for _ in range(num_pops)] assert(len(female_cloning_fraction) == num_pops) if type(male_cloning_fraction) is float: male_cloning_fraction = [male_cloning_fraction for _ in range(num_pops)] assert(len(male_cloning_fraction) == num_pops) if type(sex_ratio) is float: sex_ratio = [sex_ratio for _ in range(num_pops)] assert(len(sex_ratio) == num_pops) if type(bounds_x0) is float: bounds_x0 = [bounds_x0 for _ in range(num_pops)] assert(len(bounds_x0) == num_pops) if type(bounds_x1) is float: bounds_x1 = [bounds_x1 for _ in range(num_pops)] assert(len(bounds_x1) == num_pops) if type(bounds_y0) is float: bounds_y0 = [bounds_y0 for _ in range(num_pops)] assert(len(bounds_y0) == num_pops) if type(bounds_y1) is float: bounds_y1 = [bounds_y1 for _ in range(num_pops)] assert(len(bounds_y1) == num_pops) if type(bounds_z0) is float: bounds_z0 = [bounds_z0 for _ in range(num_pops)] assert(len(bounds_z0) == num_pops) if type(bounds_z1) is float: bounds_z1 = [bounds_z1 for _ in range(num_pops)] assert(len(bounds_z1) == num_pops) if migration_records is None: migration_records = [[] for _ in range(num_pops)] assert(len(migration_records) == num_pops) for mrl in migration_records: for mr in mrl: assert(isinstance(mr, dict)) population_metadata = [ { "slim_id" : pid, "selfing_fraction" : sf, "female_cloning_fraction" : fcf, "male_cloning_fraction" : mcf, "sex_ratio" : sr, "bounds_x0" : x0, "bounds_x1" : x1, "bounds_y0" : y0, "bounds_y1" : y1, "bounds_z0" : z0, "bounds_z1" : z1, "migration_records" : mr, } for (pid, sf, fcf, mcf, sr, x0, x1, y0, y1, z0, z1, mr) in zip(pop_id, selfing_fraction, female_cloning_fraction, male_cloning_fraction, sex_ratio, bounds_x0, bounds_x1, bounds_y0, bounds_y1, bounds_z0, bounds_z1, migration_records)] ms = tables.populations.metadata_schema tables.populations.packset_metadata( [ms.encode_row(r) for r in population_metadata]) def _set_sites_mutations( tables, mutation_id=None, mutation_type=1, selection_coeff=0.0, population=tskit.NULL, slim_time=None): ''' Adds to a TableCollection the information relevant to mutations required for SLiM to load in a tree sequence. This means adding to the metadata column of the Mutation table, It will also - give SLiM IDs to each mutation - round Site positions to integer values - stack any mutations that end up at the same position as a result - replace ancestral states with "" This will replace any information already in the metadata or derived state columns of the Mutation table. ''' num_mutations = tables.mutations.num_rows if mutation_id is None: mutation_id = list(range(num_mutations)) assert(len(mutation_id) == num_mutations) if type(mutation_type) is int: mutation_type = [mutation_type for _ in range(num_mutations)] assert(len(mutation_type) == num_mutations) if type(selection_coeff) is float: selection_coeff = [selection_coeff for _ in range(num_mutations)] assert(len(selection_coeff) == num_mutations) if type(population) is int: population = [population for _ in range(num_mutations)] assert(len(population) == num_mutations) if slim_time is None: ## This may *not* make sense because we have to round: # slim_time = [(-1) * int(tables.nodes.time[u]) for u in tables.mutations.node] slim_time = [0 for _ in range(num_mutations)] assert(len(slim_time) == num_mutations) mutation_metadata = [ {"mutation_list": [{"mutation_type": mt, "selection_coeff": sc, "subpopulation": pop, "slim_time": st, "nucleotide": -1 }] } for (mt, sc, pop, st) in zip(mutation_type, selection_coeff, population, slim_time)] ms = tables.mutations.metadata_schema tables.mutations.packset_metadata( [ms.encode_row(r) for r in mutation_metadata])
import argparse import logging import os import signal from collections import defaultdict from datetime import datetime from time import time from typing import List import torch import torchaudio from torch import nn as nn from torch.optim import Adam from torch.utils.data import DataLoader from torchaudio.datasets.utils import bg_iterator from torchaudio.models._wavernn import _WaveRNN from datasets import collate_factory, split_process_ljspeech from losses import LongCrossEntropyLoss, MoLLoss from processing import LinearToMel, NormalizeDB from utils import MetricLogger, count_parameters, save_checkpoint def parse_args(): parser = argparse.ArgumentParser() parser.add_argument( "--workers", default=4, type=int, metavar="N", help="number of data loading workers", ) parser.add_argument( "--checkpoint", default="", type=str, metavar="PATH", help="path to latest checkpoint", ) parser.add_argument( "--epochs", default=8000, type=int, metavar="N", help="number of total epochs to run", ) parser.add_argument( "--start-epoch", default=0, type=int, metavar="N", help="manual epoch number" ) parser.add_argument( "--print-freq", default=10, type=int, metavar="N", help="print frequency in epochs", ) parser.add_argument( "--batch-size", default=256, type=int, metavar="N", help="mini-batch size" ) parser.add_argument( "--learning-rate", default=1e-4, type=float, metavar="LR", help="learning rate", ) parser.add_argument("--clip-grad", metavar="NORM", type=float, default=4.0) parser.add_argument( "--mulaw", default=True, action="store_true", help="if used, waveform is mulaw encoded", ) parser.add_argument( "--jit", default=False, action="store_true", help="if used, model is jitted" ) parser.add_argument( "--upsample-scales", default=[5, 5, 11], type=List[int], help="the list of upsample scales", ) parser.add_argument( "--n-bits", default=8, type=int, help="the bits of output waveform", ) parser.add_argument( "--sample-rate", default=22050, type=int, help="the rate of audio dimensions (samples per second)", ) parser.add_argument( "--hop-length", default=275, type=int, help="the number of samples between the starts of consecutive frames", ) parser.add_argument( "--win-length", default=1100, type=int, help="the length of the STFT window", ) parser.add_argument( "--f-min", default=40.0, type=float, help="the minimum frequency", ) parser.add_argument( "--min-level-db", default=-100, type=float, help="the minimum db value for spectrogam normalization", ) parser.add_argument( "--n-res-block", default=10, type=int, help="the number of ResBlock in stack", ) parser.add_argument( "--n-rnn", default=512, type=int, help="the dimension of RNN layer", ) parser.add_argument( "--n-fc", default=512, type=int, help="the dimension of fully connected layer", ) parser.add_argument( "--kernel-size", default=5, type=int, help="the number of kernel size in the first Conv1d layer", ) parser.add_argument( "--n-freq", default=80, type=int, help="the number of spectrogram bins to use", ) parser.add_argument( "--n-hidden-melresnet", default=128, type=int, help="the number of hidden dimensions of resblock in melresnet", ) parser.add_argument( "--n-output-melresnet", default=128, type=int, help="the output dimension of melresnet", ) parser.add_argument( "--n-fft", default=2048, type=int, help="the number of Fourier bins", ) parser.add_argument( "--loss", default="crossentropy", choices=["crossentropy", "mol"], type=str, help="the type of loss", ) parser.add_argument( "--seq-len-factor", default=5, type=int, help="the length of each waveform to process per batch = hop_length * seq_len_factor", ) parser.add_argument( "--val-ratio", default=0.1, type=float, help="the ratio of waveforms for validation", ) parser.add_argument( "--file-path", default="", type=str, help="the path of audio files", ) args = parser.parse_args() return args def train_one_epoch(model, criterion, optimizer, data_loader, device, epoch): model.train() sums = defaultdict(lambda: 0.0) start1 = time() metric = MetricLogger("train_iteration") metric["epoch"] = epoch for waveform, specgram, target in bg_iterator(data_loader, maxsize=2): start2 = time() waveform = waveform.to(device) specgram = specgram.to(device) target = target.to(device) output = model(waveform, specgram) output, target = output.squeeze(1), target.squeeze(1) loss = criterion(output, target) loss_item = loss.item() sums["loss"] += loss_item metric["loss"] = loss_item optimizer.zero_grad() loss.backward() if args.clip_grad > 0: gradient = torch.nn.utils.clip_grad_norm_( model.parameters(), args.clip_grad ) sums["gradient"] += gradient.item() metric["gradient"] = gradient.item() optimizer.step() metric["iteration"] = sums["iteration"] metric["time"] = time() - start2 metric() sums["iteration"] += 1 avg_loss = sums["loss"] / len(data_loader) metric = MetricLogger("train_epoch") metric["epoch"] = epoch metric["loss"] = sums["loss"] / len(data_loader) metric["gradient"] = avg_loss metric["time"] = time() - start1 metric() def validate(model, criterion, data_loader, device, epoch): with torch.no_grad(): model.eval() sums = defaultdict(lambda: 0.0) start = time() for waveform, specgram, target in bg_iterator(data_loader, maxsize=2): waveform = waveform.to(device) specgram = specgram.to(device) target = target.to(device) output = model(waveform, specgram) output, target = output.squeeze(1), target.squeeze(1) loss = criterion(output, target) sums["loss"] += loss.item() avg_loss = sums["loss"] / len(data_loader) metric = MetricLogger("validation") metric["epoch"] = epoch metric["loss"] = avg_loss metric["time"] = time() - start metric() return avg_loss def main(args): devices = ["cuda" if torch.cuda.is_available() else "cpu"] logging.info("Start time: {}".format(str(datetime.now()))) melkwargs = { "n_fft": args.n_fft, "power": 1, "hop_length": args.hop_length, "win_length": args.win_length, } transforms = torch.nn.Sequential( torchaudio.transforms.Spectrogram(**melkwargs), LinearToMel( sample_rate=args.sample_rate, n_fft=args.n_fft, n_mels=args.n_freq, fmin=args.f_min, ), NormalizeDB(min_level_db=args.min_level_db), ) train_dataset, val_dataset = split_process_ljspeech(args, transforms) loader_training_params = { "num_workers": args.workers, "pin_memory": False, "shuffle": True, "drop_last": False, } loader_validation_params = loader_training_params.copy() loader_validation_params["shuffle"] = False collate_fn = collate_factory(args) train_loader = DataLoader( train_dataset, batch_size=args.batch_size, collate_fn=collate_fn, **loader_training_params, ) val_loader = DataLoader( val_dataset, batch_size=args.batch_size, collate_fn=collate_fn, **loader_validation_params, ) n_classes = 2 ** args.n_bits if args.loss == "crossentropy" else 30 model = _WaveRNN( upsample_scales=args.upsample_scales, n_classes=n_classes, hop_length=args.hop_length, n_res_block=args.n_res_block, n_rnn=args.n_rnn, n_fc=args.n_fc, kernel_size=args.kernel_size, n_freq=args.n_freq, n_hidden=args.n_hidden_melresnet, n_output=args.n_output_melresnet, ) if args.jit: model = torch.jit.script(model) model = torch.nn.DataParallel(model) model = model.to(devices[0], non_blocking=True) n = count_parameters(model) logging.info(f"Number of parameters: {n}") # Optimizer optimizer_params = { "lr": args.learning_rate, } optimizer = Adam(model.parameters(), **optimizer_params) criterion = LongCrossEntropyLoss() if args.loss == "crossentropy" else MoLLoss() best_loss = 10.0 if args.checkpoint and os.path.isfile(args.checkpoint): logging.info(f"Checkpoint: loading '{args.checkpoint}'") checkpoint = torch.load(args.checkpoint) args.start_epoch = checkpoint["epoch"] best_loss = checkpoint["best_loss"] model.load_state_dict(checkpoint["state_dict"]) optimizer.load_state_dict(checkpoint["optimizer"]) logging.info( f"Checkpoint: loaded '{args.checkpoint}" at epoch {checkpoint["epoch"]}" ) else: logging.info("Checkpoint: not found") save_checkpoint( { "epoch": args.start_epoch, "state_dict": model.state_dict(), "best_loss": best_loss, "optimizer": optimizer.state_dict(), }, False, args.checkpoint, ) for epoch in range(args.start_epoch, args.epochs): train_one_epoch( model, criterion, optimizer, train_loader, devices[0], epoch, ) if not (epoch + 1) % args.print_freq or epoch == args.epochs - 1: sum_loss = validate(model, criterion, val_loader, devices[0], epoch) is_best = sum_loss < best_loss best_loss = min(sum_loss, best_loss) save_checkpoint( { "epoch": epoch + 1, "state_dict": model.state_dict(), "best_loss": best_loss, "optimizer": optimizer.state_dict(), }, is_best, args.checkpoint, ) logging.info(f"End time: {datetime.now()}") if __name__ == "__main__": logging.basicConfig(level=logging.INFO) args = parse_args() main(args)
import argparse import logging import os import signal from collections import defaultdict from datetime import datetime from time import time from typing import List import torch import torchaudio from torch import nn as nn from torch.optim import Adam from torch.utils.data import DataLoader from torchaudio.datasets.utils import bg_iterator from torchaudio.models._wavernn import _WaveRNN from datasets import collate_factory, split_process_ljspeech from losses import LongCrossEntropyLoss, MoLLoss from processing import LinearToMel, NormalizeDB from utils import MetricLogger, count_parameters, save_checkpoint def parse_args(): parser = argparse.ArgumentParser() parser.add_argument( "--workers", default=4, type=int, metavar="N", help="number of data loading workers", ) parser.add_argument( "--checkpoint", default="", type=str, metavar="PATH", help="path to latest checkpoint", ) parser.add_argument( "--epochs", default=8000, type=int, metavar="N", help="number of total epochs to run", ) parser.add_argument( "--start-epoch", default=0, type=int, metavar="N", help="manual epoch number" ) parser.add_argument( "--print-freq", default=10, type=int, metavar="N", help="print frequency in epochs", ) parser.add_argument( "--batch-size", default=256, type=int, metavar="N", help="mini-batch size" ) parser.add_argument( "--learning-rate", default=1e-4, type=float, metavar="LR", help="learning rate", ) parser.add_argument("--clip-grad", metavar="NORM", type=float, default=4.0) parser.add_argument( "--mulaw", default=True, action="store_true", help="if used, waveform is mulaw encoded", ) parser.add_argument( "--jit", default=False, action="store_true", help="if used, model is jitted" ) parser.add_argument( "--upsample-scales", default=[5, 5, 11], type=List[int], help="the list of upsample scales", ) parser.add_argument( "--n-bits", default=8, type=int, help="the bits of output waveform", ) parser.add_argument( "--sample-rate", default=22050, type=int, help="the rate of audio dimensions (samples per second)", ) parser.add_argument( "--hop-length", default=275, type=int, help="the number of samples between the starts of consecutive frames", ) parser.add_argument( "--win-length", default=1100, type=int, help="the length of the STFT window", ) parser.add_argument( "--f-min", default=40.0, type=float, help="the minimum frequency", ) parser.add_argument( "--min-level-db", default=-100, type=float, help="the minimum db value for spectrogam normalization", ) parser.add_argument( "--n-res-block", default=10, type=int, help="the number of ResBlock in stack", ) parser.add_argument( "--n-rnn", default=512, type=int, help="the dimension of RNN layer", ) parser.add_argument( "--n-fc", default=512, type=int, help="the dimension of fully connected layer", ) parser.add_argument( "--kernel-size", default=5, type=int, help="the number of kernel size in the first Conv1d layer", ) parser.add_argument( "--n-freq", default=80, type=int, help="the number of spectrogram bins to use", ) parser.add_argument( "--n-hidden-melresnet", default=128, type=int, help="the number of hidden dimensions of resblock in melresnet", ) parser.add_argument( "--n-output-melresnet", default=128, type=int, help="the output dimension of melresnet", ) parser.add_argument( "--n-fft", default=2048, type=int, help="the number of Fourier bins", ) parser.add_argument( "--loss", default="crossentropy", choices=["crossentropy", "mol"], type=str, help="the type of loss", ) parser.add_argument( "--seq-len-factor", default=5, type=int, help="the length of each waveform to process per batch = hop_length * seq_len_factor", ) parser.add_argument( "--val-ratio", default=0.1, type=float, help="the ratio of waveforms for validation", ) parser.add_argument( "--file-path", default="", type=str, help="the path of audio files", ) args = parser.parse_args() return args def train_one_epoch(model, criterion, optimizer, data_loader, device, epoch): model.train() sums = defaultdict(lambda: 0.0) start1 = time() metric = MetricLogger("train_iteration") metric["epoch"] = epoch for waveform, specgram, target in bg_iterator(data_loader, maxsize=2): start2 = time() waveform = waveform.to(device) specgram = specgram.to(device) target = target.to(device) output = model(waveform, specgram) output, target = output.squeeze(1), target.squeeze(1) loss = criterion(output, target) loss_item = loss.item() sums["loss"] += loss_item metric["loss"] = loss_item optimizer.zero_grad() loss.backward() if args.clip_grad > 0: gradient = torch.nn.utils.clip_grad_norm_( model.parameters(), args.clip_grad ) sums["gradient"] += gradient.item() metric["gradient"] = gradient.item() optimizer.step() metric["iteration"] = sums["iteration"] metric["time"] = time() - start2 metric() sums["iteration"] += 1 avg_loss = sums["loss"] / len(data_loader) metric = MetricLogger("train_epoch") metric["epoch"] = epoch metric["loss"] = sums["loss"] / len(data_loader) metric["gradient"] = avg_loss metric["time"] = time() - start1 metric() def validate(model, criterion, data_loader, device, epoch): with torch.no_grad(): model.eval() sums = defaultdict(lambda: 0.0) start = time() for waveform, specgram, target in bg_iterator(data_loader, maxsize=2): waveform = waveform.to(device) specgram = specgram.to(device) target = target.to(device) output = model(waveform, specgram) output, target = output.squeeze(1), target.squeeze(1) loss = criterion(output, target) sums["loss"] += loss.item() avg_loss = sums["loss"] / len(data_loader) metric = MetricLogger("validation") metric["epoch"] = epoch metric["loss"] = avg_loss metric["time"] = time() - start metric() return avg_loss def main(args): devices = ["cuda" if torch.cuda.is_available() else "cpu"] logging.info("Start time: {}".format(str(datetime.now()))) melkwargs = { "n_fft": args.n_fft, "power": 1, "hop_length": args.hop_length, "win_length": args.win_length, } transforms = torch.nn.Sequential( torchaudio.transforms.Spectrogram(**melkwargs), LinearToMel( sample_rate=args.sample_rate, n_fft=args.n_fft, n_mels=args.n_freq, fmin=args.f_min, ), NormalizeDB(min_level_db=args.min_level_db), ) train_dataset, val_dataset = split_process_ljspeech(args, transforms) loader_training_params = { "num_workers": args.workers, "pin_memory": False, "shuffle": True, "drop_last": False, } loader_validation_params = loader_training_params.copy() loader_validation_params["shuffle"] = False collate_fn = collate_factory(args) train_loader = DataLoader( train_dataset, batch_size=args.batch_size, collate_fn=collate_fn, **loader_training_params, ) val_loader = DataLoader( val_dataset, batch_size=args.batch_size, collate_fn=collate_fn, **loader_validation_params, ) n_classes = 2 ** args.n_bits if args.loss == "crossentropy" else 30 model = _WaveRNN( upsample_scales=args.upsample_scales, n_classes=n_classes, hop_length=args.hop_length, n_res_block=args.n_res_block, n_rnn=args.n_rnn, n_fc=args.n_fc, kernel_size=args.kernel_size, n_freq=args.n_freq, n_hidden=args.n_hidden_melresnet, n_output=args.n_output_melresnet, ) if args.jit: model = torch.jit.script(model) model = torch.nn.DataParallel(model) model = model.to(devices[0], non_blocking=True) n = count_parameters(model) logging.info(f"Number of parameters: {n}") # Optimizer optimizer_params = { "lr": args.learning_rate, } optimizer = Adam(model.parameters(), **optimizer_params) criterion = LongCrossEntropyLoss() if args.loss == "crossentropy" else MoLLoss() best_loss = 10.0 if args.checkpoint and os.path.isfile(args.checkpoint): logging.info(f"Checkpoint: loading '{args.checkpoint}'") checkpoint = torch.load(args.checkpoint) args.start_epoch = checkpoint["epoch"] best_loss = checkpoint["best_loss"] model.load_state_dict(checkpoint["state_dict"]) optimizer.load_state_dict(checkpoint["optimizer"]) logging.info( f"Checkpoint: loaded '{args.checkpoint}' at epoch {checkpoint['epoch']}" ) else: logging.info("Checkpoint: not found") save_checkpoint( { "epoch": args.start_epoch, "state_dict": model.state_dict(), "best_loss": best_loss, "optimizer": optimizer.state_dict(), }, False, args.checkpoint, ) for epoch in range(args.start_epoch, args.epochs): train_one_epoch( model, criterion, optimizer, train_loader, devices[0], epoch, ) if not (epoch + 1) % args.print_freq or epoch == args.epochs - 1: sum_loss = validate(model, criterion, val_loader, devices[0], epoch) is_best = sum_loss < best_loss best_loss = min(sum_loss, best_loss) save_checkpoint( { "epoch": epoch + 1, "state_dict": model.state_dict(), "best_loss": best_loss, "optimizer": optimizer.state_dict(), }, is_best, args.checkpoint, ) logging.info(f"End time: {datetime.now()}") if __name__ == "__main__": logging.basicConfig(level=logging.INFO) args = parse_args() main(args)
""" Test the code templates by rendering them for different parameter combinations and checking that the code runs without errors. """ import sys import os # Activate this in case we need to import some functions, e.g. from utils. # sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) from jinja2 import Environment, FileSystemLoader import pytest # import shutil def render_template(**kwargs): """Renders template (passing in kwargs) and returns Python code.""" env = Environment( loader=FileSystemLoader("templates"), trim_blocks=True, lstrip_blocks=True, ) template = env.get_template(f"image_classification_{kwargs["framework"]}.py.jinja") code = template.render(header=lambda x: "", notebook=False, **kwargs) return code def execute_code(code, tmp_path): """ Executes code in temporary working directory. This is required so logs and checkpoints are not saved in the repo. """ cwd = os.getcwd() os.chdir(tmp_path) # print("Execute code in:", os.getcwd()) try: exec(code, globals()) finally: os.chdir(cwd) # print("Back to:", os.getcwd()) @pytest.mark.parametrize( "model_func", ["sklearn.svm.SVC", "sklearn.linear_model.Perceptron"] ) @pytest.mark.parametrize("data_format", ["Numpy arrays", "Image files"]) @pytest.mark.parametrize("scale_mean_std", [True, False]) @pytest.mark.parametrize("visualization_tool", ["Not at all", "Tensorboard"]) def test_sklearn_code( model_func, data_format, scale_mean_std, visualization_tool, tmp_path ): code = render_template( framework="scikit-learn", model_func=model_func, data_format=data_format, resize_pixels=28, crop_pixels=28, scale_mean_std=scale_mean_std, visualization_tool=visualization_tool, ) # if data_format == "Image files": # copy some test data # shutil.copytree( # "tests/data/image-classification-data", tmp_path / "path/to/data/dir" # ) execute_code(code, tmp_path) @pytest.mark.parametrize("model_func", ["resnet18"]) @pytest.mark.parametrize("data_format", ["Numpy arrays", "Image files"]) @pytest.mark.parametrize("gpu", [True, False]) # this will only use GPU if available @pytest.mark.parametrize("checkpoint", [True, False]) @pytest.mark.parametrize("visualization_tool", ["Not at all", "Tensorboard"]) def test_pytorch_code( model_func, data_format, gpu, checkpoint, visualization_tool, tmp_path ): code = render_template( framework="PyTorch", model_func=model_func, pretrained=False, data_format=data_format, gpu=gpu, checkpoint=checkpoint, loss="CrossEntropyLoss", optimizer="Adam", lr=0.001, batch_size=128, num_epochs=1, print_every=1, visualization_tool=visualization_tool, ) # if data_format == "Image files": # copy some test data # shutil.copytree( # "tests/data/image-classification-data", tmp_path / "path/to/data/dir" # ) execute_code(code, tmp_path)
""" Test the code templates by rendering them for different parameter combinations and checking that the code runs without errors. """ import sys import os # Activate this in case we need to import some functions, e.g. from utils. # sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) from jinja2 import Environment, FileSystemLoader import pytest # import shutil def render_template(**kwargs): """Renders template (passing in kwargs) and returns Python code.""" env = Environment( loader=FileSystemLoader("templates"), trim_blocks=True, lstrip_blocks=True, ) template = env.get_template(f"image_classification_{kwargs['framework']}.py.jinja") code = template.render(header=lambda x: "", notebook=False, **kwargs) return code def execute_code(code, tmp_path): """ Executes code in temporary working directory. This is required so logs and checkpoints are not saved in the repo. """ cwd = os.getcwd() os.chdir(tmp_path) # print("Execute code in:", os.getcwd()) try: exec(code, globals()) finally: os.chdir(cwd) # print("Back to:", os.getcwd()) @pytest.mark.parametrize( "model_func", ["sklearn.svm.SVC", "sklearn.linear_model.Perceptron"] ) @pytest.mark.parametrize("data_format", ["Numpy arrays", "Image files"]) @pytest.mark.parametrize("scale_mean_std", [True, False]) @pytest.mark.parametrize("visualization_tool", ["Not at all", "Tensorboard"]) def test_sklearn_code( model_func, data_format, scale_mean_std, visualization_tool, tmp_path ): code = render_template( framework="scikit-learn", model_func=model_func, data_format=data_format, resize_pixels=28, crop_pixels=28, scale_mean_std=scale_mean_std, visualization_tool=visualization_tool, ) # if data_format == "Image files": # copy some test data # shutil.copytree( # "tests/data/image-classification-data", tmp_path / "path/to/data/dir" # ) execute_code(code, tmp_path) @pytest.mark.parametrize("model_func", ["resnet18"]) @pytest.mark.parametrize("data_format", ["Numpy arrays", "Image files"]) @pytest.mark.parametrize("gpu", [True, False]) # this will only use GPU if available @pytest.mark.parametrize("checkpoint", [True, False]) @pytest.mark.parametrize("visualization_tool", ["Not at all", "Tensorboard"]) def test_pytorch_code( model_func, data_format, gpu, checkpoint, visualization_tool, tmp_path ): code = render_template( framework="PyTorch", model_func=model_func, pretrained=False, data_format=data_format, gpu=gpu, checkpoint=checkpoint, loss="CrossEntropyLoss", optimizer="Adam", lr=0.001, batch_size=128, num_epochs=1, print_every=1, visualization_tool=visualization_tool, ) # if data_format == "Image files": # copy some test data # shutil.copytree( # "tests/data/image-classification-data", tmp_path / "path/to/data/dir" # ) execute_code(code, tmp_path)
#!/usr/bin/env python3 # vim: set syntax=python ts=4 : # # Copyright (c) 2018 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import os import contextlib import string import mmap import sys import re import subprocess import select import shutil import shlex import signal import threading import concurrent.futures from collections import OrderedDict import queue import time import csv import glob import concurrent import xml.etree.ElementTree as ET import logging from pathlib import Path from distutils.spawn import find_executable from colorama import Fore import pickle import platform import yaml import json from multiprocessing import Lock, Process, Value from typing import List try: # Use the C LibYAML parser if available, rather than the Python parser. # It's much faster. from yaml import CSafeLoader as SafeLoader from yaml import CDumper as Dumper except ImportError: from yaml import SafeLoader, Dumper try: import serial except ImportError: print("Install pyserial python module with pip to use --device-testing option.") try: from tabulate import tabulate except ImportError: print("Install tabulate python module with pip to use --device-testing option.") try: import psutil except ImportError: print("Install psutil python module with pip to run in Qemu.") try: import pty except ImportError as capture_error: if os.name == "nt": # "nt" means that program is running on Windows OS pass # "--device-serial-pty" option is not supported on Windows OS else: raise capture_error ZEPHYR_BASE = os.getenv("ZEPHYR_BASE") if not ZEPHYR_BASE: sys.exit("$ZEPHYR_BASE environment variable undefined") # This is needed to load edt.pickle files. sys.path.insert(0, os.path.join(ZEPHYR_BASE, "scripts", "dts", "python-devicetree", "src")) from devicetree import edtlib # pylint: disable=unused-import # Use this for internal comparisons; that's what canonicalization is # for. Don't use it when invoking other components of the build system # to avoid confusing and hard to trace inconsistencies in error messages # and logs, generated Makefiles, etc. compared to when users invoke these # components directly. # Note "normalization" is different from canonicalization, see os.path. canonical_zephyr_base = os.path.realpath(ZEPHYR_BASE) sys.path.insert(0, os.path.join(ZEPHYR_BASE, "scripts/")) import scl import expr_parser logger = logging.getLogger('twister') logger.setLevel(logging.DEBUG) class ExecutionCounter(object): def __init__(self, total=0): self._done = Value('i', 0) self._passed = Value('i', 0) self._skipped_configs = Value('i', 0) self._skipped_runtime = Value('i', 0) self._skipped_cases = Value('i', 0) self._error = Value('i', 0) self._failed = Value('i', 0) self._total = Value('i', total) self._cases = Value('i', 0) self.lock = Lock() @property def cases(self): with self._cases.get_lock(): return self._cases.value @cases.setter def cases(self, value): with self._cases.get_lock(): self._cases.value = value @property def skipped_cases(self): with self._skipped_cases.get_lock(): return self._skipped_cases.value @skipped_cases.setter def skipped_cases(self, value): with self._skipped_cases.get_lock(): self._skipped_cases.value = value @property def error(self): with self._error.get_lock(): return self._error.value @error.setter def error(self, value): with self._error.get_lock(): self._error.value = value @property def done(self): with self._done.get_lock(): return self._done.value @done.setter def done(self, value): with self._done.get_lock(): self._done.value = value @property def passed(self): with self._passed.get_lock(): return self._passed.value @passed.setter def passed(self, value): with self._passed.get_lock(): self._passed.value = value @property def skipped_configs(self): with self._skipped_configs.get_lock(): return self._skipped_configs.value @skipped_configs.setter def skipped_configs(self, value): with self._skipped_configs.get_lock(): self._skipped_configs.value = value @property def skipped_runtime(self): with self._skipped_runtime.get_lock(): return self._skipped_runtime.value @skipped_runtime.setter def skipped_runtime(self, value): with self._skipped_runtime.get_lock(): self._skipped_runtime.value = value @property def failed(self): with self._failed.get_lock(): return self._failed.value @failed.setter def failed(self, value): with self._failed.get_lock(): self._failed.value = value @property def total(self): with self._total.get_lock(): return self._total.value class CMakeCacheEntry: '''Represents a CMake cache entry. This class understands the type system in a CMakeCache.txt, and converts the following cache types to Python types: Cache Type Python type ---------- ------------------------------------------- FILEPATH str PATH str STRING str OR list of str (if ';' is in the value) BOOL bool INTERNAL str OR list of str (if ';' is in the value) ---------- ------------------------------------------- ''' # Regular expression for a cache entry. # # CMake variable names can include escape characters, allowing a # wider set of names than is easy to match with a regular # expression. To be permissive here, use a non-greedy match up to # the first colon (':'). This breaks if the variable name has a # colon inside, but it's good enough. CACHE_ENTRY = re.compile( r'''(?P<name>.*?) # name :(?P<type>FILEPATH|PATH|STRING|BOOL|INTERNAL) # type =(?P<value>.*) # value ''', re.X) @classmethod def _to_bool(cls, val): # Convert a CMake BOOL string into a Python bool. # # "True if the constant is 1, ON, YES, TRUE, Y, or a # non-zero number. False if the constant is 0, OFF, NO, # FALSE, N, IGNORE, NOTFOUND, the empty string, or ends in # the suffix -NOTFOUND. Named boolean constants are # case-insensitive. If the argument is not one of these # constants, it is treated as a variable." # # https://cmake.org/cmake/help/v3.0/command/if.html val = val.upper() if val in ('ON', 'YES', 'TRUE', 'Y'): return 1 elif val in ('OFF', 'NO', 'FALSE', 'N', 'IGNORE', 'NOTFOUND', ''): return 0 elif val.endswith('-NOTFOUND'): return 0 else: try: v = int(val) return v != 0 except ValueError as exc: raise ValueError('invalid bool {}'.format(val)) from exc @classmethod def from_line(cls, line, line_no): # Comments can only occur at the beginning of a line. # (The value of an entry could contain a comment character). if line.startswith('//') or line.startswith('#'): return None # Whitespace-only lines do not contain cache entries. if not line.strip(): return None m = cls.CACHE_ENTRY.match(line) if not m: return None name, type_, value = (m.group(g) for g in ('name', 'type', 'value')) if type_ == 'BOOL': try: value = cls._to_bool(value) except ValueError as exc: args = exc.args + ('on line {}: {}'.format(line_no, line),) raise ValueError(args) from exc elif type_ in ['STRING', 'INTERNAL']: # If the value is a CMake list (i.e. is a string which # contains a ';'), convert to a Python list. if ';' in value: value = value.split(';') return CMakeCacheEntry(name, value) def __init__(self, name, value): self.name = name self.value = value def __str__(self): fmt = 'CMakeCacheEntry(name={}, value={})' return fmt.format(self.name, self.value) class CMakeCache: '''Parses and represents a CMake cache file.''' @staticmethod def from_file(cache_file): return CMakeCache(cache_file) def __init__(self, cache_file): self.cache_file = cache_file self.load(cache_file) def load(self, cache_file): entries = [] with open(cache_file, 'r') as cache: for line_no, line in enumerate(cache): entry = CMakeCacheEntry.from_line(line, line_no) if entry: entries.append(entry) self._entries = OrderedDict((e.name, e) for e in entries) def get(self, name, default=None): entry = self._entries.get(name) if entry is not None: return entry.value else: return default def get_list(self, name, default=None): if default is None: default = [] entry = self._entries.get(name) if entry is not None: value = entry.value if isinstance(value, list): return value elif isinstance(value, str): return [value] if value else [] else: msg = 'invalid value {} type {}' raise RuntimeError(msg.format(value, type(value))) else: return default def __contains__(self, name): return name in self._entries def __getitem__(self, name): return self._entries[name].value def __setitem__(self, name, entry): if not isinstance(entry, CMakeCacheEntry): msg = 'improper type {} for value {}, expecting CMakeCacheEntry' raise TypeError(msg.format(type(entry), entry)) self._entries[name] = entry def __delitem__(self, name): del self._entries[name] def __iter__(self): return iter(self._entries.values()) class TwisterException(Exception): pass class TwisterRuntimeError(TwisterException): pass class ConfigurationError(TwisterException): def __init__(self, cfile, message): TwisterException.__init__(self, cfile + ": " + message) class BuildError(TwisterException): pass class ExecutionError(TwisterException): pass class HarnessImporter: def __init__(self, name): sys.path.insert(0, os.path.join(ZEPHYR_BASE, "scripts/pylib/twister")) module = __import__("harness") if name: my_class = getattr(module, name) else: my_class = getattr(module, "Test") self.instance = my_class() class Handler: def __init__(self, instance, type_str="build"): """Constructor """ self.state = "waiting" self.run = False self.duration = 0 self.type_str = type_str self.binary = None self.pid_fn = None self.call_make_run = False self.name = instance.name self.instance = instance self.timeout = instance.testcase.timeout self.sourcedir = instance.testcase.source_dir self.build_dir = instance.build_dir self.log = os.path.join(self.build_dir, "handler.log") self.returncode = 0 self.set_state("running", self.duration) self.generator = None self.generator_cmd = None self.args = [] self.terminated = False def set_state(self, state, duration): self.state = state self.duration = duration def get_state(self): ret = (self.state, self.duration) return ret def record(self, harness): if harness.recording: filename = os.path.join(self.build_dir, "recording.csv") with open(filename, "at") as csvfile: cw = csv.writer(csvfile, harness.fieldnames, lineterminator=os.linesep) cw.writerow(harness.fieldnames) for instance in harness.recording: cw.writerow(instance) def terminate(self, proc): # encapsulate terminate functionality so we do it consistently where ever # we might want to terminate the proc. We need try_kill_process_by_pid # because of both how newer ninja (1.6.0 or greater) and .NET / renode # work. Newer ninja's don't seem to pass SIGTERM down to the children # so we need to use try_kill_process_by_pid. for child in psutil.Process(proc.pid).children(recursive=True): try: os.kill(child.pid, signal.SIGTERM) except ProcessLookupError: pass proc.terminate() # sleep for a while before attempting to kill time.sleep(0.5) proc.kill() self.terminated = True def add_missing_testscases(self, harness): """ If testsuite was broken by some error (e.g. timeout) it is necessary to add information about next testcases, which were not be performed due to this error. """ for c in self.instance.testcase.cases: if c not in harness.tests: harness.tests[c] = "BLOCK" def _set_skip_reason(self, harness_state): """ If testcase written in ztest framework is skipped by "ztest_test_skip()" function, then such testcase is marked in instance.results dict as "SKIP", but reason of this sipping still "Unknown". This method pick up this situation and complete the instance.reason properly. """ harness_state_pass = "passed" harness_testcase_result_skip = "SKIP" instance_reason_unknown = "Unknown" if harness_state == harness_state_pass and \ self.instance.reason == instance_reason_unknown and \ harness_testcase_result_skip in self.instance.results.values(): self.instance.reason = "ztest skip" class BinaryHandler(Handler): def __init__(self, instance, type_str): """Constructor @param instance Test Instance """ super().__init__(instance, type_str) self.call_west_flash = False # Tool options self.valgrind = False self.lsan = False self.asan = False self.ubsan = False self.coverage = False def try_kill_process_by_pid(self): if self.pid_fn: pid = int(open(self.pid_fn).read()) os.unlink(self.pid_fn) self.pid_fn = None # clear so we don't try to kill the binary twice try: os.kill(pid, signal.SIGTERM) except ProcessLookupError: pass def _output_reader(self, proc): self.line = proc.stdout.readline() def _output_handler(self, proc, harness): if harness.is_pytest: harness.handle(None) return log_out_fp = open(self.log, "wt") timeout_extended = False timeout_time = time.time() + self.timeout while True: this_timeout = timeout_time - time.time() if this_timeout < 0: break reader_t = threading.Thread(target=self._output_reader, args=(proc,), daemon=True) reader_t.start() reader_t.join(this_timeout) if not reader_t.is_alive(): line = self.line logger.debug("OUTPUT: {0}".format(line.decode('utf-8').rstrip())) log_out_fp.write(line.decode('utf-8')) log_out_fp.flush() harness.handle(line.decode('utf-8').rstrip()) if harness.state: if not timeout_extended or harness.capture_coverage: timeout_extended = True if harness.capture_coverage: timeout_time = time.time() + 30 else: timeout_time = time.time() + 2 else: reader_t.join(0) break try: # POSIX arch based ztests end on their own, # so let's give it up to 100ms to do so proc.wait(0.1) except subprocess.TimeoutExpired: self.terminate(proc) log_out_fp.close() def handle(self): harness_name = self.instance.testcase.harness.capitalize() harness_import = HarnessImporter(harness_name) harness = harness_import.instance harness.configure(self.instance) if self.call_make_run: command = [self.generator_cmd, "run"] elif self.call_west_flash: command = ["west", "flash", "--skip-rebuild", "-d", self.build_dir] else: command = [self.binary] run_valgrind = False if self.valgrind and shutil.which("valgrind"): command = ["valgrind", "--error-exitcode=2", "--leak-check=full", "--suppressions=" + ZEPHYR_BASE + "/scripts/valgrind.supp", "--log-file=" + self.build_dir + "/valgrind.log" ] + command run_valgrind = True logger.debug("Spawning process: " + " ".join(shlex.quote(word) for word in command) + os.linesep + "in directory: " + self.build_dir) start_time = time.time() env = os.environ.copy() if self.asan: env["ASAN_OPTIONS"] = "log_path=stdout:" + \ env.get("ASAN_OPTIONS", "") if not self.lsan: env["ASAN_OPTIONS"] += "detect_leaks=0" if self.ubsan: env["UBSAN_OPTIONS"] = "log_path=stdout:halt_on_error=1:" + \ env.get("UBSAN_OPTIONS", "") with subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=self.build_dir, env=env) as proc: logger.debug("Spawning BinaryHandler Thread for %s" % self.name) t = threading.Thread(target=self._output_handler, args=(proc, harness,), daemon=True) t.start() t.join() if t.is_alive(): self.terminate(proc) t.join() proc.wait() self.returncode = proc.returncode self.try_kill_process_by_pid() handler_time = time.time() - start_time if self.coverage: subprocess.call(["GCOV_PREFIX=" + self.build_dir, "gcov", self.sourcedir, "-b", "-s", self.build_dir], shell=True) # FIXME: This is needed when killing the simulator, the console is # garbled and needs to be reset. Did not find a better way to do that. if sys.stdout.isatty(): subprocess.call(["stty", "sane"]) if harness.is_pytest: harness.pytest_run(self.log) self.instance.results = harness.tests if not self.terminated and self.returncode != 0: # When a process is killed, the default handler returns 128 + SIGTERM # so in that case the return code itself is not meaningful self.set_state("failed", handler_time) self.instance.reason = "Failed" elif run_valgrind and self.returncode == 2: self.set_state("failed", handler_time) self.instance.reason = "Valgrind error" elif harness.state: self.set_state(harness.state, handler_time) if harness.state == "failed": self.instance.reason = "Failed" else: self.set_state("timeout", handler_time) self.instance.reason = "Timeout" self.add_missing_testscases(harness) self._set_skip_reason(harness.state) self.record(harness) class DeviceHandler(Handler): def __init__(self, instance, type_str): """Constructor @param instance Test Instance """ super().__init__(instance, type_str) self.suite = None def monitor_serial(self, ser, halt_fileno, harness): if harness.is_pytest: harness.handle(None) return log_out_fp = open(self.log, "wt") ser_fileno = ser.fileno() readlist = [halt_fileno, ser_fileno] if self.coverage: # Set capture_coverage to True to indicate that right after # test results we should get coverage data, otherwise we exit # from the test. harness.capture_coverage = True ser.flush() while ser.isOpen(): readable, _, _ = select.select(readlist, [], [], self.timeout) if halt_fileno in readable: logger.debug('halted') ser.close() break if ser_fileno not in readable: continue # Timeout. serial_line = None try: serial_line = ser.readline() except TypeError: pass except serial.SerialException: ser.close() break # Just because ser_fileno has data doesn't mean an entire line # is available yet. if serial_line: sl = serial_line.decode('utf-8', 'ignore').lstrip() logger.debug("DEVICE: {0}".format(sl.rstrip())) log_out_fp.write(sl) log_out_fp.flush() harness.handle(sl.rstrip()) if harness.state: if not harness.capture_coverage: ser.close() break log_out_fp.close() def device_is_available(self, instance): device = instance.platform.name fixture = instance.testcase.harness_config.get("fixture") for d in self.suite.duts: if fixture and fixture not in d.fixtures: continue if d.platform != device or not (d.serial or d.serial_pty): continue d.lock.acquire() avail = False if d.available: d.available = 0 d.counter += 1 avail = True d.lock.release() if avail: return d return None def make_device_available(self, serial): for d in self.suite.duts: if d.serial == serial or d.serial_pty: d.available = 1 @staticmethod def run_custom_script(script, timeout): with subprocess.Popen(script, stderr=subprocess.PIPE, stdout=subprocess.PIPE) as proc: try: stdout, stderr = proc.communicate(timeout=timeout) logger.debug(stdout.decode()) if proc.returncode != 0: logger.error(f"Custom script failure: {stderr.decode(errors="ignore")}") except subprocess.TimeoutExpired: proc.kill() proc.communicate() logger.error("{} timed out".format(script)) def handle(self): out_state = "failed" runner = None hardware = self.device_is_available(self.instance) while not hardware: logger.debug("Waiting for device {} to become available".format(self.instance.platform.name)) time.sleep(1) hardware = self.device_is_available(self.instance) runner = hardware.runner or self.suite.west_runner serial_pty = hardware.serial_pty ser_pty_process = None if serial_pty: master, slave = pty.openpty() try: ser_pty_process = subprocess.Popen(re.split(',| ', serial_pty), stdout=master, stdin=master, stderr=master) except subprocess.CalledProcessError as error: logger.error("Failed to run subprocess {}, error {}".format(serial_pty, error.output)) return serial_device = os.ttyname(slave) else: serial_device = hardware.serial logger.debug(f"Using serial device {serial_device} @ {hardware.baud} baud") if (self.suite.west_flash is not None) or runner: command = ["west", "flash", "--skip-rebuild", "-d", self.build_dir] command_extra_args = [] # There are three ways this option is used. # 1) bare: --west-flash # This results in options.west_flash == [] # 2) with a value: --west-flash="--board-id=42" # This results in options.west_flash == "--board-id=42" # 3) Multiple values: --west-flash="--board-id=42,--erase" # This results in options.west_flash == "--board-id=42 --erase" if self.suite.west_flash and self.suite.west_flash != []: command_extra_args.extend(self.suite.west_flash.split(',')) if runner: command.append("--runner") command.append(runner) board_id = hardware.probe_id or hardware.id product = hardware.product if board_id is not None: if runner == "pyocd": command_extra_args.append("--board-id") command_extra_args.append(board_id) elif runner == "nrfjprog": command_extra_args.append("--dev-id") command_extra_args.append(board_id) elif runner == "openocd" and product == "STM32 STLink": command_extra_args.append("--cmd-pre-init") command_extra_args.append("hla_serial %s" % (board_id)) elif runner == "openocd" and product == "STLINK-V3": command_extra_args.append("--cmd-pre-init") command_extra_args.append("hla_serial %s" % (board_id)) elif runner == "openocd" and product == "EDBG CMSIS-DAP": command_extra_args.append("--cmd-pre-init") command_extra_args.append("cmsis_dap_serial %s" % (board_id)) elif runner == "jlink": command.append("--tool-opt=-SelectEmuBySN %s" % (board_id)) elif runner == "stm32cubeprogrammer": command.append("--tool-opt=sn=%s" % (board_id)) if command_extra_args != []: command.append('--') command.extend(command_extra_args) else: command = [self.generator_cmd, "-C", self.build_dir, "flash"] pre_script = hardware.pre_script post_flash_script = hardware.post_flash_script post_script = hardware.post_script if pre_script: self.run_custom_script(pre_script, 30) try: ser = serial.Serial( serial_device, baudrate=hardware.baud, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=self.timeout ) except serial.SerialException as e: self.set_state("failed", 0) self.instance.reason = "Failed" logger.error("Serial device error: %s" % (str(e))) if serial_pty and ser_pty_process: ser_pty_process.terminate() outs, errs = ser_pty_process.communicate() logger.debug("Process {} terminated outs: {} errs {}".format(serial_pty, outs, errs)) self.make_device_available(serial_device) return ser.flush() harness_name = self.instance.testcase.harness.capitalize() harness_import = HarnessImporter(harness_name) harness = harness_import.instance harness.configure(self.instance) read_pipe, write_pipe = os.pipe() start_time = time.time() t = threading.Thread(target=self.monitor_serial, daemon=True, args=(ser, read_pipe, harness)) t.start() d_log = "{}/device.log".format(self.instance.build_dir) logger.debug('Flash command: %s', command) try: stdout = stderr = None with subprocess.Popen(command, stderr=subprocess.PIPE, stdout=subprocess.PIPE) as proc: try: (stdout, stderr) = proc.communicate(timeout=30) # ignore unencodable unicode chars logger.debug(stdout.decode(errors = "ignore")) if proc.returncode != 0: self.instance.reason = "Device issue (Flash?)" with open(d_log, "w") as dlog_fp: dlog_fp.write(stderr.decode()) os.write(write_pipe, b'x') # halt the thread out_state = "flash_error" except subprocess.TimeoutExpired: proc.kill() (stdout, stderr) = proc.communicate() self.instance.reason = "Device issue (Timeout)" with open(d_log, "w") as dlog_fp: dlog_fp.write(stderr.decode()) except subprocess.CalledProcessError: os.write(write_pipe, b'x') # halt the thread if post_flash_script: self.run_custom_script(post_flash_script, 30) t.join(self.timeout) if t.is_alive(): logger.debug("Timed out while monitoring serial output on {}".format(self.instance.platform.name)) out_state = "timeout" if ser.isOpen(): ser.close() if serial_pty: ser_pty_process.terminate() outs, errs = ser_pty_process.communicate() logger.debug("Process {} terminated outs: {} errs {}".format(serial_pty, outs, errs)) os.close(write_pipe) os.close(read_pipe) handler_time = time.time() - start_time if out_state in ["timeout", "flash_error"]: self.add_missing_testscases(harness) if out_state == "timeout": self.instance.reason = "Timeout" elif out_state == "flash_error": self.instance.reason = "Flash error" if harness.is_pytest: harness.pytest_run(self.log) self.instance.results = harness.tests # sometimes a test instance hasn't been executed successfully with an # empty dictionary results, in order to include it into final report, # so fill the results as BLOCK if self.instance.results == {}: for k in self.instance.testcase.cases: self.instance.results[k] = 'BLOCK' if harness.state: self.set_state(harness.state, handler_time) if harness.state == "failed": self.instance.reason = "Failed" else: self.set_state(out_state, handler_time) self._set_skip_reason(harness.state) if post_script: self.run_custom_script(post_script, 30) self.make_device_available(serial_device) self.record(harness) class QEMUHandler(Handler): """Spawns a thread to monitor QEMU output from pipes We pass QEMU_PIPE to 'make run' and monitor the pipes for output. We need to do this as once qemu starts, it runs forever until killed. Test cases emit special messages to the console as they run, we check for these to collect whether the test passed or failed. """ def __init__(self, instance, type_str): """Constructor @param instance Test instance """ super().__init__(instance, type_str) self.fifo_fn = os.path.join(instance.build_dir, "qemu-fifo") self.pid_fn = os.path.join(instance.build_dir, "qemu.pid") if "ignore_qemu_crash" in instance.testcase.tags: self.ignore_qemu_crash = True self.ignore_unexpected_eof = True else: self.ignore_qemu_crash = False self.ignore_unexpected_eof = False @staticmethod def _get_cpu_time(pid): """get process CPU time. The guest virtual time in QEMU icount mode isn't host time and it's maintained by counting guest instructions, so we use QEMU process exection time to mostly simulate the time of guest OS. """ proc = psutil.Process(pid) cpu_time = proc.cpu_times() return cpu_time.user + cpu_time.system @staticmethod def _thread(handler, timeout, outdir, logfile, fifo_fn, pid_fn, results, harness, ignore_unexpected_eof=False): fifo_in = fifo_fn + ".in" fifo_out = fifo_fn + ".out" # These in/out nodes are named from QEMU's perspective, not ours if os.path.exists(fifo_in): os.unlink(fifo_in) os.mkfifo(fifo_in) if os.path.exists(fifo_out): os.unlink(fifo_out) os.mkfifo(fifo_out) # We don't do anything with out_fp but we need to open it for # writing so that QEMU doesn't block, due to the way pipes work out_fp = open(fifo_in, "wb") # Disable internal buffering, we don't # want read() or poll() to ever block if there is data in there in_fp = open(fifo_out, "rb", buffering=0) log_out_fp = open(logfile, "wt") start_time = time.time() timeout_time = start_time + timeout p = select.poll() p.register(in_fp, select.POLLIN) out_state = None line = "" timeout_extended = False pid = 0 if os.path.exists(pid_fn): pid = int(open(pid_fn).read()) while True: this_timeout = int((timeout_time - time.time()) * 1000) if this_timeout < 0 or not p.poll(this_timeout): try: if pid and this_timeout > 0: #there's possibility we polled nothing because #of not enough CPU time scheduled by host for #QEMU process during p.poll(this_timeout) cpu_time = QEMUHandler._get_cpu_time(pid) if cpu_time < timeout and not out_state: timeout_time = time.time() + (timeout - cpu_time) continue except ProcessLookupError: out_state = "failed" break if not out_state: out_state = "timeout" break if pid == 0 and os.path.exists(pid_fn): pid = int(open(pid_fn).read()) if harness.is_pytest: harness.handle(None) out_state = harness.state break try: c = in_fp.read(1).decode("utf-8") except UnicodeDecodeError: # Test is writing something weird, fail out_state = "unexpected byte" break if c == "": # EOF, this shouldn't happen unless QEMU crashes if not ignore_unexpected_eof: out_state = "unexpected eof" break line = line + c if c != "\n": continue # line contains a full line of data output from QEMU log_out_fp.write(line) log_out_fp.flush() line = line.strip() logger.debug(f"QEMU ({pid}): {line}") harness.handle(line) if harness.state: # if we have registered a fail make sure the state is not # overridden by a false success message coming from the # testsuite if out_state not in ['failed', 'unexpected eof', 'unexpected byte']: out_state = harness.state # if we get some state, that means test is doing well, we reset # the timeout and wait for 2 more seconds to catch anything # printed late. We wait much longer if code # coverage is enabled since dumping this information can # take some time. if not timeout_extended or harness.capture_coverage: timeout_extended = True if harness.capture_coverage: timeout_time = time.time() + 30 else: timeout_time = time.time() + 2 line = "" if harness.is_pytest: harness.pytest_run(logfile) out_state = harness.state handler.record(harness) handler_time = time.time() - start_time logger.debug(f"QEMU ({pid}) complete ({out_state}) after {handler_time} seconds") if out_state == "timeout": handler.instance.reason = "Timeout" handler.set_state("failed", handler_time) elif out_state == "failed": handler.instance.reason = "Failed" handler.set_state("failed", handler_time) elif out_state in ['unexpected eof', 'unexpected byte']: handler.instance.reason = out_state handler.set_state("failed", handler_time) else: handler.set_state(out_state, handler_time) log_out_fp.close() out_fp.close() in_fp.close() if pid: try: if pid: os.kill(pid, signal.SIGTERM) except ProcessLookupError: # Oh well, as long as it's dead! User probably sent Ctrl-C pass os.unlink(fifo_in) os.unlink(fifo_out) def handle(self): self.results = {} self.run = True # We pass this to QEMU which looks for fifos with .in and .out # suffixes. self.fifo_fn = os.path.join(self.instance.build_dir, "qemu-fifo") self.pid_fn = os.path.join(self.instance.build_dir, "qemu.pid") if os.path.exists(self.pid_fn): os.unlink(self.pid_fn) self.log_fn = self.log harness_import = HarnessImporter(self.instance.testcase.harness.capitalize()) harness = harness_import.instance harness.configure(self.instance) self.thread = threading.Thread(name=self.name, target=QEMUHandler._thread, args=(self, self.timeout, self.build_dir, self.log_fn, self.fifo_fn, self.pid_fn, self.results, harness, self.ignore_unexpected_eof)) self.instance.results = harness.tests self.thread.daemon = True logger.debug("Spawning QEMUHandler Thread for %s" % self.name) self.thread.start() if sys.stdout.isatty(): subprocess.call(["stty", "sane"]) logger.debug("Running %s (%s)" % (self.name, self.type_str)) command = [self.generator_cmd] command += ["-C", self.build_dir, "run"] is_timeout = False qemu_pid = None with subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=self.build_dir) as proc: logger.debug("Spawning QEMUHandler Thread for %s" % self.name) try: proc.wait(self.timeout) except subprocess.TimeoutExpired: # sometimes QEMU can't handle SIGTERM signal correctly # in that case kill -9 QEMU process directly and leave # twister to judge testing result by console output is_timeout = True self.terminate(proc) if harness.state == "passed": self.returncode = 0 else: self.returncode = proc.returncode else: if os.path.exists(self.pid_fn): qemu_pid = int(open(self.pid_fn).read()) logger.debug(f"No timeout, return code from QEMU ({qemu_pid}): {proc.returncode}") self.returncode = proc.returncode # Need to wait for harness to finish processing # output from QEMU. Otherwise it might miss some # error messages. self.thread.join(0) if self.thread.is_alive(): logger.debug("Timed out while monitoring QEMU output") if os.path.exists(self.pid_fn): qemu_pid = int(open(self.pid_fn).read()) os.unlink(self.pid_fn) logger.debug(f"return code from QEMU ({qemu_pid}): {self.returncode}") if (self.returncode != 0 and not self.ignore_qemu_crash) or not harness.state: self.set_state("failed", 0) if is_timeout: self.instance.reason = "Timeout" else: self.instance.reason = "Exited with {}".format(self.returncode) self.add_missing_testscases(harness) self._set_skip_reason(harness.state) def get_fifo(self): return self.fifo_fn class SizeCalculator: alloc_sections = [ "bss", "noinit", "app_bss", "app_noinit", "ccm_bss", "ccm_noinit" ] rw_sections = [ "datas", "initlevel", "exceptions", "initshell", "_static_thread_data_area", "k_timer_area", "k_mem_slab_area", "k_mem_pool_area", "sw_isr_table", "k_sem_area", "k_mutex_area", "app_shmem_regions", "_k_fifo_area", "_k_lifo_area", "k_stack_area", "k_msgq_area", "k_mbox_area", "k_pipe_area", "net_if_area", "net_if_dev_area", "net_l2_area", "net_l2_data", "k_queue_area", "_net_buf_pool_area", "app_datas", "kobject_data", "mmu_tables", "app_pad", "priv_stacks", "ccm_data", "usb_descriptor", "usb_data", "usb_bos_desc", "uart_mux", 'log_backends_sections', 'log_dynamic_sections', 'log_const_sections', "app_smem", 'shell_root_cmds_sections', 'log_const_sections', "font_entry_sections", "priv_stacks_noinit", "_GCOV_BSS_SECTION_NAME", "gcov", "nocache", "devices", "k_heap_area", ] # These get copied into RAM only on non-XIP ro_sections = [ "rom_start", "text", "ctors", "init_array", "reset", "z_object_assignment_area", "rodata", "net_l2", "vector", "sw_isr_table", "settings_handler_static_area", "bt_l2cap_fixed_chan_area", "bt_l2cap_br_fixed_chan_area", "bt_gatt_service_static_area", "vectors", "net_socket_register_area", "net_ppp_proto", "shell_area", "tracing_backend_area", "ppp_protocol_handler_area", ] def __init__(self, filename, extra_sections): """Constructor @param filename Path to the output binary The <filename> is parsed by objdump to determine section sizes """ # Make sure this is an ELF binary with open(filename, "rb") as f: magic = f.read(4) try: if magic != b'\x7fELF': raise TwisterRuntimeError("%s is not an ELF binary" % filename) except Exception as e: print(str(e)) sys.exit(2) # Search for CONFIG_XIP in the ELF's list of symbols using NM and AWK. # GREP can not be used as it returns an error if the symbol is not # found. is_xip_command = "nm " + filename + \ " | awk '/CONFIG_XIP/ { print $3 }'" is_xip_output = subprocess.check_output( is_xip_command, shell=True, stderr=subprocess.STDOUT).decode( "utf-8").strip() try: if is_xip_output.endswith("no symbols"): raise TwisterRuntimeError("%s has no symbol information" % filename) except Exception as e: print(str(e)) sys.exit(2) self.is_xip = (len(is_xip_output) != 0) self.filename = filename self.sections = [] self.rom_size = 0 self.ram_size = 0 self.extra_sections = extra_sections self._calculate_sizes() def get_ram_size(self): """Get the amount of RAM the application will use up on the device @return amount of RAM, in bytes """ return self.ram_size def get_rom_size(self): """Get the size of the data that this application uses on device's flash @return amount of ROM, in bytes """ return self.rom_size def unrecognized_sections(self): """Get a list of sections inside the binary that weren't recognized @return list of unrecognized section names """ slist = [] for v in self.sections: if not v["recognized"]: slist.append(v["name"]) return slist def _calculate_sizes(self): """ Calculate RAM and ROM usage by section """ objdump_command = "objdump -h " + self.filename objdump_output = subprocess.check_output( objdump_command, shell=True).decode("utf-8").splitlines() for line in objdump_output: words = line.split() if not words: # Skip lines that are too short continue index = words[0] if not index[0].isdigit(): # Skip lines that do not start continue # with a digit name = words[1] # Skip lines with section names if name[0] == '.': # starting with '.' continue # TODO this doesn't actually reflect the size in flash or RAM as # it doesn't include linker-imposed padding between sections. # It is close though. size = int(words[2], 16) if size == 0: continue load_addr = int(words[4], 16) virt_addr = int(words[3], 16) # Add section to memory use totals (for both non-XIP and XIP scenarios) # Unrecognized section names are not included in the calculations. recognized = True if name in SizeCalculator.alloc_sections: self.ram_size += size stype = "alloc" elif name in SizeCalculator.rw_sections: self.ram_size += size self.rom_size += size stype = "rw" elif name in SizeCalculator.ro_sections: self.rom_size += size if not self.is_xip: self.ram_size += size stype = "ro" else: stype = "unknown" if name not in self.extra_sections: recognized = False self.sections.append({"name": name, "load_addr": load_addr, "size": size, "virt_addr": virt_addr, "type": stype, "recognized": recognized}) class TwisterConfigParser: """Class to read test case files with semantic checking """ def __init__(self, filename, schema): """Instantiate a new TwisterConfigParser object @param filename Source .yaml file to read """ self.data = {} self.schema = schema self.filename = filename self.tests = {} self.common = {} def load(self): self.data = scl.yaml_load_verify(self.filename, self.schema) if 'tests' in self.data: self.tests = self.data['tests'] if 'common' in self.data: self.common = self.data['common'] def _cast_value(self, value, typestr): if isinstance(value, str): v = value.strip() if typestr == "str": return v elif typestr == "float": return float(value) elif typestr == "int": return int(value) elif typestr == "bool": return value elif typestr.startswith("list") and isinstance(value, list): return value elif typestr.startswith("list") and isinstance(value, str): vs = v.split() if len(typestr) > 4 and typestr[4] == ":": return [self._cast_value(vsi, typestr[5:]) for vsi in vs] else: return vs elif typestr.startswith("set"): vs = v.split() if len(typestr) > 3 and typestr[3] == ":": return {self._cast_value(vsi, typestr[4:]) for vsi in vs} else: return set(vs) elif typestr.startswith("map"): return value else: raise ConfigurationError( self.filename, "unknown type '%s'" % value) def get_test(self, name, valid_keys): """Get a dictionary representing the keys/values within a test @param name The test in the .yaml file to retrieve data from @param valid_keys A dictionary representing the intended semantics for this test. Each key in this dictionary is a key that could be specified, if a key is given in the .yaml file which isn't in here, it will generate an error. Each value in this dictionary is another dictionary containing metadata: "default" - Default value if not given "type" - Data type to convert the text value to. Simple types supported are "str", "float", "int", "bool" which will get converted to respective Python data types. "set" and "list" may also be specified which will split the value by whitespace (but keep the elements as strings). finally, "list:<type>" and "set:<type>" may be given which will perform a type conversion after splitting the value up. "required" - If true, raise an error if not defined. If false and "default" isn't specified, a type conversion will be done on an empty string @return A dictionary containing the test key-value pairs with type conversion and default values filled in per valid_keys """ d = {} for k, v in self.common.items(): d[k] = v for k, v in self.tests[name].items(): if k in d: if isinstance(d[k], str): # By default, we just concatenate string values of keys # which appear both in "common" and per-test sections, # but some keys are handled in adhoc way based on their # semantics. if k == "filter": d[k] = "(%s) and (%s)" % (d[k], v) else: d[k] += " " + v else: d[k] = v for k, kinfo in valid_keys.items(): if k not in d: if "required" in kinfo: required = kinfo["required"] else: required = False if required: raise ConfigurationError( self.filename, "missing required value for '%s' in test '%s'" % (k, name)) else: if "default" in kinfo: default = kinfo["default"] else: default = self._cast_value("", kinfo["type"]) d[k] = default else: try: d[k] = self._cast_value(d[k], kinfo["type"]) except ValueError: raise ConfigurationError( self.filename, "bad %s value '%s' for key '%s' in name '%s'" % (kinfo["type"], d[k], k, name)) return d class Platform: """Class representing metadata for a particular platform Maps directly to BOARD when building""" platform_schema = scl.yaml_load(os.path.join(ZEPHYR_BASE, "scripts", "schemas", "twister", "platform-schema.yaml")) def __init__(self): """Constructor. """ self.name = "" self.twister = True # if no RAM size is specified by the board, take a default of 128K self.ram = 128 self.ignore_tags = [] self.only_tags = [] self.default = False # if no flash size is specified by the board, take a default of 512K self.flash = 512 self.supported = set() self.arch = "" self.type = "na" self.simulation = "na" self.supported_toolchains = [] self.env = [] self.env_satisfied = True self.filter_data = dict() def load(self, platform_file): scp = TwisterConfigParser(platform_file, self.platform_schema) scp.load() data = scp.data self.name = data['identifier'] self.twister = data.get("twister", True) # if no RAM size is specified by the board, take a default of 128K self.ram = data.get("ram", 128) testing = data.get("testing", {}) self.ignore_tags = testing.get("ignore_tags", []) self.only_tags = testing.get("only_tags", []) self.default = testing.get("default", False) # if no flash size is specified by the board, take a default of 512K self.flash = data.get("flash", 512) self.supported = set() for supp_feature in data.get("supported", []): for item in supp_feature.split(":"): self.supported.add(item) self.arch = data['arch'] self.type = data.get('type', "na") self.simulation = data.get('simulation', "na") self.supported_toolchains = data.get("toolchain", []) self.env = data.get("env", []) self.env_satisfied = True for env in self.env: if not os.environ.get(env, None): self.env_satisfied = False def __repr__(self): return "<%s on %s>" % (self.name, self.arch) class DisablePyTestCollectionMixin(object): __test__ = False class ScanPathResult: """Result of the TestCase.scan_path function call. Attributes: matches A list of test cases warnings A string containing one or more warnings to display has_registered_test_suites Whether or not the path contained any calls to the ztest_register_test_suite macro. has_run_registered_test_suites Whether or not the path contained at least one call to ztest_run_registered_test_suites. has_test_main Whether or not the path contains a definition of test_main(void) """ def __init__(self, matches: List[str] = None, warnings: str = None, has_registered_test_suites: bool = False, has_run_registered_test_suites: bool = False, has_test_main: bool = False): self.matches = matches self.warnings = warnings self.has_registered_test_suites = has_registered_test_suites self.has_run_registered_test_suites = has_run_registered_test_suites self.has_test_main = has_test_main def __eq__(self, other): if not isinstance(other, ScanPathResult): return False return (sorted(self.matches) == sorted(other.matches) and self.warnings == other.warnings and (self.has_registered_test_suites == other.has_registered_test_suites) and (self.has_run_registered_test_suites == other.has_run_registered_test_suites) and self.has_test_main == other.has_test_main) class TestCase(DisablePyTestCollectionMixin): """Class representing a test application """ def __init__(self, testcase_root, workdir, name): """TestCase constructor. This gets called by TestSuite as it finds and reads test yaml files. Multiple TestCase instances may be generated from a single testcase.yaml, each one corresponds to an entry within that file. We need to have a unique name for every single test case. Since a testcase.yaml can define multiple tests, the canonical name for the test case is <workdir>/<name>. @param testcase_root os.path.abspath() of one of the --testcase-root @param workdir Sub-directory of testcase_root where the .yaml test configuration file was found @param name Name of this test case, corresponding to the entry name in the test case configuration file. For many test cases that just define one test, can be anything and is usually "test". This is really only used to distinguish between different cases when the testcase.yaml defines multiple tests """ self.source_dir = "" self.yamlfile = "" self.cases = [] self.name = self.get_unique(testcase_root, workdir, name) self.id = name self.type = None self.tags = set() self.extra_args = None self.extra_configs = None self.arch_allow = None self.arch_exclude = None self.skip = False self.platform_exclude = None self.platform_allow = None self.toolchain_exclude = None self.toolchain_allow = None self.tc_filter = None self.timeout = 60 self.harness = "" self.harness_config = {} self.build_only = True self.build_on_all = False self.slow = False self.min_ram = -1 self.depends_on = None self.min_flash = -1 self.extra_sections = None self.integration_platforms = [] @staticmethod def get_unique(testcase_root, workdir, name): canonical_testcase_root = os.path.realpath(testcase_root) if Path(canonical_zephyr_base) in Path(canonical_testcase_root).parents: # This is in ZEPHYR_BASE, so include path in name for uniqueness # FIXME: We should not depend on path of test for unique names. relative_tc_root = os.path.relpath(canonical_testcase_root, start=canonical_zephyr_base) else: relative_tc_root = "" # workdir can be "." unique = os.path.normpath(os.path.join(relative_tc_root, workdir, name)) check = name.split(".") if len(check) < 2: raise TwisterException(f"""bad test name '{name}' in {testcase_root}/{workdir}. \ Tests should reference the category and subsystem with a dot as a separator. """ ) return unique @staticmethod def scan_file(inf_name): suite_regex = re.compile( # do not match until end-of-line, otherwise we won't allow # stc_regex below to catch the ones that are declared in the same # line--as we only search starting the end of this match br"^\s*ztest_test_suite\(\s*(?P<suite_name>[a-zA-Z0-9_]+)\s*,", re.MULTILINE) registered_suite_regex = re.compile( br"^\s*ztest_register_test_suite" br"\(\s*(?P<suite_name>[a-zA-Z0-9_]+)\s*,", re.MULTILINE) # Checks if the file contains a definition of "void test_main(void)" # Since ztest provides a plain test_main implementation it is OK to: # 1. register test suites and not call the run function iff the test # doesn't have a custom test_main. # 2. register test suites and a custom test_main definition iff the test # also calls ztest_run_registered_test_suites. test_main_regex = re.compile( br"^\s*void\s+test_main\(void\)", re.MULTILINE) stc_regex = re.compile( br"""^\s* # empy space at the beginning is ok # catch the case where it is declared in the same sentence, e.g: # # ztest_test_suite(mutex_complex, ztest_user_unit_test(TESTNAME)); # ztest_register_test_suite(n, p, ztest_user_unit_test(TESTNAME), (?:ztest_ (?:test_suite\(|register_test_suite\([a-zA-Z0-9_]+\s*,\s*) [a-zA-Z0-9_]+\s*,\s* )? # Catch ztest[_user]_unit_test-[_setup_teardown](TESTNAME) ztest_(?:1cpu_)?(?:user_)?unit_test(?:_setup_teardown)? # Consume the argument that becomes the extra testcse \(\s*(?P<stc_name>[a-zA-Z0-9_]+) # _setup_teardown() variant has two extra arguments that we ignore (?:\s*,\s*[a-zA-Z0-9_]+\s*,\s*[a-zA-Z0-9_]+)? \s*\)""", # We don't check how it finishes; we don't care re.MULTILINE | re.VERBOSE) suite_run_regex = re.compile( br"^\s*ztest_run_test_suite\((?P<suite_name>[a-zA-Z0-9_]+)\)", re.MULTILINE) registered_suite_run_regex = re.compile( br"^\s*ztest_run_registered_test_suites\(" br"(\*+|&)?(?P<state_identifier>[a-zA-Z0-9_]+)\)", re.MULTILINE) achtung_regex = re.compile( br"(#ifdef|#endif)", re.MULTILINE) warnings = None has_registered_test_suites = False has_run_registered_test_suites = False has_test_main = False with open(inf_name) as inf: if os.name == 'nt': mmap_args = {'fileno': inf.fileno(), 'length': 0, 'access': mmap.ACCESS_READ} else: mmap_args = {'fileno': inf.fileno(), 'length': 0, 'flags': mmap.MAP_PRIVATE, 'prot': mmap.PROT_READ, 'offset': 0} with contextlib.closing(mmap.mmap(**mmap_args)) as main_c: suite_regex_match = suite_regex.search(main_c) registered_suite_regex_match = registered_suite_regex.search( main_c) if registered_suite_regex_match: has_registered_test_suites = True if registered_suite_run_regex.search(main_c): has_run_registered_test_suites = True if test_main_regex.search(main_c): has_test_main = True if not suite_regex_match and not has_registered_test_suites: # can't find ztest_test_suite, maybe a client, because # it includes ztest.h return ScanPathResult( matches=None, warnings=None, has_registered_test_suites=has_registered_test_suites, has_run_registered_test_suites=has_run_registered_test_suites, has_test_main=has_test_main) suite_run_match = suite_run_regex.search(main_c) if suite_regex_match and not suite_run_match: raise ValueError("can't find ztest_run_test_suite") if suite_regex_match: search_start = suite_regex_match.end() else: search_start = registered_suite_regex_match.end() if suite_run_match: search_end = suite_run_match.start() else: search_end = re.compile(br"\);", re.MULTILINE) \ .search(main_c, search_start) \ .end() achtung_matches = re.findall( achtung_regex, main_c[search_start:search_end]) if achtung_matches: warnings = "found invalid %s in ztest_test_suite()" \ % ", ".join(sorted({match.decode() for match in achtung_matches},reverse = True)) _matches = re.findall( stc_regex, main_c[search_start:search_end]) for match in _matches: if not match.decode().startswith("test_"): warnings = "Found a test that does not start with test_" matches = [match.decode().replace("test_", "", 1) for match in _matches] return ScanPathResult( matches=matches, warnings=warnings, has_registered_test_suites=has_registered_test_suites, has_run_registered_test_suites=has_run_registered_test_suites, has_test_main=has_test_main) def scan_path(self, path): subcases = [] has_registered_test_suites = False has_run_registered_test_suites = False has_test_main = False for filename in glob.glob(os.path.join(path, "src", "*.c*")): try: result: ScanPathResult = self.scan_file(filename) if result.warnings: logger.error("%s: %s" % (filename, result.warnings)) raise TwisterRuntimeError( "%s: %s" % (filename, result.warnings)) if result.matches: subcases += result.matches if result.has_registered_test_suites: has_registered_test_suites = True if result.has_run_registered_test_suites: has_run_registered_test_suites = True if result.has_test_main: has_test_main = True except ValueError as e: logger.error("%s: can't find: %s" % (filename, e)) for filename in glob.glob(os.path.join(path, "*.c")): try: result: ScanPathResult = self.scan_file(filename) if result.warnings: logger.error("%s: %s" % (filename, result.warnings)) if result.matches: subcases += result.matches except ValueError as e: logger.error("%s: can't find: %s" % (filename, e)) if (has_registered_test_suites and has_test_main and not has_run_registered_test_suites): warning = \ "Found call to 'ztest_register_test_suite()' but no "\ "call to 'ztest_run_registered_test_suites()'" logger.error(warning) raise TwisterRuntimeError(warning) return subcases def parse_subcases(self, test_path): results = self.scan_path(test_path) for sub in results: name = "{}.{}".format(self.id, sub) self.cases.append(name) if not results: self.cases.append(self.id) def __str__(self): return self.name class TestInstance(DisablePyTestCollectionMixin): """Class representing the execution of a particular TestCase on a platform @param test The TestCase object we want to build/execute @param platform Platform object that we want to build and run against @param base_outdir Base directory for all test results. The actual out directory used is <outdir>/<platform>/<test case name> """ def __init__(self, testcase, platform, outdir): self.testcase = testcase self.platform = platform self.status = None self.reason = "Unknown" self.metrics = dict() self.handler = None self.outdir = outdir self.name = os.path.join(platform.name, testcase.name) self.build_dir = os.path.join(outdir, platform.name, testcase.name) self.run = False self.results = {} def __getstate__(self): d = self.__dict__.copy() return d def __setstate__(self, d): self.__dict__.update(d) def __lt__(self, other): return self.name < other.name @staticmethod def testcase_runnable(testcase, fixtures): can_run = False # console harness allows us to run the test and capture data. if testcase.harness in [ 'console', 'ztest', 'pytest']: can_run = True # if we have a fixture that is also being supplied on the # command-line, then we need to run the test, not just build it. fixture = testcase.harness_config.get('fixture') if fixture: can_run = (fixture in fixtures) elif testcase.harness: can_run = False else: can_run = True return can_run # Global testsuite parameters def check_runnable(self, enable_slow=False, filter='buildable', fixtures=[]): # right now we only support building on windows. running is still work # in progress. if os.name == 'nt': return False # we asked for build-only on the command line if self.testcase.build_only: return False # Do not run slow tests: skip_slow = self.testcase.slow and not enable_slow if skip_slow: return False target_ready = bool(self.testcase.type == "unit" or \ self.platform.type == "native" or \ self.platform.simulation in ["mdb-nsim", "nsim", "renode", "qemu", "tsim", "armfvp", "xt-sim"] or \ filter == 'runnable') if self.platform.simulation == "nsim": if not find_executable("nsimdrv"): target_ready = False if self.platform.simulation == "mdb-nsim": if not find_executable("mdb"): target_ready = False if self.platform.simulation == "renode": if not find_executable("renode"): target_ready = False if self.platform.simulation == "tsim": if not find_executable("tsim-leon3"): target_ready = False testcase_runnable = self.testcase_runnable(self.testcase, fixtures) return testcase_runnable and target_ready def create_overlay(self, platform, enable_asan=False, enable_ubsan=False, enable_coverage=False, coverage_platform=[]): # Create this in a "twister/" subdirectory otherwise this # will pass this overlay to kconfig.py *twice* and kconfig.cmake # will silently give that second time precedence over any # --extra-args=CONFIG_* subdir = os.path.join(self.build_dir, "twister") content = "" if self.testcase.extra_configs: content = "\n".join(self.testcase.extra_configs) if enable_coverage: if platform.name in coverage_platform: content = content + "\nCONFIG_COVERAGE=y" content = content + "\nCONFIG_COVERAGE_DUMP=y" if enable_asan: if platform.type == "native": content = content + "\nCONFIG_ASAN=y" if enable_ubsan: if platform.type == "native": content = content + "\nCONFIG_UBSAN=y" if content: os.makedirs(subdir, exist_ok=True) file = os.path.join(subdir, "testcase_extra.conf") with open(file, "w") as f: f.write(content) return content def calculate_sizes(self): """Get the RAM/ROM sizes of a test case. This can only be run after the instance has been executed by MakeGenerator, otherwise there won't be any binaries to measure. @return A SizeCalculator object """ fns = glob.glob(os.path.join(self.build_dir, "zephyr", "*.elf")) fns.extend(glob.glob(os.path.join(self.build_dir, "zephyr", "*.exe"))) fns = [x for x in fns if '_pre' not in x] if len(fns) != 1: raise BuildError("Missing/multiple output ELF binary") return SizeCalculator(fns[0], self.testcase.extra_sections) def fill_results_by_status(self): """Fills results according to self.status The method is used to propagate the instance level status to the test cases inside. Useful when the whole instance is skipped and the info is required also at the test cases level for reporting. Should be used with caution, e.g. should not be used to fill all results with passes """ status_to_verdict = { 'skipped': 'SKIP', 'error': 'BLOCK', 'failure': 'FAILED' } for k in self.results: self.results[k] = status_to_verdict[self.status] def __repr__(self): return "<TestCase %s on %s>" % (self.testcase.name, self.platform.name) class CMake(): config_re = re.compile('(CONFIG_[A-Za-z0-9_]+)[=]\"?([^\"]*)\"?$') dt_re = re.compile('([A-Za-z0-9_]+)[=]\"?([^\"]*)\"?$') def __init__(self, testcase, platform, source_dir, build_dir): self.cwd = None self.capture_output = True self.defconfig = {} self.cmake_cache = {} self.instance = None self.testcase = testcase self.platform = platform self.source_dir = source_dir self.build_dir = build_dir self.log = "build.log" self.generator = None self.generator_cmd = None def parse_generated(self): self.defconfig = {} return {} def run_build(self, args=[]): logger.debug("Building %s for %s" % (self.source_dir, self.platform.name)) cmake_args = [] cmake_args.extend(args) cmake = shutil.which('cmake') cmd = [cmake] + cmake_args kwargs = dict() if self.capture_output: kwargs['stdout'] = subprocess.PIPE # CMake sends the output of message() to stderr unless it's STATUS kwargs['stderr'] = subprocess.STDOUT if self.cwd: kwargs['cwd'] = self.cwd p = subprocess.Popen(cmd, **kwargs) out, _ = p.communicate() results = {} if p.returncode == 0: msg = "Finished building %s for %s" % (self.source_dir, self.platform.name) self.instance.status = "passed" results = {'msg': msg, "returncode": p.returncode, "instance": self.instance} if out: log_msg = out.decode(sys.getdefaultencoding()) with open(os.path.join(self.build_dir, self.log), "a") as log: log.write(log_msg) else: return None else: # A real error occurred, raise an exception log_msg = "" if out: log_msg = out.decode(sys.getdefaultencoding()) with open(os.path.join(self.build_dir, self.log), "a") as log: log.write(log_msg) if log_msg: res = re.findall("region `(FLASH|ROM|RAM|ICCM|DCCM|SRAM)' overflowed by", log_msg) if res and not self.overflow_as_errors: logger.debug("Test skipped due to {} Overflow".format(res[0])) self.instance.status = "skipped" self.instance.reason = "{} overflow".format(res[0]) else: self.instance.status = "error" self.instance.reason = "Build failure" results = { "returncode": p.returncode, "instance": self.instance, } return results def run_cmake(self, args=[]): if self.warnings_as_errors: ldflags = "-Wl,--fatal-warnings" cflags = "-Werror" aflags = "-Werror -Wa,--fatal-warnings" gen_defines_args = "--edtlib-Werror" else: ldflags = cflags = aflags = "" gen_defines_args = "" logger.debug("Running cmake on %s for %s" % (self.source_dir, self.platform.name)) cmake_args = [ f'-B{self.build_dir}', f'-S{self.source_dir}', f'-DEXTRA_CFLAGS={cflags}', f'-DEXTRA_AFLAGS={aflags}', f'-DEXTRA_LDFLAGS={ldflags}', f'-DEXTRA_GEN_DEFINES_ARGS={gen_defines_args}', f'-G{self.generator}' ] args = ["-D{}".format(a.replace('"', '')) for a in args] cmake_args.extend(args) cmake_opts = ['-DBOARD={}'.format(self.platform.name)] cmake_args.extend(cmake_opts) logger.debug("Calling cmake with arguments: {}".format(cmake_args)) cmake = shutil.which('cmake') cmd = [cmake] + cmake_args kwargs = dict() if self.capture_output: kwargs['stdout'] = subprocess.PIPE # CMake sends the output of message() to stderr unless it's STATUS kwargs['stderr'] = subprocess.STDOUT if self.cwd: kwargs['cwd'] = self.cwd p = subprocess.Popen(cmd, **kwargs) out, _ = p.communicate() if p.returncode == 0: filter_results = self.parse_generated() msg = "Finished building %s for %s" % (self.source_dir, self.platform.name) logger.debug(msg) results = {'msg': msg, 'filter': filter_results} else: self.instance.status = "error" self.instance.reason = "Cmake build failure" self.instance.fill_results_by_status() logger.error("Cmake build failure: %s for %s" % (self.source_dir, self.platform.name)) results = {"returncode": p.returncode} if out: with open(os.path.join(self.build_dir, self.log), "a") as log: log_msg = out.decode(sys.getdefaultencoding()) log.write(log_msg) return results @staticmethod def run_cmake_script(args=[]): logger.debug("Running cmake script %s" % (args[0])) cmake_args = ["-D{}".format(a.replace('"', '')) for a in args[1:]] cmake_args.extend(['-P', args[0]]) logger.debug("Calling cmake with arguments: {}".format(cmake_args)) cmake = shutil.which('cmake') if not cmake: msg = "Unable to find `cmake` in path" logger.error(msg) raise Exception(msg) cmd = [cmake] + cmake_args kwargs = dict() kwargs['stdout'] = subprocess.PIPE # CMake sends the output of message() to stderr unless it's STATUS kwargs['stderr'] = subprocess.STDOUT p = subprocess.Popen(cmd, **kwargs) out, _ = p.communicate() # It might happen that the environment adds ANSI escape codes like \x1b[0m, # for instance if twister is executed from inside a makefile. In such a # scenario it is then necessary to remove them, as otherwise the JSON decoding # will fail. ansi_escape = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])') out = ansi_escape.sub('', out.decode()) if p.returncode == 0: msg = "Finished running %s" % (args[0]) logger.debug(msg) results = {"returncode": p.returncode, "msg": msg, "stdout": out} else: logger.error("Cmake script failure: %s" % (args[0])) results = {"returncode": p.returncode, "returnmsg": out} return results class FilterBuilder(CMake): def __init__(self, testcase, platform, source_dir, build_dir): super().__init__(testcase, platform, source_dir, build_dir) self.log = "config-twister.log" def parse_generated(self): if self.platform.name == "unit_testing": return {} cmake_cache_path = os.path.join(self.build_dir, "CMakeCache.txt") defconfig_path = os.path.join(self.build_dir, "zephyr", ".config") with open(defconfig_path, "r") as fp: defconfig = {} for line in fp.readlines(): m = self.config_re.match(line) if not m: if line.strip() and not line.startswith("#"): sys.stderr.write("Unrecognized line %s\n" % line) continue defconfig[m.group(1)] = m.group(2).strip() self.defconfig = defconfig cmake_conf = {} try: cache = CMakeCache.from_file(cmake_cache_path) except FileNotFoundError: cache = {} for k in iter(cache): cmake_conf[k.name] = k.value self.cmake_cache = cmake_conf filter_data = { "ARCH": self.platform.arch, "PLATFORM": self.platform.name } filter_data.update(os.environ) filter_data.update(self.defconfig) filter_data.update(self.cmake_cache) edt_pickle = os.path.join(self.build_dir, "zephyr", "edt.pickle") if self.testcase and self.testcase.tc_filter: try: if os.path.exists(edt_pickle): with open(edt_pickle, 'rb') as f: edt = pickle.load(f) else: edt = None res = expr_parser.parse(self.testcase.tc_filter, filter_data, edt) except (ValueError, SyntaxError) as se: sys.stderr.write( "Failed processing %s\n" % self.testcase.yamlfile) raise se if not res: return {os.path.join(self.platform.name, self.testcase.name): True} else: return {os.path.join(self.platform.name, self.testcase.name): False} else: self.platform.filter_data = filter_data return filter_data class ProjectBuilder(FilterBuilder): def __init__(self, suite, instance, **kwargs): super().__init__(instance.testcase, instance.platform, instance.testcase.source_dir, instance.build_dir) self.log = "build.log" self.instance = instance self.suite = suite self.filtered_tests = 0 self.lsan = kwargs.get('lsan', False) self.asan = kwargs.get('asan', False) self.ubsan = kwargs.get('ubsan', False) self.valgrind = kwargs.get('valgrind', False) self.extra_args = kwargs.get('extra_args', []) self.device_testing = kwargs.get('device_testing', False) self.cmake_only = kwargs.get('cmake_only', False) self.cleanup = kwargs.get('cleanup', False) self.coverage = kwargs.get('coverage', False) self.inline_logs = kwargs.get('inline_logs', False) self.generator = kwargs.get('generator', None) self.generator_cmd = kwargs.get('generator_cmd', None) self.verbose = kwargs.get('verbose', None) self.warnings_as_errors = kwargs.get('warnings_as_errors', True) self.overflow_as_errors = kwargs.get('overflow_as_errors', False) @staticmethod def log_info(filename, inline_logs): filename = os.path.abspath(os.path.realpath(filename)) if inline_logs: logger.info("{:-^100}".format(filename)) try: with open(filename) as fp: data = fp.read() except Exception as e: data = "Unable to read log data (%s)\n" % (str(e)) logger.error(data) logger.info("{:-^100}".format(filename)) else: logger.error("see: " + Fore.YELLOW + filename + Fore.RESET) def log_info_file(self, inline_logs): build_dir = self.instance.build_dir h_log = "{}/handler.log".format(build_dir) b_log = "{}/build.log".format(build_dir) v_log = "{}/valgrind.log".format(build_dir) d_log = "{}/device.log".format(build_dir) if os.path.exists(v_log) and "Valgrind" in self.instance.reason: self.log_info("{}".format(v_log), inline_logs) elif os.path.exists(h_log) and os.path.getsize(h_log) > 0: self.log_info("{}".format(h_log), inline_logs) elif os.path.exists(d_log) and os.path.getsize(d_log) > 0: self.log_info("{}".format(d_log), inline_logs) else: self.log_info("{}".format(b_log), inline_logs) def setup_handler(self): instance = self.instance args = [] # FIXME: Needs simplification if instance.platform.simulation == "qemu": instance.handler = QEMUHandler(instance, "qemu") args.append("QEMU_PIPE=%s" % instance.handler.get_fifo()) instance.handler.call_make_run = True elif instance.testcase.type == "unit": instance.handler = BinaryHandler(instance, "unit") instance.handler.binary = os.path.join(instance.build_dir, "testbinary") if self.coverage: args.append("COVERAGE=1") elif instance.platform.type == "native": handler = BinaryHandler(instance, "native") handler.asan = self.asan handler.valgrind = self.valgrind handler.lsan = self.lsan handler.ubsan = self.ubsan handler.coverage = self.coverage handler.binary = os.path.join(instance.build_dir, "zephyr", "zephyr.exe") instance.handler = handler elif instance.platform.simulation == "renode": if find_executable("renode"): instance.handler = BinaryHandler(instance, "renode") instance.handler.pid_fn = os.path.join(instance.build_dir, "renode.pid") instance.handler.call_make_run = True elif instance.platform.simulation == "tsim": instance.handler = BinaryHandler(instance, "tsim") instance.handler.call_make_run = True elif self.device_testing: instance.handler = DeviceHandler(instance, "device") instance.handler.coverage = self.coverage elif instance.platform.simulation == "nsim": if find_executable("nsimdrv"): instance.handler = BinaryHandler(instance, "nsim") instance.handler.call_make_run = True elif instance.platform.simulation == "mdb-nsim": if find_executable("mdb"): instance.handler = BinaryHandler(instance, "nsim") instance.handler.call_make_run = True elif instance.platform.simulation == "armfvp": instance.handler = BinaryHandler(instance, "armfvp") instance.handler.call_make_run = True elif instance.platform.simulation == "xt-sim": instance.handler = BinaryHandler(instance, "xt-sim") instance.handler.call_make_run = True if instance.handler: instance.handler.args = args instance.handler.generator_cmd = self.generator_cmd instance.handler.generator = self.generator def process(self, pipeline, done, message, lock, results): op = message.get('op') if not self.instance.handler: self.setup_handler() # The build process, call cmake and build with configured generator if op == "cmake": res = self.cmake() if self.instance.status in ["failed", "error"]: pipeline.put({"op": "report", "test": self.instance}) elif self.cmake_only: if self.instance.status is None: self.instance.status = "passed" pipeline.put({"op": "report", "test": self.instance}) else: if self.instance.name in res['filter'] and res['filter'][self.instance.name]: logger.debug("filtering %s" % self.instance.name) self.instance.status = "skipped" self.instance.reason = "filter" results.skipped_runtime += 1 for case in self.instance.testcase.cases: self.instance.results.update({case: 'SKIP'}) pipeline.put({"op": "report", "test": self.instance}) else: pipeline.put({"op": "build", "test": self.instance}) elif op == "build": logger.debug("build test: %s" % self.instance.name) res = self.build() if not res: self.instance.status = "error" self.instance.reason = "Build Failure" pipeline.put({"op": "report", "test": self.instance}) else: # Count skipped cases during build, for example # due to ram/rom overflow. inst = res.get("instance", None) if inst and inst.status == "skipped": results.skipped_runtime += 1 if res.get('returncode', 1) > 0: pipeline.put({"op": "report", "test": self.instance}) else: if self.instance.run and self.instance.handler: pipeline.put({"op": "run", "test": self.instance}) else: pipeline.put({"op": "report", "test": self.instance}) # Run the generated binary using one of the supported handlers elif op == "run": logger.debug("run test: %s" % self.instance.name) self.run() self.instance.status, _ = self.instance.handler.get_state() logger.debug(f"run status: {self.instance.name} {self.instance.status}") # to make it work with pickle self.instance.handler.thread = None self.instance.handler.suite = None pipeline.put({ "op": "report", "test": self.instance, "status": self.instance.status, "reason": self.instance.reason } ) # Report results and output progress to screen elif op == "report": with lock: done.put(self.instance) self.report_out(results) if self.cleanup and not self.coverage and self.instance.status == "passed": pipeline.put({ "op": "cleanup", "test": self.instance }) elif op == "cleanup": if self.device_testing: self.cleanup_device_testing_artifacts() else: self.cleanup_artifacts() def cleanup_artifacts(self, additional_keep=[]): logger.debug("Cleaning up {}".format(self.instance.build_dir)) allow = [ 'zephyr/.config', 'handler.log', 'build.log', 'device.log', 'recording.csv', ] allow += additional_keep allow = [os.path.join(self.instance.build_dir, file) for file in allow] for dirpath, dirnames, filenames in os.walk(self.instance.build_dir, topdown=False): for name in filenames: path = os.path.join(dirpath, name) if path not in allow: os.remove(path) # Remove empty directories and symbolic links to directories for dir in dirnames: path = os.path.join(dirpath, dir) if os.path.islink(path): os.remove(path) elif not os.listdir(path): os.rmdir(path) def cleanup_device_testing_artifacts(self): logger.debug("Cleaning up for Device Testing {}".format(self.instance.build_dir)) sanitizelist = [ 'CMakeCache.txt', 'zephyr/runners.yaml', ] keep = [ 'zephyr/zephyr.hex', 'zephyr/zephyr.bin', 'zephyr/zephyr.elf', ] keep += sanitizelist self.cleanup_artifacts(keep) # sanitize paths so files are relocatable for file in sanitizelist: file = os.path.join(self.instance.build_dir, file) with open(file, "rt") as fin: data = fin.read() data = data.replace(canonical_zephyr_base+"/", "") with open(file, "wt") as fin: fin.write(data) def report_out(self, results): total_to_do = results.total - results.skipped_configs total_tests_width = len(str(total_to_do)) results.done += 1 instance = self.instance if instance.status in ["error", "failed", "timeout", "flash_error"]: if instance.status == "error": results.error += 1 results.failed += 1 if self.verbose: status = Fore.RED + "FAILED " + Fore.RESET + instance.reason else: print("") logger.error( "{:<25} {:<50} {}FAILED{}: {}".format( instance.platform.name, instance.testcase.name, Fore.RED, Fore.RESET, instance.reason)) if not self.verbose: self.log_info_file(self.inline_logs) elif instance.status == "skipped": status = Fore.YELLOW + "SKIPPED" + Fore.RESET elif instance.status == "passed": status = Fore.GREEN + "PASSED" + Fore.RESET else: logger.debug(f"Unknown status = {instance.status}") status = Fore.YELLOW + "UNKNOWN" + Fore.RESET if self.verbose: if self.cmake_only: more_info = "cmake" elif instance.status == "skipped": more_info = instance.reason else: if instance.handler and instance.run: more_info = instance.handler.type_str htime = instance.handler.duration if htime: more_info += " {:.3f}s".format(htime) else: more_info = "build" logger.info("{:>{}}/{} {:<25} {:<50} {} ({})".format( results.done, total_tests_width, total_to_do, instance.platform.name, instance.testcase.name, status, more_info)) if instance.status in ["error", "failed", "timeout"]: self.log_info_file(self.inline_logs) else: completed_perc = 0 if total_to_do > 0: completed_perc = int((float(results.done) / total_to_do) * 100) skipped = results.skipped_configs + results.skipped_runtime sys.stdout.write("\rINFO - Total complete: %s%4d/%4d%s %2d%% skipped: %s%4d%s, failed: %s%4d%s" % ( Fore.GREEN, results.done, total_to_do, Fore.RESET, completed_perc, Fore.YELLOW if skipped > 0 else Fore.RESET, skipped, Fore.RESET, Fore.RED if results.failed > 0 else Fore.RESET, results.failed, Fore.RESET ) ) sys.stdout.flush() def cmake(self): instance = self.instance args = self.testcase.extra_args[:] args += self.extra_args if instance.handler: args += instance.handler.args # merge overlay files into one variable def extract_overlays(args): re_overlay = re.compile('OVERLAY_CONFIG=(.*)') other_args = [] overlays = [] for arg in args: match = re_overlay.search(arg) if match: overlays.append(match.group(1).strip('\'"')) else: other_args.append(arg) args[:] = other_args return overlays overlays = extract_overlays(args) if os.path.exists(os.path.join(instance.build_dir, "twister", "testcase_extra.conf")): overlays.append(os.path.join(instance.build_dir, "twister", "testcase_extra.conf")) if overlays: args.append("OVERLAY_CONFIG=\"%s\"" % (" ".join(overlays))) res = self.run_cmake(args) return res def build(self): res = self.run_build(['--build', self.build_dir]) return res def run(self): instance = self.instance if instance.handler: if instance.handler.type_str == "device": instance.handler.suite = self.suite instance.handler.handle() sys.stdout.flush() class TestSuite(DisablePyTestCollectionMixin): config_re = re.compile('(CONFIG_[A-Za-z0-9_]+)[=]\"?([^\"]*)\"?$') dt_re = re.compile('([A-Za-z0-9_]+)[=]\"?([^\"]*)\"?$') tc_schema = scl.yaml_load( os.path.join(ZEPHYR_BASE, "scripts", "schemas", "twister", "testcase-schema.yaml")) quarantine_schema = scl.yaml_load( os.path.join(ZEPHYR_BASE, "scripts", "schemas", "twister", "quarantine-schema.yaml")) testcase_valid_keys = {"tags": {"type": "set", "required": False}, "type": {"type": "str", "default": "integration"}, "extra_args": {"type": "list"}, "extra_configs": {"type": "list"}, "build_only": {"type": "bool", "default": False}, "build_on_all": {"type": "bool", "default": False}, "skip": {"type": "bool", "default": False}, "slow": {"type": "bool", "default": False}, "timeout": {"type": "int", "default": 60}, "min_ram": {"type": "int", "default": 8}, "depends_on": {"type": "set"}, "min_flash": {"type": "int", "default": 32}, "arch_allow": {"type": "set"}, "arch_exclude": {"type": "set"}, "extra_sections": {"type": "list", "default": []}, "integration_platforms": {"type": "list", "default": []}, "platform_exclude": {"type": "set"}, "platform_allow": {"type": "set"}, "toolchain_exclude": {"type": "set"}, "toolchain_allow": {"type": "set"}, "filter": {"type": "str"}, "harness": {"type": "str"}, "harness_config": {"type": "map", "default": {}} } RELEASE_DATA = os.path.join(ZEPHYR_BASE, "scripts", "release", "twister_last_release.csv") SAMPLE_FILENAME = 'sample.yaml' TESTCASE_FILENAME = 'testcase.yaml' def __init__(self, board_root_list=[], testcase_roots=[], outdir=None): self.roots = testcase_roots if not isinstance(board_root_list, list): self.board_roots = [board_root_list] else: self.board_roots = board_root_list # Testsuite Options self.coverage_platform = [] self.build_only = False self.cmake_only = False self.cleanup = False self.enable_slow = False self.device_testing = False self.fixtures = [] self.enable_coverage = False self.enable_ubsan = False self.enable_lsan = False self.enable_asan = False self.enable_valgrind = False self.extra_args = [] self.inline_logs = False self.enable_sizes_report = False self.west_flash = None self.west_runner = None self.generator = None self.generator_cmd = None self.warnings_as_errors = True self.overflow_as_errors = False self.quarantine_verify = False # Keep track of which test cases we've filtered out and why self.testcases = {} self.quarantine = {} self.platforms = [] self.platform_names = [] self.selected_platforms = [] self.filtered_platforms = [] self.default_platforms = [] self.outdir = os.path.abspath(outdir) self.discards = {} self.load_errors = 0 self.instances = dict() self.total_platforms = 0 self.start_time = 0 self.duration = 0 self.warnings = 0 # hardcoded for now self.duts = [] # run integration tests only self.integration = False # used during creating shorter build paths self.link_dir_counter = 0 self.pipeline = None self.version = "NA" def check_zephyr_version(self): try: subproc = subprocess.run(["git", "describe", "--abbrev=12"], stdout=subprocess.PIPE, universal_newlines=True, cwd=ZEPHYR_BASE) if subproc.returncode == 0: self.version = subproc.stdout.strip() logger.info(f"Zephyr version: {self.version}") except OSError: logger.info("Cannot read zephyr version.") def get_platform_instances(self, platform): filtered_dict = {k:v for k,v in self.instances.items() if k.startswith(platform + os.sep)} return filtered_dict def config(self): logger.info("coverage platform: {}".format(self.coverage_platform)) # Debug Functions @staticmethod def info(what): sys.stdout.write(what + "\n") sys.stdout.flush() def update_counting(self, results=None, initial=False): results.skipped_configs = 0 results.skipped_cases = 0 for instance in self.instances.values(): if initial: results.cases += len(instance.testcase.cases) if instance.status == 'skipped': results.skipped_configs += 1 results.skipped_cases += len(instance.testcase.cases) elif instance.status == "passed": results.passed += 1 for res in instance.results.values(): if res == 'SKIP': results.skipped_cases += 1 def compare_metrics(self, filename): # name, datatype, lower results better interesting_metrics = [("ram_size", int, True), ("rom_size", int, True)] if not os.path.exists(filename): logger.error("Cannot compare metrics, %s not found" % filename) return [] results = [] saved_metrics = {} with open(filename) as fp: cr = csv.DictReader(fp) for row in cr: d = {} for m, _, _ in interesting_metrics: d[m] = row[m] saved_metrics[(row["test"], row["platform"])] = d for instance in self.instances.values(): mkey = (instance.testcase.name, instance.platform.name) if mkey not in saved_metrics: continue sm = saved_metrics[mkey] for metric, mtype, lower_better in interesting_metrics: if metric not in instance.metrics: continue if sm[metric] == "": continue delta = instance.metrics.get(metric, 0) - mtype(sm[metric]) if delta == 0: continue results.append((instance, metric, instance.metrics.get(metric, 0), delta, lower_better)) return results def footprint_reports(self, report, show_footprint, all_deltas, footprint_threshold, last_metrics): if not report: return logger.debug("running footprint_reports") deltas = self.compare_metrics(report) warnings = 0 if deltas and show_footprint: for i, metric, value, delta, lower_better in deltas: if not all_deltas and ((delta < 0 and lower_better) or (delta > 0 and not lower_better)): continue percentage = 0 if value > delta: percentage = (float(delta) / float(value - delta)) if not all_deltas and (percentage < (footprint_threshold / 100.0)): continue logger.info("{:<25} {:<60} {}{}{}: {} {:<+4}, is now {:6} {:+.2%}".format( i.platform.name, i.testcase.name, Fore.YELLOW, "INFO" if all_deltas else "WARNING", Fore.RESET, metric, delta, value, percentage)) warnings += 1 if warnings: logger.warning("Deltas based on metrics from last %s" % ("release" if not last_metrics else "run")) def summary(self, results, unrecognized_sections): failed = 0 run = 0 for instance in self.instances.values(): if instance.status == "failed": failed += 1 elif instance.metrics.get("unrecognized") and not unrecognized_sections: logger.error("%sFAILED%s: %s has unrecognized binary sections: %s" % (Fore.RED, Fore.RESET, instance.name, str(instance.metrics.get("unrecognized", [])))) failed += 1 if instance.metrics.get('handler_time', None): run += 1 if results.total and results.total != results.skipped_configs: pass_rate = (float(results.passed) / float(results.total - results.skipped_configs)) else: pass_rate = 0 logger.info( "{}{} of {}{} test configurations passed ({:.2%}), {}{}{} failed, {} skipped with {}{}{} warnings in {:.2f} seconds".format( Fore.RED if failed else Fore.GREEN, results.passed, results.total - results.skipped_configs, Fore.RESET, pass_rate, Fore.RED if results.failed else Fore.RESET, results.failed, Fore.RESET, results.skipped_configs, Fore.YELLOW if self.warnings else Fore.RESET, self.warnings, Fore.RESET, self.duration)) self.total_platforms = len(self.platforms) # if we are only building, do not report about tests being executed. if self.platforms and not self.build_only: logger.info("In total {} test cases were executed, {} skipped on {} out of total {} platforms ({:02.2f}%)".format( results.cases - results.skipped_cases, results.skipped_cases, len(self.filtered_platforms), self.total_platforms, (100 * len(self.filtered_platforms) / len(self.platforms)) )) logger.info(f"{Fore.GREEN}{run}{Fore.RESET} test configurations executed on platforms, \ {Fore.RED}{results.total - run - results.skipped_configs}{Fore.RESET} test configurations were only built.") def save_reports(self, name, suffix, report_dir, no_update, release, only_failed, platform_reports, json_report): if not self.instances: return logger.info("Saving reports...") if name: report_name = name else: report_name = "twister" if report_dir: os.makedirs(report_dir, exist_ok=True) filename = os.path.join(report_dir, report_name) outdir = report_dir else: filename = os.path.join(self.outdir, report_name) outdir = self.outdir if suffix: filename = "{}_{}".format(filename, suffix) if not no_update: self.xunit_report(filename + ".xml", full_report=False, append=only_failed, version=self.version) self.xunit_report(filename + "_report.xml", full_report=True, append=only_failed, version=self.version) self.csv_report(filename + ".csv") if json_report: self.json_report(filename + ".json", append=only_failed, version=self.version) if platform_reports: self.target_report(outdir, suffix, append=only_failed) if self.discards: self.discard_report(filename + "_discard.csv") if release: self.csv_report(self.RELEASE_DATA) def add_configurations(self): for board_root in self.board_roots: board_root = os.path.abspath(board_root) logger.debug("Reading platform configuration files under %s..." % board_root) for file in glob.glob(os.path.join(board_root, "*", "*", "*.yaml")): try: platform = Platform() platform.load(file) if platform.name in [p.name for p in self.platforms]: logger.error(f"Duplicate platform {platform.name} in {file}") raise Exception(f"Duplicate platform identifier {platform.name} found") if platform.twister: self.platforms.append(platform) if platform.default: self.default_platforms.append(platform.name) except RuntimeError as e: logger.error("E: %s: can't load: %s" % (file, e)) self.load_errors += 1 self.platform_names = [p.name for p in self.platforms] def get_all_tests(self): tests = [] for _, tc in self.testcases.items(): for case in tc.cases: tests.append(case) return tests @staticmethod def get_toolchain(): toolchain_script = Path(ZEPHYR_BASE) / Path('cmake/modules/verify-toolchain.cmake') result = CMake.run_cmake_script([toolchain_script, "FORMAT=json"]) try: if result['returncode']: raise TwisterRuntimeError(f"E: {result["returnmsg"]}") except Exception as e: print(str(e)) sys.exit(2) toolchain = json.loads(result['stdout'])['ZEPHYR_TOOLCHAIN_VARIANT'] logger.info(f"Using '{toolchain}' toolchain.") return toolchain def add_testcases(self, testcase_filter=[]): for root in self.roots: root = os.path.abspath(root) logger.debug("Reading test case configuration files under %s..." % root) for dirpath, _, filenames in os.walk(root, topdown=True): if self.SAMPLE_FILENAME in filenames: filename = self.SAMPLE_FILENAME elif self.TESTCASE_FILENAME in filenames: filename = self.TESTCASE_FILENAME else: continue logger.debug("Found possible test case in " + dirpath) tc_path = os.path.join(dirpath, filename) try: parsed_data = TwisterConfigParser(tc_path, self.tc_schema) parsed_data.load() tc_path = os.path.dirname(tc_path) workdir = os.path.relpath(tc_path, root) for name in parsed_data.tests.keys(): tc = TestCase(root, workdir, name) tc_dict = parsed_data.get_test(name, self.testcase_valid_keys) tc.source_dir = tc_path tc.yamlfile = tc_path tc.type = tc_dict["type"] tc.tags = tc_dict["tags"] tc.extra_args = tc_dict["extra_args"] tc.extra_configs = tc_dict["extra_configs"] tc.arch_allow = tc_dict["arch_allow"] tc.arch_exclude = tc_dict["arch_exclude"] tc.skip = tc_dict["skip"] tc.platform_exclude = tc_dict["platform_exclude"] tc.platform_allow = tc_dict["platform_allow"] tc.toolchain_exclude = tc_dict["toolchain_exclude"] tc.toolchain_allow = tc_dict["toolchain_allow"] tc.tc_filter = tc_dict["filter"] tc.timeout = tc_dict["timeout"] tc.harness = tc_dict["harness"] tc.harness_config = tc_dict["harness_config"] if tc.harness == 'console' and not tc.harness_config: raise Exception('Harness config error: console harness defined without a configuration.') tc.build_only = tc_dict["build_only"] tc.build_on_all = tc_dict["build_on_all"] tc.slow = tc_dict["slow"] tc.min_ram = tc_dict["min_ram"] tc.depends_on = tc_dict["depends_on"] tc.min_flash = tc_dict["min_flash"] tc.extra_sections = tc_dict["extra_sections"] tc.integration_platforms = tc_dict["integration_platforms"] tc.parse_subcases(tc_path) if testcase_filter: if tc.name and tc.name in testcase_filter: self.testcases[tc.name] = tc else: self.testcases[tc.name] = tc except Exception as e: logger.error("%s: can't load (skipping): %s" % (tc_path, e)) self.load_errors += 1 return len(self.testcases) def get_platform(self, name): selected_platform = None for platform in self.platforms: if platform.name == name: selected_platform = platform break return selected_platform def load_quarantine(self, file): """ Loads quarantine list from the given yaml file. Creates a dictionary of all tests configurations (platform + scenario: comment) that shall be skipped due to quarantine """ # Load yaml into quarantine_yaml quarantine_yaml = scl.yaml_load_verify(file, self.quarantine_schema) # Create quarantine_list with a product of the listed # platforms and scenarios for each entry in quarantine yaml quarantine_list = [] for quar_dict in quarantine_yaml: if quar_dict['platforms'][0] == "all": plat = self.platform_names else: plat = quar_dict['platforms'] comment = quar_dict.get('comment', "NA") quarantine_list.append([{".".join([p, s]): comment} for p in plat for s in quar_dict['scenarios']]) # Flatten the quarantine_list quarantine_list = [it for sublist in quarantine_list for it in sublist] # Change quarantine_list into a dictionary for d in quarantine_list: self.quarantine.update(d) def load_from_file(self, file, filter_status=[], filter_platform=[]): try: with open(file, "r") as fp: cr = csv.DictReader(fp) instance_list = [] for row in cr: if row["status"] in filter_status: continue test = row["test"] platform = self.get_platform(row["platform"]) if filter_platform and platform.name not in filter_platform: continue instance = TestInstance(self.testcases[test], platform, self.outdir) if self.device_testing: tfilter = 'runnable' else: tfilter = 'buildable' instance.run = instance.check_runnable( self.enable_slow, tfilter, self.fixtures ) instance.create_overlay(platform, self.enable_asan, self.enable_ubsan, self.enable_coverage, self.coverage_platform) instance_list.append(instance) self.add_instances(instance_list) except KeyError as e: logger.error("Key error while parsing tests file.({})".format(str(e))) sys.exit(2) except FileNotFoundError as e: logger.error("Couldn't find input file with list of tests. ({})".format(e)) sys.exit(2) def apply_filters(self, **kwargs): toolchain = self.get_toolchain() discards = {} platform_filter = kwargs.get('platform') exclude_platform = kwargs.get('exclude_platform', []) testcase_filter = kwargs.get('run_individual_tests', []) arch_filter = kwargs.get('arch') tag_filter = kwargs.get('tag') exclude_tag = kwargs.get('exclude_tag') all_filter = kwargs.get('all') runnable = kwargs.get('runnable') force_toolchain = kwargs.get('force_toolchain') force_platform = kwargs.get('force_platform') emu_filter = kwargs.get('emulation_only') logger.debug("platform filter: " + str(platform_filter)) logger.debug(" arch_filter: " + str(arch_filter)) logger.debug(" tag_filter: " + str(tag_filter)) logger.debug(" exclude_tag: " + str(exclude_tag)) default_platforms = False emulation_platforms = False if all_filter: logger.info("Selecting all possible platforms per test case") # When --all used, any --platform arguments ignored platform_filter = [] elif not platform_filter and not emu_filter: logger.info("Selecting default platforms per test case") default_platforms = True elif emu_filter: logger.info("Selecting emulation platforms per test case") emulation_platforms = True if platform_filter: self.verify_platforms_existence(platform_filter, f"platform_filter") platforms = list(filter(lambda p: p.name in platform_filter, self.platforms)) elif emu_filter: platforms = list(filter(lambda p: p.simulation != 'na', self.platforms)) elif arch_filter: platforms = list(filter(lambda p: p.arch in arch_filter, self.platforms)) elif default_platforms: platforms = list(filter(lambda p: p.default, self.platforms)) else: platforms = self.platforms logger.info("Building initial testcase list...") for tc_name, tc in self.testcases.items(): if tc.build_on_all and not platform_filter: platform_scope = self.platforms elif tc.integration_platforms and self.integration: self.verify_platforms_existence( tc.integration_platforms, f"{tc_name} - integration_platforms") platform_scope = list(filter(lambda item: item.name in tc.integration_platforms, \ self.platforms)) else: platform_scope = platforms integration = self.integration and tc.integration_platforms # If there isn't any overlap between the platform_allow list and the platform_scope # we set the scope to the platform_allow list if tc.platform_allow and not platform_filter and not integration: self.verify_platforms_existence( tc.platform_allow, f"{tc_name} - platform_allow") a = set(platform_scope) b = set(filter(lambda item: item.name in tc.platform_allow, self.platforms)) c = a.intersection(b) if not c: platform_scope = list(filter(lambda item: item.name in tc.platform_allow, \ self.platforms)) # list of instances per testcase, aka configurations. instance_list = [] for plat in platform_scope: instance = TestInstance(tc, plat, self.outdir) if runnable: tfilter = 'runnable' else: tfilter = 'buildable' instance.run = instance.check_runnable( self.enable_slow, tfilter, self.fixtures ) for t in tc.cases: instance.results[t] = None if runnable and self.duts: for h in self.duts: if h.platform == plat.name: if tc.harness_config.get('fixture') in h.fixtures: instance.run = True if not force_platform and plat.name in exclude_platform: discards[instance] = discards.get(instance, "Platform is excluded on command line.") if (plat.arch == "unit") != (tc.type == "unit"): # Discard silently continue if runnable and not instance.run: discards[instance] = discards.get(instance, "Not runnable on device") if self.integration and tc.integration_platforms and plat.name not in tc.integration_platforms: discards[instance] = discards.get(instance, "Not part of integration platforms") if tc.skip: discards[instance] = discards.get(instance, "Skip filter") if tag_filter and not tc.tags.intersection(tag_filter): discards[instance] = discards.get(instance, "Command line testcase tag filter") if exclude_tag and tc.tags.intersection(exclude_tag): discards[instance] = discards.get(instance, "Command line testcase exclude filter") if testcase_filter and tc_name not in testcase_filter: discards[instance] = discards.get(instance, "Testcase name filter") if arch_filter and plat.arch not in arch_filter: discards[instance] = discards.get(instance, "Command line testcase arch filter") if not force_platform: if tc.arch_allow and plat.arch not in tc.arch_allow: discards[instance] = discards.get(instance, "Not in test case arch allow list") if tc.arch_exclude and plat.arch in tc.arch_exclude: discards[instance] = discards.get(instance, "In test case arch exclude") if tc.platform_exclude and plat.name in tc.platform_exclude: discards[instance] = discards.get(instance, "In test case platform exclude") if tc.toolchain_exclude and toolchain in tc.toolchain_exclude: discards[instance] = discards.get(instance, "In test case toolchain exclude") if platform_filter and plat.name not in platform_filter: discards[instance] = discards.get(instance, "Command line platform filter") if tc.platform_allow and plat.name not in tc.platform_allow: discards[instance] = discards.get(instance, "Not in testcase platform allow list") if tc.toolchain_allow and toolchain not in tc.toolchain_allow: discards[instance] = discards.get(instance, "Not in testcase toolchain allow list") if not plat.env_satisfied: discards[instance] = discards.get(instance, "Environment ({}) not satisfied".format(", ".join(plat.env))) if not force_toolchain \ and toolchain and (toolchain not in plat.supported_toolchains) \ and "host" not in plat.supported_toolchains \ and tc.type != 'unit': discards[instance] = discards.get(instance, "Not supported by the toolchain") if plat.ram < tc.min_ram: discards[instance] = discards.get(instance, "Not enough RAM") if tc.depends_on: dep_intersection = tc.depends_on.intersection(set(plat.supported)) if dep_intersection != set(tc.depends_on): discards[instance] = discards.get(instance, "No hardware support") if plat.flash < tc.min_flash: discards[instance] = discards.get(instance, "Not enough FLASH") if set(plat.ignore_tags) & tc.tags: discards[instance] = discards.get(instance, "Excluded tags per platform (exclude_tags)") if plat.only_tags and not set(plat.only_tags) & tc.tags: discards[instance] = discards.get(instance, "Excluded tags per platform (only_tags)") test_configuration = ".".join([instance.platform.name, instance.testcase.id]) # skip quarantined tests if test_configuration in self.quarantine and not self.quarantine_verify: discards[instance] = discards.get(instance, f"Quarantine: {self.quarantine[test_configuration]}") # run only quarantined test to verify their statuses (skip everything else) if self.quarantine_verify and test_configuration not in self.quarantine: discards[instance] = discards.get(instance, "Not under quarantine") # if nothing stopped us until now, it means this configuration # needs to be added. instance_list.append(instance) # no configurations, so jump to next testcase if not instance_list: continue # if twister was launched with no platform options at all, we # take all default platforms if default_platforms and not tc.build_on_all and not integration: if tc.platform_allow: a = set(self.default_platforms) b = set(tc.platform_allow) c = a.intersection(b) if c: aa = list(filter(lambda tc: tc.platform.name in c, instance_list)) self.add_instances(aa) else: self.add_instances(instance_list) else: instances = list(filter(lambda tc: tc.platform.default, instance_list)) self.add_instances(instances) elif integration: instances = list(filter(lambda item: item.platform.name in tc.integration_platforms, instance_list)) self.add_instances(instances) elif emulation_platforms: self.add_instances(instance_list) for instance in list(filter(lambda inst: not inst.platform.simulation != 'na', instance_list)): discards[instance] = discards.get(instance, "Not an emulated platform") else: self.add_instances(instance_list) for _, case in self.instances.items(): case.create_overlay(case.platform, self.enable_asan, self.enable_ubsan, self.enable_coverage, self.coverage_platform) self.discards = discards self.selected_platforms = set(p.platform.name for p in self.instances.values()) remove_from_discards = [] # configurations to be removed from discards. for instance in self.discards: instance.reason = self.discards[instance] # If integration mode is on all skips on integration_platforms are treated as errors. if self.integration and instance.platform.name in instance.testcase.integration_platforms \ and "Quarantine" not in instance.reason: instance.status = "error" instance.reason += " but is one of the integration platforms" instance.fill_results_by_status() self.instances[instance.name] = instance # Such configuration has to be removed from discards to make sure it won't get skipped remove_from_discards.append(instance) else: instance.status = "skipped" instance.fill_results_by_status() self.filtered_platforms = set(p.platform.name for p in self.instances.values() if p.status != "skipped" ) # Remove from discards configururations that must not be discarded (e.g. integration_platforms when --integration was used) for instance in remove_from_discards: del self.discards[instance] return discards def add_instances(self, instance_list): for instance in instance_list: self.instances[instance.name] = instance @staticmethod def calc_one_elf_size(instance): if instance.status not in ["error", "failed", "skipped"]: if instance.platform.type != "native": size_calc = instance.calculate_sizes() instance.metrics["ram_size"] = size_calc.get_ram_size() instance.metrics["rom_size"] = size_calc.get_rom_size() instance.metrics["unrecognized"] = size_calc.unrecognized_sections() else: instance.metrics["ram_size"] = 0 instance.metrics["rom_size"] = 0 instance.metrics["unrecognized"] = [] instance.metrics["handler_time"] = instance.handler.duration if instance.handler else 0 def add_tasks_to_queue(self, pipeline, build_only=False, test_only=False): for instance in self.instances.values(): if build_only: instance.run = False if instance.status not in ['passed', 'skipped', 'error']: logger.debug(f"adding {instance.name}") instance.status = None if test_only and instance.run: pipeline.put({"op": "run", "test": instance}) else: pipeline.put({"op": "cmake", "test": instance}) # If the instance got 'error' status before, proceed to the report stage if instance.status == "error": pipeline.put({"op": "report", "test": instance}) def pipeline_mgr(self, pipeline, done_queue, lock, results): while True: try: task = pipeline.get_nowait() except queue.Empty: break else: test = task['test'] pb = ProjectBuilder(self, test, lsan=self.enable_lsan, asan=self.enable_asan, ubsan=self.enable_ubsan, coverage=self.enable_coverage, extra_args=self.extra_args, device_testing=self.device_testing, cmake_only=self.cmake_only, cleanup=self.cleanup, valgrind=self.enable_valgrind, inline_logs=self.inline_logs, generator=self.generator, generator_cmd=self.generator_cmd, verbose=self.verbose, warnings_as_errors=self.warnings_as_errors, overflow_as_errors=self.overflow_as_errors ) pb.process(pipeline, done_queue, task, lock, results) return True def execute(self, pipeline, done, results): lock = Lock() logger.info("Adding tasks to the queue...") self.add_tasks_to_queue(pipeline, self.build_only, self.test_only) logger.info("Added initial list of jobs to queue") processes = [] for job in range(self.jobs): logger.debug(f"Launch process {job}") p = Process(target=self.pipeline_mgr, args=(pipeline, done, lock, results, )) processes.append(p) p.start() try: for p in processes: p.join() except KeyboardInterrupt: logger.info("Execution interrupted") for p in processes: p.terminate() # FIXME: This needs to move out. if self.enable_size_report and not self.cmake_only: # Parallelize size calculation executor = concurrent.futures.ThreadPoolExecutor(self.jobs) futures = [executor.submit(self.calc_one_elf_size, instance) for instance in self.instances.values()] concurrent.futures.wait(futures) else: for instance in self.instances.values(): instance.metrics["ram_size"] = 0 instance.metrics["rom_size"] = 0 instance.metrics["handler_time"] = instance.handler.duration if instance.handler else 0 instance.metrics["unrecognized"] = [] return results def discard_report(self, filename): try: if not self.discards: raise TwisterRuntimeError("apply_filters() hasn't been run!") except Exception as e: logger.error(str(e)) sys.exit(2) with open(filename, "wt") as csvfile: fieldnames = ["test", "arch", "platform", "reason"] cw = csv.DictWriter(csvfile, fieldnames, lineterminator=os.linesep) cw.writeheader() for instance, reason in sorted(self.discards.items()): rowdict = {"test": instance.testcase.name, "arch": instance.platform.arch, "platform": instance.platform.name, "reason": reason} cw.writerow(rowdict) def target_report(self, outdir, suffix, append=False): platforms = {inst.platform.name for _, inst in self.instances.items()} for platform in platforms: if suffix: filename = os.path.join(outdir,"{}_{}.xml".format(platform, suffix)) else: filename = os.path.join(outdir,"{}.xml".format(platform)) self.xunit_report(filename, platform, full_report=True, append=append, version=self.version) @staticmethod def process_log(log_file): filtered_string = "" if os.path.exists(log_file): with open(log_file, "rb") as f: log = f.read().decode("utf-8") filtered_string = ''.join(filter(lambda x: x in string.printable, log)) return filtered_string def xunit_report(self, filename, platform=None, full_report=False, append=False, version="NA"): total = 0 fails = passes = errors = skips = 0 if platform: selected = [platform] logger.info(f"Writing target report for {platform}...") else: logger.info(f"Writing xunit report {filename}...") selected = self.selected_platforms if os.path.exists(filename) and append: tree = ET.parse(filename) eleTestsuites = tree.getroot() else: eleTestsuites = ET.Element('testsuites') for p in selected: inst = self.get_platform_instances(p) fails = 0 passes = 0 errors = 0 skips = 0 duration = 0 for _, instance in inst.items(): handler_time = instance.metrics.get('handler_time', 0) duration += handler_time if full_report and instance.run: for k in instance.results.keys(): if instance.results[k] == 'PASS': passes += 1 elif instance.results[k] == 'BLOCK': errors += 1 elif instance.results[k] == 'SKIP' or instance.status in ['skipped']: skips += 1 else: fails += 1 else: if instance.status in ["error", "failed", "timeout", "flash_error"]: if instance.reason in ['build_error', 'handler_crash']: errors += 1 else: fails += 1 elif instance.status == 'skipped': skips += 1 elif instance.status == 'passed': passes += 1 else: if instance.status: logger.error(f"{instance.name}: Unknown status {instance.status}") else: logger.error(f"{instance.name}: No status") total = (errors + passes + fails + skips) # do not produce a report if no tests were actually run (only built) if total == 0: continue run = p eleTestsuite = None # When we re-run the tests, we re-use the results and update only with # the newly run tests. if os.path.exists(filename) and append: ts = eleTestsuites.findall(f'testsuite/[@name="{p}"]') if ts: eleTestsuite = ts[0] eleTestsuite.attrib['failures'] = "%d" % fails eleTestsuite.attrib['errors'] = "%d" % errors eleTestsuite.attrib['skipped'] = "%d" % skips else: logger.info(f"Did not find any existing results for {p}") eleTestsuite = ET.SubElement(eleTestsuites, 'testsuite', name=run, time="%f" % duration, tests="%d" % (total), failures="%d" % fails, errors="%d" % (errors), skipped="%s" % (skips)) eleTSPropetries = ET.SubElement(eleTestsuite, 'properties') # Multiple 'property' can be added to 'properties' # differing by name and value ET.SubElement(eleTSPropetries, 'property', name="version", value=version) else: eleTestsuite = ET.SubElement(eleTestsuites, 'testsuite', name=run, time="%f" % duration, tests="%d" % (total), failures="%d" % fails, errors="%d" % (errors), skipped="%s" % (skips)) eleTSPropetries = ET.SubElement(eleTestsuite, 'properties') # Multiple 'property' can be added to 'properties' # differing by name and value ET.SubElement(eleTSPropetries, 'property', name="version", value=version) for _, instance in inst.items(): if full_report: tname = os.path.basename(instance.testcase.name) else: tname = instance.testcase.id handler_time = instance.metrics.get('handler_time', 0) if full_report: for k in instance.results.keys(): # remove testcases that are being re-run from exiting reports for tc in eleTestsuite.findall(f'testcase/[@name="{k}"]'): eleTestsuite.remove(tc) classname = ".".join(tname.split(".")[:2]) eleTestcase = ET.SubElement( eleTestsuite, 'testcase', classname=classname, name="%s" % (k), time="%f" % handler_time) if instance.results[k] in ['FAIL', 'BLOCK'] or \ (not instance.run and instance.status in ["error", "failed", "timeout"]): if instance.results[k] == 'FAIL': el = ET.SubElement( eleTestcase, 'failure', type="failure", message="failed") else: el = ET.SubElement( eleTestcase, 'error', type="failure", message=instance.reason) log_root = os.path.join(self.outdir, instance.platform.name, instance.testcase.name) log_file = os.path.join(log_root, "handler.log") el.text = self.process_log(log_file) elif instance.results[k] == 'PASS' \ or (not instance.run and instance.status in ["passed"]): pass elif instance.results[k] == 'SKIP' or (instance.status in ["skipped"]): el = ET.SubElement(eleTestcase, 'skipped', type="skipped", message=instance.reason) else: el = ET.SubElement( eleTestcase, 'error', type="error", message=f"{instance.reason}") else: if platform: classname = ".".join(instance.testcase.name.split(".")[:2]) else: classname = p + ":" + ".".join(instance.testcase.name.split(".")[:2]) # remove testcases that are being re-run from exiting reports for tc in eleTestsuite.findall(f'testcase/[@classname="{classname}"][@name="{instance.testcase.name}"]'): eleTestsuite.remove(tc) eleTestcase = ET.SubElement(eleTestsuite, 'testcase', classname=classname, name="%s" % (instance.testcase.name), time="%f" % handler_time) if instance.status in ["error", "failed", "timeout", "flash_error"]: failure = ET.SubElement( eleTestcase, 'failure', type="failure", message=instance.reason) log_root = ("%s/%s/%s" % (self.outdir, instance.platform.name, instance.testcase.name)) bl = os.path.join(log_root, "build.log") hl = os.path.join(log_root, "handler.log") log_file = bl if instance.reason != 'Build error': if os.path.exists(hl): log_file = hl else: log_file = bl failure.text = self.process_log(log_file) elif instance.status == "skipped": ET.SubElement(eleTestcase, 'skipped', type="skipped", message="Skipped") result = ET.tostring(eleTestsuites) with open(filename, 'wb') as report: report.write(result) return fails, passes, errors, skips def csv_report(self, filename): with open(filename, "wt") as csvfile: fieldnames = ["test", "arch", "platform", "status", "extra_args", "handler", "handler_time", "ram_size", "rom_size"] cw = csv.DictWriter(csvfile, fieldnames, lineterminator=os.linesep) cw.writeheader() for instance in self.instances.values(): rowdict = {"test": instance.testcase.name, "arch": instance.platform.arch, "platform": instance.platform.name, "extra_args": " ".join(instance.testcase.extra_args), "handler": instance.platform.simulation} rowdict["status"] = instance.status if instance.status not in ["error", "failed", "timeout"]: if instance.handler: rowdict["handler_time"] = instance.metrics.get("handler_time", 0) ram_size = instance.metrics.get("ram_size", 0) rom_size = instance.metrics.get("rom_size", 0) rowdict["ram_size"] = ram_size rowdict["rom_size"] = rom_size cw.writerow(rowdict) def json_report(self, filename, append=False, version="NA"): logger.info(f"Writing JSON report {filename}") report = {} selected = self.selected_platforms report["environment"] = {"os": os.name, "zephyr_version": version, "toolchain": self.get_toolchain() } json_data = {} if os.path.exists(filename) and append: with open(filename, 'r') as json_file: json_data = json.load(json_file) suites = json_data.get("testsuites", []) if suites: suite = suites[0] testcases = suite.get("testcases", []) else: suite = {} testcases = [] for p in selected: inst = self.get_platform_instances(p) for _, instance in inst.items(): testcase = {} handler_log = os.path.join(instance.build_dir, "handler.log") build_log = os.path.join(instance.build_dir, "build.log") device_log = os.path.join(instance.build_dir, "device.log") handler_time = instance.metrics.get('handler_time', 0) ram_size = instance.metrics.get ("ram_size", 0) rom_size = instance.metrics.get("rom_size",0) for k in instance.results.keys(): testcases = list(filter(lambda d: not (d.get('testcase') == k and d.get('platform') == p), testcases )) testcase = {"testcase": k, "arch": instance.platform.arch, "platform": p, } if ram_size: testcase["ram_size"] = ram_size if rom_size: testcase["rom_size"] = rom_size if instance.results[k] in ["SKIP"] or instance.status == 'skipped': testcase["status"] = "skipped" testcase["reason"] = instance.reason elif instance.results[k] in ["PASS"] or instance.status == 'passed': testcase["status"] = "passed" if instance.handler: testcase["execution_time"] = handler_time elif instance.results[k] in ['FAIL', 'BLOCK'] or instance.status in ["error", "failed", "timeout", "flash_error"]: testcase["status"] = "failed" testcase["reason"] = instance.reason testcase["execution_time"] = handler_time if os.path.exists(handler_log): testcase["test_output"] = self.process_log(handler_log) elif os.path.exists(device_log): testcase["device_log"] = self.process_log(device_log) else: testcase["build_log"] = self.process_log(build_log) testcases.append(testcase) suites = [ {"testcases": testcases} ] report["testsuites"] = suites with open(filename, "wt") as json_file: json.dump(report, json_file, indent=4, separators=(',',':')) def get_testcase(self, identifier): results = [] for _, tc in self.testcases.items(): for case in tc.cases: if case == identifier: results.append(tc) return results def verify_platforms_existence(self, platform_names_to_verify, log_info=""): """ Verify if platform name (passed by --platform option, or in yaml file as platform_allow or integration_platforms options) is correct. If not - log and raise error. """ for platform in platform_names_to_verify: if platform in self.platform_names: break else: logger.error(f"{log_info} - unrecognized platform - {platform}") sys.exit(2) def create_build_dir_links(self): """ Iterate through all no-skipped instances in suite and create links for each one build directories. Those links will be passed in the next steps to the CMake command. """ links_dir_name = "twister_links" # folder for all links links_dir_path = os.path.join(self.outdir, links_dir_name) if not os.path.exists(links_dir_path): os.mkdir(links_dir_path) for instance in self.instances.values(): if instance.status != "skipped": self._create_build_dir_link(links_dir_path, instance) def _create_build_dir_link(self, links_dir_path, instance): """ Create build directory with original "long" path. Next take shorter path and link them with original path - create link. At the end replace build_dir to created link. This link will be passed to CMake command. This action helps to limit path length which can be significant during building by CMake on Windows OS. """ os.makedirs(instance.build_dir, exist_ok=True) link_name = f"test_{self.link_dir_counter}" link_path = os.path.join(links_dir_path, link_name) if os.name == "nt": # if OS is Windows command = ["mklink", "/J", f"{link_path}", f"{instance.build_dir}"] subprocess.call(command, shell=True) else: # for Linux and MAC OS os.symlink(instance.build_dir, link_path) # Here original build directory is replaced with symbolic link. It will # be passed to CMake command instance.build_dir = link_path self.link_dir_counter += 1 class CoverageTool: """ Base class for every supported coverage tool """ def __init__(self): self.gcov_tool = None self.base_dir = None @staticmethod def factory(tool): if tool == 'lcov': t = Lcov() elif tool == 'gcovr': t = Gcovr() else: logger.error("Unsupported coverage tool specified: {}".format(tool)) return None logger.debug(f"Select {tool} as the coverage tool...") return t @staticmethod def retrieve_gcov_data(input_file): logger.debug("Working on %s" % input_file) extracted_coverage_info = {} capture_data = False capture_complete = False with open(input_file, 'r') as fp: for line in fp.readlines(): if re.search("GCOV_COVERAGE_DUMP_START", line): capture_data = True continue if re.search("GCOV_COVERAGE_DUMP_END", line): capture_complete = True break # Loop until the coverage data is found. if not capture_data: continue if line.startswith("*"): sp = line.split("<") if len(sp) > 1: # Remove the leading delimiter "*" file_name = sp[0][1:] # Remove the trailing new line char hex_dump = sp[1][:-1] else: continue else: continue extracted_coverage_info.update({file_name: hex_dump}) if not capture_data: capture_complete = True return {'complete': capture_complete, 'data': extracted_coverage_info} @staticmethod def create_gcda_files(extracted_coverage_info): logger.debug("Generating gcda files") for filename, hexdump_val in extracted_coverage_info.items(): # if kobject_hash is given for coverage gcovr fails # hence skipping it problem only in gcovr v4.1 if "kobject_hash" in filename: filename = (filename[:-4]) + "gcno" try: os.remove(filename) except Exception: pass continue with open(filename, 'wb') as fp: fp.write(bytes.fromhex(hexdump_val)) def generate(self, outdir): for filename in glob.glob("%s/**/handler.log" % outdir, recursive=True): gcov_data = self.__class__.retrieve_gcov_data(filename) capture_complete = gcov_data['complete'] extracted_coverage_info = gcov_data['data'] if capture_complete: self.__class__.create_gcda_files(extracted_coverage_info) logger.debug("Gcov data captured: {}".format(filename)) else: logger.error("Gcov data capture incomplete: {}".format(filename)) with open(os.path.join(outdir, "coverage.log"), "a") as coveragelog: ret = self._generate(outdir, coveragelog) if ret == 0: logger.info("HTML report generated: {}".format( os.path.join(outdir, "coverage", "index.html"))) class Lcov(CoverageTool): def __init__(self): super().__init__() self.ignores = [] def add_ignore_file(self, pattern): self.ignores.append('*' + pattern + '*') def add_ignore_directory(self, pattern): self.ignores.append('*/' + pattern + '/*') def _generate(self, outdir, coveragelog): coveragefile = os.path.join(outdir, "coverage.info") ztestfile = os.path.join(outdir, "ztest.info") cmd = ["lcov", "--gcov-tool", self.gcov_tool, "--capture", "--directory", outdir, "--rc", "lcov_branch_coverage=1", "--output-file", coveragefile] cmd_str = " ".join(cmd) logger.debug(f"Running {cmd_str}...") subprocess.call(cmd, stdout=coveragelog) # We want to remove tests/* and tests/ztest/test/* but save tests/ztest subprocess.call(["lcov", "--gcov-tool", self.gcov_tool, "--extract", coveragefile, os.path.join(self.base_dir, "tests", "ztest", "*"), "--output-file", ztestfile, "--rc", "lcov_branch_coverage=1"], stdout=coveragelog) if os.path.exists(ztestfile) and os.path.getsize(ztestfile) > 0: subprocess.call(["lcov", "--gcov-tool", self.gcov_tool, "--remove", ztestfile, os.path.join(self.base_dir, "tests/ztest/test/*"), "--output-file", ztestfile, "--rc", "lcov_branch_coverage=1"], stdout=coveragelog) files = [coveragefile, ztestfile] else: files = [coveragefile] for i in self.ignores: subprocess.call( ["lcov", "--gcov-tool", self.gcov_tool, "--remove", coveragefile, i, "--output-file", coveragefile, "--rc", "lcov_branch_coverage=1"], stdout=coveragelog) # The --ignore-errors source option is added to avoid it exiting due to # samples/application_development/external_lib/ return subprocess.call(["genhtml", "--legend", "--branch-coverage", "--ignore-errors", "source", "-output-directory", os.path.join(outdir, "coverage")] + files, stdout=coveragelog) class Gcovr(CoverageTool): def __init__(self): super().__init__() self.ignores = [] def add_ignore_file(self, pattern): self.ignores.append('.*' + pattern + '.*') def add_ignore_directory(self, pattern): self.ignores.append(".*/" + pattern + '/.*') @staticmethod def _interleave_list(prefix, list): tuple_list = [(prefix, item) for item in list] return [item for sublist in tuple_list for item in sublist] def _generate(self, outdir, coveragelog): coveragefile = os.path.join(outdir, "coverage.json") ztestfile = os.path.join(outdir, "ztest.json") excludes = Gcovr._interleave_list("-e", self.ignores) # We want to remove tests/* and tests/ztest/test/* but save tests/ztest cmd = ["gcovr", "-r", self.base_dir, "--gcov-executable", self.gcov_tool, "-e", "tests/*"] + excludes + ["--json", "-o", coveragefile, outdir] cmd_str = " ".join(cmd) logger.debug(f"Running {cmd_str}...") subprocess.call(cmd, stdout=coveragelog) subprocess.call(["gcovr", "-r", self.base_dir, "--gcov-executable", self.gcov_tool, "-f", "tests/ztest", "-e", "tests/ztest/test/*", "--json", "-o", ztestfile, outdir], stdout=coveragelog) if os.path.exists(ztestfile) and os.path.getsize(ztestfile) > 0: files = [coveragefile, ztestfile] else: files = [coveragefile] subdir = os.path.join(outdir, "coverage") os.makedirs(subdir, exist_ok=True) tracefiles = self._interleave_list("--add-tracefile", files) return subprocess.call(["gcovr", "-r", self.base_dir, "--html", "--html-details"] + tracefiles + ["-o", os.path.join(subdir, "index.html")], stdout=coveragelog) class DUT(object): def __init__(self, id=None, serial=None, serial_baud=None, platform=None, product=None, serial_pty=None, connected=False, pre_script=None, post_script=None, post_flash_script=None, runner=None): self.serial = serial self.baud = serial_baud or 115200 self.platform = platform self.serial_pty = serial_pty self._counter = Value("i", 0) self._available = Value("i", 1) self.connected = connected self.pre_script = pre_script self.id = id self.product = product self.runner = runner self.fixtures = [] self.post_flash_script = post_flash_script self.post_script = post_script self.pre_script = pre_script self.probe_id = None self.notes = None self.lock = Lock() self.match = False @property def available(self): with self._available.get_lock(): return self._available.value @available.setter def available(self, value): with self._available.get_lock(): self._available.value = value @property def counter(self): with self._counter.get_lock(): return self._counter.value @counter.setter def counter(self, value): with self._counter.get_lock(): self._counter.value = value def to_dict(self): d = {} exclude = ['_available', '_counter', 'match'] v = vars(self) for k in v.keys(): if k not in exclude and v[k]: d[k] = v[k] return d def __repr__(self): return f"<{self.platform} ({self.product}) on {self.serial}>" class HardwareMap: schema_path = os.path.join(ZEPHYR_BASE, "scripts", "schemas", "twister", "hwmap-schema.yaml") manufacturer = [ 'ARM', 'SEGGER', 'MBED', 'STMicroelectronics', 'Atmel Corp.', 'Texas Instruments', 'Silicon Labs', 'NXP Semiconductors', 'Microchip Technology Inc.', 'FTDI', 'Digilent' ] runner_mapping = { 'pyocd': [ 'DAPLink CMSIS-DAP', 'MBED CMSIS-DAP' ], 'jlink': [ 'J-Link', 'J-Link OB' ], 'openocd': [ 'STM32 STLink', '^XDS110.*', 'STLINK-V3' ], 'dediprog': [ 'TTL232R-3V3', 'MCP2200 USB Serial Port Emulator' ] } def __init__(self): self.detected = [] self.duts = [] def add_device(self, serial, platform, pre_script, is_pty, baud=None): device = DUT(platform=platform, connected=True, pre_script=pre_script, serial_baud=baud) if is_pty: device.serial_pty = serial else: device.serial = serial self.duts.append(device) def load(self, map_file): hwm_schema = scl.yaml_load(self.schema_path) duts = scl.yaml_load_verify(map_file, hwm_schema) for dut in duts: pre_script = dut.get('pre_script') post_script = dut.get('post_script') post_flash_script = dut.get('post_flash_script') platform = dut.get('platform') id = dut.get('id') runner = dut.get('runner') serial = dut.get('serial') baud = dut.get('baud', None) product = dut.get('product') fixtures = dut.get('fixtures', []) new_dut = DUT(platform=platform, product=product, runner=runner, id=id, serial=serial, serial_baud=baud, connected=serial is not None, pre_script=pre_script, post_script=post_script, post_flash_script=post_flash_script) new_dut.fixtures = fixtures new_dut.counter = 0 self.duts.append(new_dut) def scan(self, persistent=False): from serial.tools import list_ports if persistent and platform.system() == 'Linux': # On Linux, /dev/serial/by-id provides symlinks to # '/dev/ttyACMx' nodes using names which are unique as # long as manufacturers fill out USB metadata nicely. # # This creates a map from '/dev/ttyACMx' device nodes # to '/dev/serial/by-id/usb-...' symlinks. The symlinks # go into the hardware map because they stay the same # even when the user unplugs / replugs the device. # # Some inexpensive USB/serial adapters don't result # in unique names here, though, so use of this feature # requires explicitly setting persistent=True. by_id = Path('/dev/serial/by-id') def readlink(link): return str((by_id / link).resolve()) persistent_map = {readlink(link): str(link) for link in by_id.iterdir()} else: persistent_map = {} serial_devices = list_ports.comports() logger.info("Scanning connected hardware...") for d in serial_devices: if d.manufacturer in self.manufacturer: # TI XDS110 can have multiple serial devices for a single board # assume endpoint 0 is the serial, skip all others if d.manufacturer == 'Texas Instruments' and not d.location.endswith('0'): continue s_dev = DUT(platform="unknown", id=d.serial_number, serial=persistent_map.get(d.device, d.device), product=d.product, runner='unknown', connected=True) for runner, _ in self.runner_mapping.items(): products = self.runner_mapping.get(runner) if d.product in products: s_dev.runner = runner continue # Try regex matching for p in products: if re.match(p, d.product): s_dev.runner = runner s_dev.connected = True s_dev.lock = None self.detected.append(s_dev) else: logger.warning("Unsupported device (%s): %s" % (d.manufacturer, d)) def save(self, hwm_file): # use existing map self.detected.sort(key=lambda x: x.serial or '') if os.path.exists(hwm_file): with open(hwm_file, 'r') as yaml_file: hwm = yaml.load(yaml_file, Loader=SafeLoader) if hwm: hwm.sort(key=lambda x: x['serial'] or '') # disconnect everything for h in hwm: h['connected'] = False h['serial'] = None for _detected in self.detected: for h in hwm: if _detected.id == h['id'] and _detected.product == h['product'] and not _detected.match: h['connected'] = True h['serial'] = _detected.serial _detected.match = True new_duts = list(filter(lambda d: not d.match, self.detected)) new = [] for d in new_duts: new.append(d.to_dict()) if hwm: hwm = hwm + new else: hwm = new with open(hwm_file, 'w') as yaml_file: yaml.dump(hwm, yaml_file, Dumper=Dumper, default_flow_style=False) self.load(hwm_file) logger.info("Registered devices:") self.dump() else: # create new file dl = [] for _connected in self.detected: platform = _connected.platform id = _connected.id runner = _connected.runner serial = _connected.serial product = _connected.product d = { 'platform': platform, 'id': id, 'runner': runner, 'serial': serial, 'product': product, 'connected': _connected.connected } dl.append(d) with open(hwm_file, 'w') as yaml_file: yaml.dump(dl, yaml_file, Dumper=Dumper, default_flow_style=False) logger.info("Detected devices:") self.dump(detected=True) def dump(self, filtered=[], header=[], connected_only=False, detected=False): print("") table = [] if detected: to_show = self.detected else: to_show = self.duts if not header: header = ["Platform", "ID", "Serial device"] for p in to_show: platform = p.platform connected = p.connected if filtered and platform not in filtered: continue if not connected_only or connected: table.append([platform, p.id, p.serial]) print(tabulate(table, headers=header, tablefmt="github"))
#!/usr/bin/env python3 # vim: set syntax=python ts=4 : # # Copyright (c) 2018 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import os import contextlib import string import mmap import sys import re import subprocess import select import shutil import shlex import signal import threading import concurrent.futures from collections import OrderedDict import queue import time import csv import glob import concurrent import xml.etree.ElementTree as ET import logging from pathlib import Path from distutils.spawn import find_executable from colorama import Fore import pickle import platform import yaml import json from multiprocessing import Lock, Process, Value from typing import List try: # Use the C LibYAML parser if available, rather than the Python parser. # It's much faster. from yaml import CSafeLoader as SafeLoader from yaml import CDumper as Dumper except ImportError: from yaml import SafeLoader, Dumper try: import serial except ImportError: print("Install pyserial python module with pip to use --device-testing option.") try: from tabulate import tabulate except ImportError: print("Install tabulate python module with pip to use --device-testing option.") try: import psutil except ImportError: print("Install psutil python module with pip to run in Qemu.") try: import pty except ImportError as capture_error: if os.name == "nt": # "nt" means that program is running on Windows OS pass # "--device-serial-pty" option is not supported on Windows OS else: raise capture_error ZEPHYR_BASE = os.getenv("ZEPHYR_BASE") if not ZEPHYR_BASE: sys.exit("$ZEPHYR_BASE environment variable undefined") # This is needed to load edt.pickle files. sys.path.insert(0, os.path.join(ZEPHYR_BASE, "scripts", "dts", "python-devicetree", "src")) from devicetree import edtlib # pylint: disable=unused-import # Use this for internal comparisons; that's what canonicalization is # for. Don't use it when invoking other components of the build system # to avoid confusing and hard to trace inconsistencies in error messages # and logs, generated Makefiles, etc. compared to when users invoke these # components directly. # Note "normalization" is different from canonicalization, see os.path. canonical_zephyr_base = os.path.realpath(ZEPHYR_BASE) sys.path.insert(0, os.path.join(ZEPHYR_BASE, "scripts/")) import scl import expr_parser logger = logging.getLogger('twister') logger.setLevel(logging.DEBUG) class ExecutionCounter(object): def __init__(self, total=0): self._done = Value('i', 0) self._passed = Value('i', 0) self._skipped_configs = Value('i', 0) self._skipped_runtime = Value('i', 0) self._skipped_cases = Value('i', 0) self._error = Value('i', 0) self._failed = Value('i', 0) self._total = Value('i', total) self._cases = Value('i', 0) self.lock = Lock() @property def cases(self): with self._cases.get_lock(): return self._cases.value @cases.setter def cases(self, value): with self._cases.get_lock(): self._cases.value = value @property def skipped_cases(self): with self._skipped_cases.get_lock(): return self._skipped_cases.value @skipped_cases.setter def skipped_cases(self, value): with self._skipped_cases.get_lock(): self._skipped_cases.value = value @property def error(self): with self._error.get_lock(): return self._error.value @error.setter def error(self, value): with self._error.get_lock(): self._error.value = value @property def done(self): with self._done.get_lock(): return self._done.value @done.setter def done(self, value): with self._done.get_lock(): self._done.value = value @property def passed(self): with self._passed.get_lock(): return self._passed.value @passed.setter def passed(self, value): with self._passed.get_lock(): self._passed.value = value @property def skipped_configs(self): with self._skipped_configs.get_lock(): return self._skipped_configs.value @skipped_configs.setter def skipped_configs(self, value): with self._skipped_configs.get_lock(): self._skipped_configs.value = value @property def skipped_runtime(self): with self._skipped_runtime.get_lock(): return self._skipped_runtime.value @skipped_runtime.setter def skipped_runtime(self, value): with self._skipped_runtime.get_lock(): self._skipped_runtime.value = value @property def failed(self): with self._failed.get_lock(): return self._failed.value @failed.setter def failed(self, value): with self._failed.get_lock(): self._failed.value = value @property def total(self): with self._total.get_lock(): return self._total.value class CMakeCacheEntry: '''Represents a CMake cache entry. This class understands the type system in a CMakeCache.txt, and converts the following cache types to Python types: Cache Type Python type ---------- ------------------------------------------- FILEPATH str PATH str STRING str OR list of str (if ';' is in the value) BOOL bool INTERNAL str OR list of str (if ';' is in the value) ---------- ------------------------------------------- ''' # Regular expression for a cache entry. # # CMake variable names can include escape characters, allowing a # wider set of names than is easy to match with a regular # expression. To be permissive here, use a non-greedy match up to # the first colon (':'). This breaks if the variable name has a # colon inside, but it's good enough. CACHE_ENTRY = re.compile( r'''(?P<name>.*?) # name :(?P<type>FILEPATH|PATH|STRING|BOOL|INTERNAL) # type =(?P<value>.*) # value ''', re.X) @classmethod def _to_bool(cls, val): # Convert a CMake BOOL string into a Python bool. # # "True if the constant is 1, ON, YES, TRUE, Y, or a # non-zero number. False if the constant is 0, OFF, NO, # FALSE, N, IGNORE, NOTFOUND, the empty string, or ends in # the suffix -NOTFOUND. Named boolean constants are # case-insensitive. If the argument is not one of these # constants, it is treated as a variable." # # https://cmake.org/cmake/help/v3.0/command/if.html val = val.upper() if val in ('ON', 'YES', 'TRUE', 'Y'): return 1 elif val in ('OFF', 'NO', 'FALSE', 'N', 'IGNORE', 'NOTFOUND', ''): return 0 elif val.endswith('-NOTFOUND'): return 0 else: try: v = int(val) return v != 0 except ValueError as exc: raise ValueError('invalid bool {}'.format(val)) from exc @classmethod def from_line(cls, line, line_no): # Comments can only occur at the beginning of a line. # (The value of an entry could contain a comment character). if line.startswith('//') or line.startswith('#'): return None # Whitespace-only lines do not contain cache entries. if not line.strip(): return None m = cls.CACHE_ENTRY.match(line) if not m: return None name, type_, value = (m.group(g) for g in ('name', 'type', 'value')) if type_ == 'BOOL': try: value = cls._to_bool(value) except ValueError as exc: args = exc.args + ('on line {}: {}'.format(line_no, line),) raise ValueError(args) from exc elif type_ in ['STRING', 'INTERNAL']: # If the value is a CMake list (i.e. is a string which # contains a ';'), convert to a Python list. if ';' in value: value = value.split(';') return CMakeCacheEntry(name, value) def __init__(self, name, value): self.name = name self.value = value def __str__(self): fmt = 'CMakeCacheEntry(name={}, value={})' return fmt.format(self.name, self.value) class CMakeCache: '''Parses and represents a CMake cache file.''' @staticmethod def from_file(cache_file): return CMakeCache(cache_file) def __init__(self, cache_file): self.cache_file = cache_file self.load(cache_file) def load(self, cache_file): entries = [] with open(cache_file, 'r') as cache: for line_no, line in enumerate(cache): entry = CMakeCacheEntry.from_line(line, line_no) if entry: entries.append(entry) self._entries = OrderedDict((e.name, e) for e in entries) def get(self, name, default=None): entry = self._entries.get(name) if entry is not None: return entry.value else: return default def get_list(self, name, default=None): if default is None: default = [] entry = self._entries.get(name) if entry is not None: value = entry.value if isinstance(value, list): return value elif isinstance(value, str): return [value] if value else [] else: msg = 'invalid value {} type {}' raise RuntimeError(msg.format(value, type(value))) else: return default def __contains__(self, name): return name in self._entries def __getitem__(self, name): return self._entries[name].value def __setitem__(self, name, entry): if not isinstance(entry, CMakeCacheEntry): msg = 'improper type {} for value {}, expecting CMakeCacheEntry' raise TypeError(msg.format(type(entry), entry)) self._entries[name] = entry def __delitem__(self, name): del self._entries[name] def __iter__(self): return iter(self._entries.values()) class TwisterException(Exception): pass class TwisterRuntimeError(TwisterException): pass class ConfigurationError(TwisterException): def __init__(self, cfile, message): TwisterException.__init__(self, cfile + ": " + message) class BuildError(TwisterException): pass class ExecutionError(TwisterException): pass class HarnessImporter: def __init__(self, name): sys.path.insert(0, os.path.join(ZEPHYR_BASE, "scripts/pylib/twister")) module = __import__("harness") if name: my_class = getattr(module, name) else: my_class = getattr(module, "Test") self.instance = my_class() class Handler: def __init__(self, instance, type_str="build"): """Constructor """ self.state = "waiting" self.run = False self.duration = 0 self.type_str = type_str self.binary = None self.pid_fn = None self.call_make_run = False self.name = instance.name self.instance = instance self.timeout = instance.testcase.timeout self.sourcedir = instance.testcase.source_dir self.build_dir = instance.build_dir self.log = os.path.join(self.build_dir, "handler.log") self.returncode = 0 self.set_state("running", self.duration) self.generator = None self.generator_cmd = None self.args = [] self.terminated = False def set_state(self, state, duration): self.state = state self.duration = duration def get_state(self): ret = (self.state, self.duration) return ret def record(self, harness): if harness.recording: filename = os.path.join(self.build_dir, "recording.csv") with open(filename, "at") as csvfile: cw = csv.writer(csvfile, harness.fieldnames, lineterminator=os.linesep) cw.writerow(harness.fieldnames) for instance in harness.recording: cw.writerow(instance) def terminate(self, proc): # encapsulate terminate functionality so we do it consistently where ever # we might want to terminate the proc. We need try_kill_process_by_pid # because of both how newer ninja (1.6.0 or greater) and .NET / renode # work. Newer ninja's don't seem to pass SIGTERM down to the children # so we need to use try_kill_process_by_pid. for child in psutil.Process(proc.pid).children(recursive=True): try: os.kill(child.pid, signal.SIGTERM) except ProcessLookupError: pass proc.terminate() # sleep for a while before attempting to kill time.sleep(0.5) proc.kill() self.terminated = True def add_missing_testscases(self, harness): """ If testsuite was broken by some error (e.g. timeout) it is necessary to add information about next testcases, which were not be performed due to this error. """ for c in self.instance.testcase.cases: if c not in harness.tests: harness.tests[c] = "BLOCK" def _set_skip_reason(self, harness_state): """ If testcase written in ztest framework is skipped by "ztest_test_skip()" function, then such testcase is marked in instance.results dict as "SKIP", but reason of this sipping still "Unknown". This method pick up this situation and complete the instance.reason properly. """ harness_state_pass = "passed" harness_testcase_result_skip = "SKIP" instance_reason_unknown = "Unknown" if harness_state == harness_state_pass and \ self.instance.reason == instance_reason_unknown and \ harness_testcase_result_skip in self.instance.results.values(): self.instance.reason = "ztest skip" class BinaryHandler(Handler): def __init__(self, instance, type_str): """Constructor @param instance Test Instance """ super().__init__(instance, type_str) self.call_west_flash = False # Tool options self.valgrind = False self.lsan = False self.asan = False self.ubsan = False self.coverage = False def try_kill_process_by_pid(self): if self.pid_fn: pid = int(open(self.pid_fn).read()) os.unlink(self.pid_fn) self.pid_fn = None # clear so we don't try to kill the binary twice try: os.kill(pid, signal.SIGTERM) except ProcessLookupError: pass def _output_reader(self, proc): self.line = proc.stdout.readline() def _output_handler(self, proc, harness): if harness.is_pytest: harness.handle(None) return log_out_fp = open(self.log, "wt") timeout_extended = False timeout_time = time.time() + self.timeout while True: this_timeout = timeout_time - time.time() if this_timeout < 0: break reader_t = threading.Thread(target=self._output_reader, args=(proc,), daemon=True) reader_t.start() reader_t.join(this_timeout) if not reader_t.is_alive(): line = self.line logger.debug("OUTPUT: {0}".format(line.decode('utf-8').rstrip())) log_out_fp.write(line.decode('utf-8')) log_out_fp.flush() harness.handle(line.decode('utf-8').rstrip()) if harness.state: if not timeout_extended or harness.capture_coverage: timeout_extended = True if harness.capture_coverage: timeout_time = time.time() + 30 else: timeout_time = time.time() + 2 else: reader_t.join(0) break try: # POSIX arch based ztests end on their own, # so let's give it up to 100ms to do so proc.wait(0.1) except subprocess.TimeoutExpired: self.terminate(proc) log_out_fp.close() def handle(self): harness_name = self.instance.testcase.harness.capitalize() harness_import = HarnessImporter(harness_name) harness = harness_import.instance harness.configure(self.instance) if self.call_make_run: command = [self.generator_cmd, "run"] elif self.call_west_flash: command = ["west", "flash", "--skip-rebuild", "-d", self.build_dir] else: command = [self.binary] run_valgrind = False if self.valgrind and shutil.which("valgrind"): command = ["valgrind", "--error-exitcode=2", "--leak-check=full", "--suppressions=" + ZEPHYR_BASE + "/scripts/valgrind.supp", "--log-file=" + self.build_dir + "/valgrind.log" ] + command run_valgrind = True logger.debug("Spawning process: " + " ".join(shlex.quote(word) for word in command) + os.linesep + "in directory: " + self.build_dir) start_time = time.time() env = os.environ.copy() if self.asan: env["ASAN_OPTIONS"] = "log_path=stdout:" + \ env.get("ASAN_OPTIONS", "") if not self.lsan: env["ASAN_OPTIONS"] += "detect_leaks=0" if self.ubsan: env["UBSAN_OPTIONS"] = "log_path=stdout:halt_on_error=1:" + \ env.get("UBSAN_OPTIONS", "") with subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=self.build_dir, env=env) as proc: logger.debug("Spawning BinaryHandler Thread for %s" % self.name) t = threading.Thread(target=self._output_handler, args=(proc, harness,), daemon=True) t.start() t.join() if t.is_alive(): self.terminate(proc) t.join() proc.wait() self.returncode = proc.returncode self.try_kill_process_by_pid() handler_time = time.time() - start_time if self.coverage: subprocess.call(["GCOV_PREFIX=" + self.build_dir, "gcov", self.sourcedir, "-b", "-s", self.build_dir], shell=True) # FIXME: This is needed when killing the simulator, the console is # garbled and needs to be reset. Did not find a better way to do that. if sys.stdout.isatty(): subprocess.call(["stty", "sane"]) if harness.is_pytest: harness.pytest_run(self.log) self.instance.results = harness.tests if not self.terminated and self.returncode != 0: # When a process is killed, the default handler returns 128 + SIGTERM # so in that case the return code itself is not meaningful self.set_state("failed", handler_time) self.instance.reason = "Failed" elif run_valgrind and self.returncode == 2: self.set_state("failed", handler_time) self.instance.reason = "Valgrind error" elif harness.state: self.set_state(harness.state, handler_time) if harness.state == "failed": self.instance.reason = "Failed" else: self.set_state("timeout", handler_time) self.instance.reason = "Timeout" self.add_missing_testscases(harness) self._set_skip_reason(harness.state) self.record(harness) class DeviceHandler(Handler): def __init__(self, instance, type_str): """Constructor @param instance Test Instance """ super().__init__(instance, type_str) self.suite = None def monitor_serial(self, ser, halt_fileno, harness): if harness.is_pytest: harness.handle(None) return log_out_fp = open(self.log, "wt") ser_fileno = ser.fileno() readlist = [halt_fileno, ser_fileno] if self.coverage: # Set capture_coverage to True to indicate that right after # test results we should get coverage data, otherwise we exit # from the test. harness.capture_coverage = True ser.flush() while ser.isOpen(): readable, _, _ = select.select(readlist, [], [], self.timeout) if halt_fileno in readable: logger.debug('halted') ser.close() break if ser_fileno not in readable: continue # Timeout. serial_line = None try: serial_line = ser.readline() except TypeError: pass except serial.SerialException: ser.close() break # Just because ser_fileno has data doesn't mean an entire line # is available yet. if serial_line: sl = serial_line.decode('utf-8', 'ignore').lstrip() logger.debug("DEVICE: {0}".format(sl.rstrip())) log_out_fp.write(sl) log_out_fp.flush() harness.handle(sl.rstrip()) if harness.state: if not harness.capture_coverage: ser.close() break log_out_fp.close() def device_is_available(self, instance): device = instance.platform.name fixture = instance.testcase.harness_config.get("fixture") for d in self.suite.duts: if fixture and fixture not in d.fixtures: continue if d.platform != device or not (d.serial or d.serial_pty): continue d.lock.acquire() avail = False if d.available: d.available = 0 d.counter += 1 avail = True d.lock.release() if avail: return d return None def make_device_available(self, serial): for d in self.suite.duts: if d.serial == serial or d.serial_pty: d.available = 1 @staticmethod def run_custom_script(script, timeout): with subprocess.Popen(script, stderr=subprocess.PIPE, stdout=subprocess.PIPE) as proc: try: stdout, stderr = proc.communicate(timeout=timeout) logger.debug(stdout.decode()) if proc.returncode != 0: logger.error(f"Custom script failure: {stderr.decode(errors='ignore')}") except subprocess.TimeoutExpired: proc.kill() proc.communicate() logger.error("{} timed out".format(script)) def handle(self): out_state = "failed" runner = None hardware = self.device_is_available(self.instance) while not hardware: logger.debug("Waiting for device {} to become available".format(self.instance.platform.name)) time.sleep(1) hardware = self.device_is_available(self.instance) runner = hardware.runner or self.suite.west_runner serial_pty = hardware.serial_pty ser_pty_process = None if serial_pty: master, slave = pty.openpty() try: ser_pty_process = subprocess.Popen(re.split(',| ', serial_pty), stdout=master, stdin=master, stderr=master) except subprocess.CalledProcessError as error: logger.error("Failed to run subprocess {}, error {}".format(serial_pty, error.output)) return serial_device = os.ttyname(slave) else: serial_device = hardware.serial logger.debug(f"Using serial device {serial_device} @ {hardware.baud} baud") if (self.suite.west_flash is not None) or runner: command = ["west", "flash", "--skip-rebuild", "-d", self.build_dir] command_extra_args = [] # There are three ways this option is used. # 1) bare: --west-flash # This results in options.west_flash == [] # 2) with a value: --west-flash="--board-id=42" # This results in options.west_flash == "--board-id=42" # 3) Multiple values: --west-flash="--board-id=42,--erase" # This results in options.west_flash == "--board-id=42 --erase" if self.suite.west_flash and self.suite.west_flash != []: command_extra_args.extend(self.suite.west_flash.split(',')) if runner: command.append("--runner") command.append(runner) board_id = hardware.probe_id or hardware.id product = hardware.product if board_id is not None: if runner == "pyocd": command_extra_args.append("--board-id") command_extra_args.append(board_id) elif runner == "nrfjprog": command_extra_args.append("--dev-id") command_extra_args.append(board_id) elif runner == "openocd" and product == "STM32 STLink": command_extra_args.append("--cmd-pre-init") command_extra_args.append("hla_serial %s" % (board_id)) elif runner == "openocd" and product == "STLINK-V3": command_extra_args.append("--cmd-pre-init") command_extra_args.append("hla_serial %s" % (board_id)) elif runner == "openocd" and product == "EDBG CMSIS-DAP": command_extra_args.append("--cmd-pre-init") command_extra_args.append("cmsis_dap_serial %s" % (board_id)) elif runner == "jlink": command.append("--tool-opt=-SelectEmuBySN %s" % (board_id)) elif runner == "stm32cubeprogrammer": command.append("--tool-opt=sn=%s" % (board_id)) if command_extra_args != []: command.append('--') command.extend(command_extra_args) else: command = [self.generator_cmd, "-C", self.build_dir, "flash"] pre_script = hardware.pre_script post_flash_script = hardware.post_flash_script post_script = hardware.post_script if pre_script: self.run_custom_script(pre_script, 30) try: ser = serial.Serial( serial_device, baudrate=hardware.baud, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=self.timeout ) except serial.SerialException as e: self.set_state("failed", 0) self.instance.reason = "Failed" logger.error("Serial device error: %s" % (str(e))) if serial_pty and ser_pty_process: ser_pty_process.terminate() outs, errs = ser_pty_process.communicate() logger.debug("Process {} terminated outs: {} errs {}".format(serial_pty, outs, errs)) self.make_device_available(serial_device) return ser.flush() harness_name = self.instance.testcase.harness.capitalize() harness_import = HarnessImporter(harness_name) harness = harness_import.instance harness.configure(self.instance) read_pipe, write_pipe = os.pipe() start_time = time.time() t = threading.Thread(target=self.monitor_serial, daemon=True, args=(ser, read_pipe, harness)) t.start() d_log = "{}/device.log".format(self.instance.build_dir) logger.debug('Flash command: %s', command) try: stdout = stderr = None with subprocess.Popen(command, stderr=subprocess.PIPE, stdout=subprocess.PIPE) as proc: try: (stdout, stderr) = proc.communicate(timeout=30) # ignore unencodable unicode chars logger.debug(stdout.decode(errors = "ignore")) if proc.returncode != 0: self.instance.reason = "Device issue (Flash?)" with open(d_log, "w") as dlog_fp: dlog_fp.write(stderr.decode()) os.write(write_pipe, b'x') # halt the thread out_state = "flash_error" except subprocess.TimeoutExpired: proc.kill() (stdout, stderr) = proc.communicate() self.instance.reason = "Device issue (Timeout)" with open(d_log, "w") as dlog_fp: dlog_fp.write(stderr.decode()) except subprocess.CalledProcessError: os.write(write_pipe, b'x') # halt the thread if post_flash_script: self.run_custom_script(post_flash_script, 30) t.join(self.timeout) if t.is_alive(): logger.debug("Timed out while monitoring serial output on {}".format(self.instance.platform.name)) out_state = "timeout" if ser.isOpen(): ser.close() if serial_pty: ser_pty_process.terminate() outs, errs = ser_pty_process.communicate() logger.debug("Process {} terminated outs: {} errs {}".format(serial_pty, outs, errs)) os.close(write_pipe) os.close(read_pipe) handler_time = time.time() - start_time if out_state in ["timeout", "flash_error"]: self.add_missing_testscases(harness) if out_state == "timeout": self.instance.reason = "Timeout" elif out_state == "flash_error": self.instance.reason = "Flash error" if harness.is_pytest: harness.pytest_run(self.log) self.instance.results = harness.tests # sometimes a test instance hasn't been executed successfully with an # empty dictionary results, in order to include it into final report, # so fill the results as BLOCK if self.instance.results == {}: for k in self.instance.testcase.cases: self.instance.results[k] = 'BLOCK' if harness.state: self.set_state(harness.state, handler_time) if harness.state == "failed": self.instance.reason = "Failed" else: self.set_state(out_state, handler_time) self._set_skip_reason(harness.state) if post_script: self.run_custom_script(post_script, 30) self.make_device_available(serial_device) self.record(harness) class QEMUHandler(Handler): """Spawns a thread to monitor QEMU output from pipes We pass QEMU_PIPE to 'make run' and monitor the pipes for output. We need to do this as once qemu starts, it runs forever until killed. Test cases emit special messages to the console as they run, we check for these to collect whether the test passed or failed. """ def __init__(self, instance, type_str): """Constructor @param instance Test instance """ super().__init__(instance, type_str) self.fifo_fn = os.path.join(instance.build_dir, "qemu-fifo") self.pid_fn = os.path.join(instance.build_dir, "qemu.pid") if "ignore_qemu_crash" in instance.testcase.tags: self.ignore_qemu_crash = True self.ignore_unexpected_eof = True else: self.ignore_qemu_crash = False self.ignore_unexpected_eof = False @staticmethod def _get_cpu_time(pid): """get process CPU time. The guest virtual time in QEMU icount mode isn't host time and it's maintained by counting guest instructions, so we use QEMU process exection time to mostly simulate the time of guest OS. """ proc = psutil.Process(pid) cpu_time = proc.cpu_times() return cpu_time.user + cpu_time.system @staticmethod def _thread(handler, timeout, outdir, logfile, fifo_fn, pid_fn, results, harness, ignore_unexpected_eof=False): fifo_in = fifo_fn + ".in" fifo_out = fifo_fn + ".out" # These in/out nodes are named from QEMU's perspective, not ours if os.path.exists(fifo_in): os.unlink(fifo_in) os.mkfifo(fifo_in) if os.path.exists(fifo_out): os.unlink(fifo_out) os.mkfifo(fifo_out) # We don't do anything with out_fp but we need to open it for # writing so that QEMU doesn't block, due to the way pipes work out_fp = open(fifo_in, "wb") # Disable internal buffering, we don't # want read() or poll() to ever block if there is data in there in_fp = open(fifo_out, "rb", buffering=0) log_out_fp = open(logfile, "wt") start_time = time.time() timeout_time = start_time + timeout p = select.poll() p.register(in_fp, select.POLLIN) out_state = None line = "" timeout_extended = False pid = 0 if os.path.exists(pid_fn): pid = int(open(pid_fn).read()) while True: this_timeout = int((timeout_time - time.time()) * 1000) if this_timeout < 0 or not p.poll(this_timeout): try: if pid and this_timeout > 0: #there's possibility we polled nothing because #of not enough CPU time scheduled by host for #QEMU process during p.poll(this_timeout) cpu_time = QEMUHandler._get_cpu_time(pid) if cpu_time < timeout and not out_state: timeout_time = time.time() + (timeout - cpu_time) continue except ProcessLookupError: out_state = "failed" break if not out_state: out_state = "timeout" break if pid == 0 and os.path.exists(pid_fn): pid = int(open(pid_fn).read()) if harness.is_pytest: harness.handle(None) out_state = harness.state break try: c = in_fp.read(1).decode("utf-8") except UnicodeDecodeError: # Test is writing something weird, fail out_state = "unexpected byte" break if c == "": # EOF, this shouldn't happen unless QEMU crashes if not ignore_unexpected_eof: out_state = "unexpected eof" break line = line + c if c != "\n": continue # line contains a full line of data output from QEMU log_out_fp.write(line) log_out_fp.flush() line = line.strip() logger.debug(f"QEMU ({pid}): {line}") harness.handle(line) if harness.state: # if we have registered a fail make sure the state is not # overridden by a false success message coming from the # testsuite if out_state not in ['failed', 'unexpected eof', 'unexpected byte']: out_state = harness.state # if we get some state, that means test is doing well, we reset # the timeout and wait for 2 more seconds to catch anything # printed late. We wait much longer if code # coverage is enabled since dumping this information can # take some time. if not timeout_extended or harness.capture_coverage: timeout_extended = True if harness.capture_coverage: timeout_time = time.time() + 30 else: timeout_time = time.time() + 2 line = "" if harness.is_pytest: harness.pytest_run(logfile) out_state = harness.state handler.record(harness) handler_time = time.time() - start_time logger.debug(f"QEMU ({pid}) complete ({out_state}) after {handler_time} seconds") if out_state == "timeout": handler.instance.reason = "Timeout" handler.set_state("failed", handler_time) elif out_state == "failed": handler.instance.reason = "Failed" handler.set_state("failed", handler_time) elif out_state in ['unexpected eof', 'unexpected byte']: handler.instance.reason = out_state handler.set_state("failed", handler_time) else: handler.set_state(out_state, handler_time) log_out_fp.close() out_fp.close() in_fp.close() if pid: try: if pid: os.kill(pid, signal.SIGTERM) except ProcessLookupError: # Oh well, as long as it's dead! User probably sent Ctrl-C pass os.unlink(fifo_in) os.unlink(fifo_out) def handle(self): self.results = {} self.run = True # We pass this to QEMU which looks for fifos with .in and .out # suffixes. self.fifo_fn = os.path.join(self.instance.build_dir, "qemu-fifo") self.pid_fn = os.path.join(self.instance.build_dir, "qemu.pid") if os.path.exists(self.pid_fn): os.unlink(self.pid_fn) self.log_fn = self.log harness_import = HarnessImporter(self.instance.testcase.harness.capitalize()) harness = harness_import.instance harness.configure(self.instance) self.thread = threading.Thread(name=self.name, target=QEMUHandler._thread, args=(self, self.timeout, self.build_dir, self.log_fn, self.fifo_fn, self.pid_fn, self.results, harness, self.ignore_unexpected_eof)) self.instance.results = harness.tests self.thread.daemon = True logger.debug("Spawning QEMUHandler Thread for %s" % self.name) self.thread.start() if sys.stdout.isatty(): subprocess.call(["stty", "sane"]) logger.debug("Running %s (%s)" % (self.name, self.type_str)) command = [self.generator_cmd] command += ["-C", self.build_dir, "run"] is_timeout = False qemu_pid = None with subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=self.build_dir) as proc: logger.debug("Spawning QEMUHandler Thread for %s" % self.name) try: proc.wait(self.timeout) except subprocess.TimeoutExpired: # sometimes QEMU can't handle SIGTERM signal correctly # in that case kill -9 QEMU process directly and leave # twister to judge testing result by console output is_timeout = True self.terminate(proc) if harness.state == "passed": self.returncode = 0 else: self.returncode = proc.returncode else: if os.path.exists(self.pid_fn): qemu_pid = int(open(self.pid_fn).read()) logger.debug(f"No timeout, return code from QEMU ({qemu_pid}): {proc.returncode}") self.returncode = proc.returncode # Need to wait for harness to finish processing # output from QEMU. Otherwise it might miss some # error messages. self.thread.join(0) if self.thread.is_alive(): logger.debug("Timed out while monitoring QEMU output") if os.path.exists(self.pid_fn): qemu_pid = int(open(self.pid_fn).read()) os.unlink(self.pid_fn) logger.debug(f"return code from QEMU ({qemu_pid}): {self.returncode}") if (self.returncode != 0 and not self.ignore_qemu_crash) or not harness.state: self.set_state("failed", 0) if is_timeout: self.instance.reason = "Timeout" else: self.instance.reason = "Exited with {}".format(self.returncode) self.add_missing_testscases(harness) self._set_skip_reason(harness.state) def get_fifo(self): return self.fifo_fn class SizeCalculator: alloc_sections = [ "bss", "noinit", "app_bss", "app_noinit", "ccm_bss", "ccm_noinit" ] rw_sections = [ "datas", "initlevel", "exceptions", "initshell", "_static_thread_data_area", "k_timer_area", "k_mem_slab_area", "k_mem_pool_area", "sw_isr_table", "k_sem_area", "k_mutex_area", "app_shmem_regions", "_k_fifo_area", "_k_lifo_area", "k_stack_area", "k_msgq_area", "k_mbox_area", "k_pipe_area", "net_if_area", "net_if_dev_area", "net_l2_area", "net_l2_data", "k_queue_area", "_net_buf_pool_area", "app_datas", "kobject_data", "mmu_tables", "app_pad", "priv_stacks", "ccm_data", "usb_descriptor", "usb_data", "usb_bos_desc", "uart_mux", 'log_backends_sections', 'log_dynamic_sections', 'log_const_sections', "app_smem", 'shell_root_cmds_sections', 'log_const_sections', "font_entry_sections", "priv_stacks_noinit", "_GCOV_BSS_SECTION_NAME", "gcov", "nocache", "devices", "k_heap_area", ] # These get copied into RAM only on non-XIP ro_sections = [ "rom_start", "text", "ctors", "init_array", "reset", "z_object_assignment_area", "rodata", "net_l2", "vector", "sw_isr_table", "settings_handler_static_area", "bt_l2cap_fixed_chan_area", "bt_l2cap_br_fixed_chan_area", "bt_gatt_service_static_area", "vectors", "net_socket_register_area", "net_ppp_proto", "shell_area", "tracing_backend_area", "ppp_protocol_handler_area", ] def __init__(self, filename, extra_sections): """Constructor @param filename Path to the output binary The <filename> is parsed by objdump to determine section sizes """ # Make sure this is an ELF binary with open(filename, "rb") as f: magic = f.read(4) try: if magic != b'\x7fELF': raise TwisterRuntimeError("%s is not an ELF binary" % filename) except Exception as e: print(str(e)) sys.exit(2) # Search for CONFIG_XIP in the ELF's list of symbols using NM and AWK. # GREP can not be used as it returns an error if the symbol is not # found. is_xip_command = "nm " + filename + \ " | awk '/CONFIG_XIP/ { print $3 }'" is_xip_output = subprocess.check_output( is_xip_command, shell=True, stderr=subprocess.STDOUT).decode( "utf-8").strip() try: if is_xip_output.endswith("no symbols"): raise TwisterRuntimeError("%s has no symbol information" % filename) except Exception as e: print(str(e)) sys.exit(2) self.is_xip = (len(is_xip_output) != 0) self.filename = filename self.sections = [] self.rom_size = 0 self.ram_size = 0 self.extra_sections = extra_sections self._calculate_sizes() def get_ram_size(self): """Get the amount of RAM the application will use up on the device @return amount of RAM, in bytes """ return self.ram_size def get_rom_size(self): """Get the size of the data that this application uses on device's flash @return amount of ROM, in bytes """ return self.rom_size def unrecognized_sections(self): """Get a list of sections inside the binary that weren't recognized @return list of unrecognized section names """ slist = [] for v in self.sections: if not v["recognized"]: slist.append(v["name"]) return slist def _calculate_sizes(self): """ Calculate RAM and ROM usage by section """ objdump_command = "objdump -h " + self.filename objdump_output = subprocess.check_output( objdump_command, shell=True).decode("utf-8").splitlines() for line in objdump_output: words = line.split() if not words: # Skip lines that are too short continue index = words[0] if not index[0].isdigit(): # Skip lines that do not start continue # with a digit name = words[1] # Skip lines with section names if name[0] == '.': # starting with '.' continue # TODO this doesn't actually reflect the size in flash or RAM as # it doesn't include linker-imposed padding between sections. # It is close though. size = int(words[2], 16) if size == 0: continue load_addr = int(words[4], 16) virt_addr = int(words[3], 16) # Add section to memory use totals (for both non-XIP and XIP scenarios) # Unrecognized section names are not included in the calculations. recognized = True if name in SizeCalculator.alloc_sections: self.ram_size += size stype = "alloc" elif name in SizeCalculator.rw_sections: self.ram_size += size self.rom_size += size stype = "rw" elif name in SizeCalculator.ro_sections: self.rom_size += size if not self.is_xip: self.ram_size += size stype = "ro" else: stype = "unknown" if name not in self.extra_sections: recognized = False self.sections.append({"name": name, "load_addr": load_addr, "size": size, "virt_addr": virt_addr, "type": stype, "recognized": recognized}) class TwisterConfigParser: """Class to read test case files with semantic checking """ def __init__(self, filename, schema): """Instantiate a new TwisterConfigParser object @param filename Source .yaml file to read """ self.data = {} self.schema = schema self.filename = filename self.tests = {} self.common = {} def load(self): self.data = scl.yaml_load_verify(self.filename, self.schema) if 'tests' in self.data: self.tests = self.data['tests'] if 'common' in self.data: self.common = self.data['common'] def _cast_value(self, value, typestr): if isinstance(value, str): v = value.strip() if typestr == "str": return v elif typestr == "float": return float(value) elif typestr == "int": return int(value) elif typestr == "bool": return value elif typestr.startswith("list") and isinstance(value, list): return value elif typestr.startswith("list") and isinstance(value, str): vs = v.split() if len(typestr) > 4 and typestr[4] == ":": return [self._cast_value(vsi, typestr[5:]) for vsi in vs] else: return vs elif typestr.startswith("set"): vs = v.split() if len(typestr) > 3 and typestr[3] == ":": return {self._cast_value(vsi, typestr[4:]) for vsi in vs} else: return set(vs) elif typestr.startswith("map"): return value else: raise ConfigurationError( self.filename, "unknown type '%s'" % value) def get_test(self, name, valid_keys): """Get a dictionary representing the keys/values within a test @param name The test in the .yaml file to retrieve data from @param valid_keys A dictionary representing the intended semantics for this test. Each key in this dictionary is a key that could be specified, if a key is given in the .yaml file which isn't in here, it will generate an error. Each value in this dictionary is another dictionary containing metadata: "default" - Default value if not given "type" - Data type to convert the text value to. Simple types supported are "str", "float", "int", "bool" which will get converted to respective Python data types. "set" and "list" may also be specified which will split the value by whitespace (but keep the elements as strings). finally, "list:<type>" and "set:<type>" may be given which will perform a type conversion after splitting the value up. "required" - If true, raise an error if not defined. If false and "default" isn't specified, a type conversion will be done on an empty string @return A dictionary containing the test key-value pairs with type conversion and default values filled in per valid_keys """ d = {} for k, v in self.common.items(): d[k] = v for k, v in self.tests[name].items(): if k in d: if isinstance(d[k], str): # By default, we just concatenate string values of keys # which appear both in "common" and per-test sections, # but some keys are handled in adhoc way based on their # semantics. if k == "filter": d[k] = "(%s) and (%s)" % (d[k], v) else: d[k] += " " + v else: d[k] = v for k, kinfo in valid_keys.items(): if k not in d: if "required" in kinfo: required = kinfo["required"] else: required = False if required: raise ConfigurationError( self.filename, "missing required value for '%s' in test '%s'" % (k, name)) else: if "default" in kinfo: default = kinfo["default"] else: default = self._cast_value("", kinfo["type"]) d[k] = default else: try: d[k] = self._cast_value(d[k], kinfo["type"]) except ValueError: raise ConfigurationError( self.filename, "bad %s value '%s' for key '%s' in name '%s'" % (kinfo["type"], d[k], k, name)) return d class Platform: """Class representing metadata for a particular platform Maps directly to BOARD when building""" platform_schema = scl.yaml_load(os.path.join(ZEPHYR_BASE, "scripts", "schemas", "twister", "platform-schema.yaml")) def __init__(self): """Constructor. """ self.name = "" self.twister = True # if no RAM size is specified by the board, take a default of 128K self.ram = 128 self.ignore_tags = [] self.only_tags = [] self.default = False # if no flash size is specified by the board, take a default of 512K self.flash = 512 self.supported = set() self.arch = "" self.type = "na" self.simulation = "na" self.supported_toolchains = [] self.env = [] self.env_satisfied = True self.filter_data = dict() def load(self, platform_file): scp = TwisterConfigParser(platform_file, self.platform_schema) scp.load() data = scp.data self.name = data['identifier'] self.twister = data.get("twister", True) # if no RAM size is specified by the board, take a default of 128K self.ram = data.get("ram", 128) testing = data.get("testing", {}) self.ignore_tags = testing.get("ignore_tags", []) self.only_tags = testing.get("only_tags", []) self.default = testing.get("default", False) # if no flash size is specified by the board, take a default of 512K self.flash = data.get("flash", 512) self.supported = set() for supp_feature in data.get("supported", []): for item in supp_feature.split(":"): self.supported.add(item) self.arch = data['arch'] self.type = data.get('type', "na") self.simulation = data.get('simulation', "na") self.supported_toolchains = data.get("toolchain", []) self.env = data.get("env", []) self.env_satisfied = True for env in self.env: if not os.environ.get(env, None): self.env_satisfied = False def __repr__(self): return "<%s on %s>" % (self.name, self.arch) class DisablePyTestCollectionMixin(object): __test__ = False class ScanPathResult: """Result of the TestCase.scan_path function call. Attributes: matches A list of test cases warnings A string containing one or more warnings to display has_registered_test_suites Whether or not the path contained any calls to the ztest_register_test_suite macro. has_run_registered_test_suites Whether or not the path contained at least one call to ztest_run_registered_test_suites. has_test_main Whether or not the path contains a definition of test_main(void) """ def __init__(self, matches: List[str] = None, warnings: str = None, has_registered_test_suites: bool = False, has_run_registered_test_suites: bool = False, has_test_main: bool = False): self.matches = matches self.warnings = warnings self.has_registered_test_suites = has_registered_test_suites self.has_run_registered_test_suites = has_run_registered_test_suites self.has_test_main = has_test_main def __eq__(self, other): if not isinstance(other, ScanPathResult): return False return (sorted(self.matches) == sorted(other.matches) and self.warnings == other.warnings and (self.has_registered_test_suites == other.has_registered_test_suites) and (self.has_run_registered_test_suites == other.has_run_registered_test_suites) and self.has_test_main == other.has_test_main) class TestCase(DisablePyTestCollectionMixin): """Class representing a test application """ def __init__(self, testcase_root, workdir, name): """TestCase constructor. This gets called by TestSuite as it finds and reads test yaml files. Multiple TestCase instances may be generated from a single testcase.yaml, each one corresponds to an entry within that file. We need to have a unique name for every single test case. Since a testcase.yaml can define multiple tests, the canonical name for the test case is <workdir>/<name>. @param testcase_root os.path.abspath() of one of the --testcase-root @param workdir Sub-directory of testcase_root where the .yaml test configuration file was found @param name Name of this test case, corresponding to the entry name in the test case configuration file. For many test cases that just define one test, can be anything and is usually "test". This is really only used to distinguish between different cases when the testcase.yaml defines multiple tests """ self.source_dir = "" self.yamlfile = "" self.cases = [] self.name = self.get_unique(testcase_root, workdir, name) self.id = name self.type = None self.tags = set() self.extra_args = None self.extra_configs = None self.arch_allow = None self.arch_exclude = None self.skip = False self.platform_exclude = None self.platform_allow = None self.toolchain_exclude = None self.toolchain_allow = None self.tc_filter = None self.timeout = 60 self.harness = "" self.harness_config = {} self.build_only = True self.build_on_all = False self.slow = False self.min_ram = -1 self.depends_on = None self.min_flash = -1 self.extra_sections = None self.integration_platforms = [] @staticmethod def get_unique(testcase_root, workdir, name): canonical_testcase_root = os.path.realpath(testcase_root) if Path(canonical_zephyr_base) in Path(canonical_testcase_root).parents: # This is in ZEPHYR_BASE, so include path in name for uniqueness # FIXME: We should not depend on path of test for unique names. relative_tc_root = os.path.relpath(canonical_testcase_root, start=canonical_zephyr_base) else: relative_tc_root = "" # workdir can be "." unique = os.path.normpath(os.path.join(relative_tc_root, workdir, name)) check = name.split(".") if len(check) < 2: raise TwisterException(f"""bad test name '{name}' in {testcase_root}/{workdir}. \ Tests should reference the category and subsystem with a dot as a separator. """ ) return unique @staticmethod def scan_file(inf_name): suite_regex = re.compile( # do not match until end-of-line, otherwise we won't allow # stc_regex below to catch the ones that are declared in the same # line--as we only search starting the end of this match br"^\s*ztest_test_suite\(\s*(?P<suite_name>[a-zA-Z0-9_]+)\s*,", re.MULTILINE) registered_suite_regex = re.compile( br"^\s*ztest_register_test_suite" br"\(\s*(?P<suite_name>[a-zA-Z0-9_]+)\s*,", re.MULTILINE) # Checks if the file contains a definition of "void test_main(void)" # Since ztest provides a plain test_main implementation it is OK to: # 1. register test suites and not call the run function iff the test # doesn't have a custom test_main. # 2. register test suites and a custom test_main definition iff the test # also calls ztest_run_registered_test_suites. test_main_regex = re.compile( br"^\s*void\s+test_main\(void\)", re.MULTILINE) stc_regex = re.compile( br"""^\s* # empy space at the beginning is ok # catch the case where it is declared in the same sentence, e.g: # # ztest_test_suite(mutex_complex, ztest_user_unit_test(TESTNAME)); # ztest_register_test_suite(n, p, ztest_user_unit_test(TESTNAME), (?:ztest_ (?:test_suite\(|register_test_suite\([a-zA-Z0-9_]+\s*,\s*) [a-zA-Z0-9_]+\s*,\s* )? # Catch ztest[_user]_unit_test-[_setup_teardown](TESTNAME) ztest_(?:1cpu_)?(?:user_)?unit_test(?:_setup_teardown)? # Consume the argument that becomes the extra testcse \(\s*(?P<stc_name>[a-zA-Z0-9_]+) # _setup_teardown() variant has two extra arguments that we ignore (?:\s*,\s*[a-zA-Z0-9_]+\s*,\s*[a-zA-Z0-9_]+)? \s*\)""", # We don't check how it finishes; we don't care re.MULTILINE | re.VERBOSE) suite_run_regex = re.compile( br"^\s*ztest_run_test_suite\((?P<suite_name>[a-zA-Z0-9_]+)\)", re.MULTILINE) registered_suite_run_regex = re.compile( br"^\s*ztest_run_registered_test_suites\(" br"(\*+|&)?(?P<state_identifier>[a-zA-Z0-9_]+)\)", re.MULTILINE) achtung_regex = re.compile( br"(#ifdef|#endif)", re.MULTILINE) warnings = None has_registered_test_suites = False has_run_registered_test_suites = False has_test_main = False with open(inf_name) as inf: if os.name == 'nt': mmap_args = {'fileno': inf.fileno(), 'length': 0, 'access': mmap.ACCESS_READ} else: mmap_args = {'fileno': inf.fileno(), 'length': 0, 'flags': mmap.MAP_PRIVATE, 'prot': mmap.PROT_READ, 'offset': 0} with contextlib.closing(mmap.mmap(**mmap_args)) as main_c: suite_regex_match = suite_regex.search(main_c) registered_suite_regex_match = registered_suite_regex.search( main_c) if registered_suite_regex_match: has_registered_test_suites = True if registered_suite_run_regex.search(main_c): has_run_registered_test_suites = True if test_main_regex.search(main_c): has_test_main = True if not suite_regex_match and not has_registered_test_suites: # can't find ztest_test_suite, maybe a client, because # it includes ztest.h return ScanPathResult( matches=None, warnings=None, has_registered_test_suites=has_registered_test_suites, has_run_registered_test_suites=has_run_registered_test_suites, has_test_main=has_test_main) suite_run_match = suite_run_regex.search(main_c) if suite_regex_match and not suite_run_match: raise ValueError("can't find ztest_run_test_suite") if suite_regex_match: search_start = suite_regex_match.end() else: search_start = registered_suite_regex_match.end() if suite_run_match: search_end = suite_run_match.start() else: search_end = re.compile(br"\);", re.MULTILINE) \ .search(main_c, search_start) \ .end() achtung_matches = re.findall( achtung_regex, main_c[search_start:search_end]) if achtung_matches: warnings = "found invalid %s in ztest_test_suite()" \ % ", ".join(sorted({match.decode() for match in achtung_matches},reverse = True)) _matches = re.findall( stc_regex, main_c[search_start:search_end]) for match in _matches: if not match.decode().startswith("test_"): warnings = "Found a test that does not start with test_" matches = [match.decode().replace("test_", "", 1) for match in _matches] return ScanPathResult( matches=matches, warnings=warnings, has_registered_test_suites=has_registered_test_suites, has_run_registered_test_suites=has_run_registered_test_suites, has_test_main=has_test_main) def scan_path(self, path): subcases = [] has_registered_test_suites = False has_run_registered_test_suites = False has_test_main = False for filename in glob.glob(os.path.join(path, "src", "*.c*")): try: result: ScanPathResult = self.scan_file(filename) if result.warnings: logger.error("%s: %s" % (filename, result.warnings)) raise TwisterRuntimeError( "%s: %s" % (filename, result.warnings)) if result.matches: subcases += result.matches if result.has_registered_test_suites: has_registered_test_suites = True if result.has_run_registered_test_suites: has_run_registered_test_suites = True if result.has_test_main: has_test_main = True except ValueError as e: logger.error("%s: can't find: %s" % (filename, e)) for filename in glob.glob(os.path.join(path, "*.c")): try: result: ScanPathResult = self.scan_file(filename) if result.warnings: logger.error("%s: %s" % (filename, result.warnings)) if result.matches: subcases += result.matches except ValueError as e: logger.error("%s: can't find: %s" % (filename, e)) if (has_registered_test_suites and has_test_main and not has_run_registered_test_suites): warning = \ "Found call to 'ztest_register_test_suite()' but no "\ "call to 'ztest_run_registered_test_suites()'" logger.error(warning) raise TwisterRuntimeError(warning) return subcases def parse_subcases(self, test_path): results = self.scan_path(test_path) for sub in results: name = "{}.{}".format(self.id, sub) self.cases.append(name) if not results: self.cases.append(self.id) def __str__(self): return self.name class TestInstance(DisablePyTestCollectionMixin): """Class representing the execution of a particular TestCase on a platform @param test The TestCase object we want to build/execute @param platform Platform object that we want to build and run against @param base_outdir Base directory for all test results. The actual out directory used is <outdir>/<platform>/<test case name> """ def __init__(self, testcase, platform, outdir): self.testcase = testcase self.platform = platform self.status = None self.reason = "Unknown" self.metrics = dict() self.handler = None self.outdir = outdir self.name = os.path.join(platform.name, testcase.name) self.build_dir = os.path.join(outdir, platform.name, testcase.name) self.run = False self.results = {} def __getstate__(self): d = self.__dict__.copy() return d def __setstate__(self, d): self.__dict__.update(d) def __lt__(self, other): return self.name < other.name @staticmethod def testcase_runnable(testcase, fixtures): can_run = False # console harness allows us to run the test and capture data. if testcase.harness in [ 'console', 'ztest', 'pytest']: can_run = True # if we have a fixture that is also being supplied on the # command-line, then we need to run the test, not just build it. fixture = testcase.harness_config.get('fixture') if fixture: can_run = (fixture in fixtures) elif testcase.harness: can_run = False else: can_run = True return can_run # Global testsuite parameters def check_runnable(self, enable_slow=False, filter='buildable', fixtures=[]): # right now we only support building on windows. running is still work # in progress. if os.name == 'nt': return False # we asked for build-only on the command line if self.testcase.build_only: return False # Do not run slow tests: skip_slow = self.testcase.slow and not enable_slow if skip_slow: return False target_ready = bool(self.testcase.type == "unit" or \ self.platform.type == "native" or \ self.platform.simulation in ["mdb-nsim", "nsim", "renode", "qemu", "tsim", "armfvp", "xt-sim"] or \ filter == 'runnable') if self.platform.simulation == "nsim": if not find_executable("nsimdrv"): target_ready = False if self.platform.simulation == "mdb-nsim": if not find_executable("mdb"): target_ready = False if self.platform.simulation == "renode": if not find_executable("renode"): target_ready = False if self.platform.simulation == "tsim": if not find_executable("tsim-leon3"): target_ready = False testcase_runnable = self.testcase_runnable(self.testcase, fixtures) return testcase_runnable and target_ready def create_overlay(self, platform, enable_asan=False, enable_ubsan=False, enable_coverage=False, coverage_platform=[]): # Create this in a "twister/" subdirectory otherwise this # will pass this overlay to kconfig.py *twice* and kconfig.cmake # will silently give that second time precedence over any # --extra-args=CONFIG_* subdir = os.path.join(self.build_dir, "twister") content = "" if self.testcase.extra_configs: content = "\n".join(self.testcase.extra_configs) if enable_coverage: if platform.name in coverage_platform: content = content + "\nCONFIG_COVERAGE=y" content = content + "\nCONFIG_COVERAGE_DUMP=y" if enable_asan: if platform.type == "native": content = content + "\nCONFIG_ASAN=y" if enable_ubsan: if platform.type == "native": content = content + "\nCONFIG_UBSAN=y" if content: os.makedirs(subdir, exist_ok=True) file = os.path.join(subdir, "testcase_extra.conf") with open(file, "w") as f: f.write(content) return content def calculate_sizes(self): """Get the RAM/ROM sizes of a test case. This can only be run after the instance has been executed by MakeGenerator, otherwise there won't be any binaries to measure. @return A SizeCalculator object """ fns = glob.glob(os.path.join(self.build_dir, "zephyr", "*.elf")) fns.extend(glob.glob(os.path.join(self.build_dir, "zephyr", "*.exe"))) fns = [x for x in fns if '_pre' not in x] if len(fns) != 1: raise BuildError("Missing/multiple output ELF binary") return SizeCalculator(fns[0], self.testcase.extra_sections) def fill_results_by_status(self): """Fills results according to self.status The method is used to propagate the instance level status to the test cases inside. Useful when the whole instance is skipped and the info is required also at the test cases level for reporting. Should be used with caution, e.g. should not be used to fill all results with passes """ status_to_verdict = { 'skipped': 'SKIP', 'error': 'BLOCK', 'failure': 'FAILED' } for k in self.results: self.results[k] = status_to_verdict[self.status] def __repr__(self): return "<TestCase %s on %s>" % (self.testcase.name, self.platform.name) class CMake(): config_re = re.compile('(CONFIG_[A-Za-z0-9_]+)[=]\"?([^\"]*)\"?$') dt_re = re.compile('([A-Za-z0-9_]+)[=]\"?([^\"]*)\"?$') def __init__(self, testcase, platform, source_dir, build_dir): self.cwd = None self.capture_output = True self.defconfig = {} self.cmake_cache = {} self.instance = None self.testcase = testcase self.platform = platform self.source_dir = source_dir self.build_dir = build_dir self.log = "build.log" self.generator = None self.generator_cmd = None def parse_generated(self): self.defconfig = {} return {} def run_build(self, args=[]): logger.debug("Building %s for %s" % (self.source_dir, self.platform.name)) cmake_args = [] cmake_args.extend(args) cmake = shutil.which('cmake') cmd = [cmake] + cmake_args kwargs = dict() if self.capture_output: kwargs['stdout'] = subprocess.PIPE # CMake sends the output of message() to stderr unless it's STATUS kwargs['stderr'] = subprocess.STDOUT if self.cwd: kwargs['cwd'] = self.cwd p = subprocess.Popen(cmd, **kwargs) out, _ = p.communicate() results = {} if p.returncode == 0: msg = "Finished building %s for %s" % (self.source_dir, self.platform.name) self.instance.status = "passed" results = {'msg': msg, "returncode": p.returncode, "instance": self.instance} if out: log_msg = out.decode(sys.getdefaultencoding()) with open(os.path.join(self.build_dir, self.log), "a") as log: log.write(log_msg) else: return None else: # A real error occurred, raise an exception log_msg = "" if out: log_msg = out.decode(sys.getdefaultencoding()) with open(os.path.join(self.build_dir, self.log), "a") as log: log.write(log_msg) if log_msg: res = re.findall("region `(FLASH|ROM|RAM|ICCM|DCCM|SRAM)' overflowed by", log_msg) if res and not self.overflow_as_errors: logger.debug("Test skipped due to {} Overflow".format(res[0])) self.instance.status = "skipped" self.instance.reason = "{} overflow".format(res[0]) else: self.instance.status = "error" self.instance.reason = "Build failure" results = { "returncode": p.returncode, "instance": self.instance, } return results def run_cmake(self, args=[]): if self.warnings_as_errors: ldflags = "-Wl,--fatal-warnings" cflags = "-Werror" aflags = "-Werror -Wa,--fatal-warnings" gen_defines_args = "--edtlib-Werror" else: ldflags = cflags = aflags = "" gen_defines_args = "" logger.debug("Running cmake on %s for %s" % (self.source_dir, self.platform.name)) cmake_args = [ f'-B{self.build_dir}', f'-S{self.source_dir}', f'-DEXTRA_CFLAGS={cflags}', f'-DEXTRA_AFLAGS={aflags}', f'-DEXTRA_LDFLAGS={ldflags}', f'-DEXTRA_GEN_DEFINES_ARGS={gen_defines_args}', f'-G{self.generator}' ] args = ["-D{}".format(a.replace('"', '')) for a in args] cmake_args.extend(args) cmake_opts = ['-DBOARD={}'.format(self.platform.name)] cmake_args.extend(cmake_opts) logger.debug("Calling cmake with arguments: {}".format(cmake_args)) cmake = shutil.which('cmake') cmd = [cmake] + cmake_args kwargs = dict() if self.capture_output: kwargs['stdout'] = subprocess.PIPE # CMake sends the output of message() to stderr unless it's STATUS kwargs['stderr'] = subprocess.STDOUT if self.cwd: kwargs['cwd'] = self.cwd p = subprocess.Popen(cmd, **kwargs) out, _ = p.communicate() if p.returncode == 0: filter_results = self.parse_generated() msg = "Finished building %s for %s" % (self.source_dir, self.platform.name) logger.debug(msg) results = {'msg': msg, 'filter': filter_results} else: self.instance.status = "error" self.instance.reason = "Cmake build failure" self.instance.fill_results_by_status() logger.error("Cmake build failure: %s for %s" % (self.source_dir, self.platform.name)) results = {"returncode": p.returncode} if out: with open(os.path.join(self.build_dir, self.log), "a") as log: log_msg = out.decode(sys.getdefaultencoding()) log.write(log_msg) return results @staticmethod def run_cmake_script(args=[]): logger.debug("Running cmake script %s" % (args[0])) cmake_args = ["-D{}".format(a.replace('"', '')) for a in args[1:]] cmake_args.extend(['-P', args[0]]) logger.debug("Calling cmake with arguments: {}".format(cmake_args)) cmake = shutil.which('cmake') if not cmake: msg = "Unable to find `cmake` in path" logger.error(msg) raise Exception(msg) cmd = [cmake] + cmake_args kwargs = dict() kwargs['stdout'] = subprocess.PIPE # CMake sends the output of message() to stderr unless it's STATUS kwargs['stderr'] = subprocess.STDOUT p = subprocess.Popen(cmd, **kwargs) out, _ = p.communicate() # It might happen that the environment adds ANSI escape codes like \x1b[0m, # for instance if twister is executed from inside a makefile. In such a # scenario it is then necessary to remove them, as otherwise the JSON decoding # will fail. ansi_escape = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])') out = ansi_escape.sub('', out.decode()) if p.returncode == 0: msg = "Finished running %s" % (args[0]) logger.debug(msg) results = {"returncode": p.returncode, "msg": msg, "stdout": out} else: logger.error("Cmake script failure: %s" % (args[0])) results = {"returncode": p.returncode, "returnmsg": out} return results class FilterBuilder(CMake): def __init__(self, testcase, platform, source_dir, build_dir): super().__init__(testcase, platform, source_dir, build_dir) self.log = "config-twister.log" def parse_generated(self): if self.platform.name == "unit_testing": return {} cmake_cache_path = os.path.join(self.build_dir, "CMakeCache.txt") defconfig_path = os.path.join(self.build_dir, "zephyr", ".config") with open(defconfig_path, "r") as fp: defconfig = {} for line in fp.readlines(): m = self.config_re.match(line) if not m: if line.strip() and not line.startswith("#"): sys.stderr.write("Unrecognized line %s\n" % line) continue defconfig[m.group(1)] = m.group(2).strip() self.defconfig = defconfig cmake_conf = {} try: cache = CMakeCache.from_file(cmake_cache_path) except FileNotFoundError: cache = {} for k in iter(cache): cmake_conf[k.name] = k.value self.cmake_cache = cmake_conf filter_data = { "ARCH": self.platform.arch, "PLATFORM": self.platform.name } filter_data.update(os.environ) filter_data.update(self.defconfig) filter_data.update(self.cmake_cache) edt_pickle = os.path.join(self.build_dir, "zephyr", "edt.pickle") if self.testcase and self.testcase.tc_filter: try: if os.path.exists(edt_pickle): with open(edt_pickle, 'rb') as f: edt = pickle.load(f) else: edt = None res = expr_parser.parse(self.testcase.tc_filter, filter_data, edt) except (ValueError, SyntaxError) as se: sys.stderr.write( "Failed processing %s\n" % self.testcase.yamlfile) raise se if not res: return {os.path.join(self.platform.name, self.testcase.name): True} else: return {os.path.join(self.platform.name, self.testcase.name): False} else: self.platform.filter_data = filter_data return filter_data class ProjectBuilder(FilterBuilder): def __init__(self, suite, instance, **kwargs): super().__init__(instance.testcase, instance.platform, instance.testcase.source_dir, instance.build_dir) self.log = "build.log" self.instance = instance self.suite = suite self.filtered_tests = 0 self.lsan = kwargs.get('lsan', False) self.asan = kwargs.get('asan', False) self.ubsan = kwargs.get('ubsan', False) self.valgrind = kwargs.get('valgrind', False) self.extra_args = kwargs.get('extra_args', []) self.device_testing = kwargs.get('device_testing', False) self.cmake_only = kwargs.get('cmake_only', False) self.cleanup = kwargs.get('cleanup', False) self.coverage = kwargs.get('coverage', False) self.inline_logs = kwargs.get('inline_logs', False) self.generator = kwargs.get('generator', None) self.generator_cmd = kwargs.get('generator_cmd', None) self.verbose = kwargs.get('verbose', None) self.warnings_as_errors = kwargs.get('warnings_as_errors', True) self.overflow_as_errors = kwargs.get('overflow_as_errors', False) @staticmethod def log_info(filename, inline_logs): filename = os.path.abspath(os.path.realpath(filename)) if inline_logs: logger.info("{:-^100}".format(filename)) try: with open(filename) as fp: data = fp.read() except Exception as e: data = "Unable to read log data (%s)\n" % (str(e)) logger.error(data) logger.info("{:-^100}".format(filename)) else: logger.error("see: " + Fore.YELLOW + filename + Fore.RESET) def log_info_file(self, inline_logs): build_dir = self.instance.build_dir h_log = "{}/handler.log".format(build_dir) b_log = "{}/build.log".format(build_dir) v_log = "{}/valgrind.log".format(build_dir) d_log = "{}/device.log".format(build_dir) if os.path.exists(v_log) and "Valgrind" in self.instance.reason: self.log_info("{}".format(v_log), inline_logs) elif os.path.exists(h_log) and os.path.getsize(h_log) > 0: self.log_info("{}".format(h_log), inline_logs) elif os.path.exists(d_log) and os.path.getsize(d_log) > 0: self.log_info("{}".format(d_log), inline_logs) else: self.log_info("{}".format(b_log), inline_logs) def setup_handler(self): instance = self.instance args = [] # FIXME: Needs simplification if instance.platform.simulation == "qemu": instance.handler = QEMUHandler(instance, "qemu") args.append("QEMU_PIPE=%s" % instance.handler.get_fifo()) instance.handler.call_make_run = True elif instance.testcase.type == "unit": instance.handler = BinaryHandler(instance, "unit") instance.handler.binary = os.path.join(instance.build_dir, "testbinary") if self.coverage: args.append("COVERAGE=1") elif instance.platform.type == "native": handler = BinaryHandler(instance, "native") handler.asan = self.asan handler.valgrind = self.valgrind handler.lsan = self.lsan handler.ubsan = self.ubsan handler.coverage = self.coverage handler.binary = os.path.join(instance.build_dir, "zephyr", "zephyr.exe") instance.handler = handler elif instance.platform.simulation == "renode": if find_executable("renode"): instance.handler = BinaryHandler(instance, "renode") instance.handler.pid_fn = os.path.join(instance.build_dir, "renode.pid") instance.handler.call_make_run = True elif instance.platform.simulation == "tsim": instance.handler = BinaryHandler(instance, "tsim") instance.handler.call_make_run = True elif self.device_testing: instance.handler = DeviceHandler(instance, "device") instance.handler.coverage = self.coverage elif instance.platform.simulation == "nsim": if find_executable("nsimdrv"): instance.handler = BinaryHandler(instance, "nsim") instance.handler.call_make_run = True elif instance.platform.simulation == "mdb-nsim": if find_executable("mdb"): instance.handler = BinaryHandler(instance, "nsim") instance.handler.call_make_run = True elif instance.platform.simulation == "armfvp": instance.handler = BinaryHandler(instance, "armfvp") instance.handler.call_make_run = True elif instance.platform.simulation == "xt-sim": instance.handler = BinaryHandler(instance, "xt-sim") instance.handler.call_make_run = True if instance.handler: instance.handler.args = args instance.handler.generator_cmd = self.generator_cmd instance.handler.generator = self.generator def process(self, pipeline, done, message, lock, results): op = message.get('op') if not self.instance.handler: self.setup_handler() # The build process, call cmake and build with configured generator if op == "cmake": res = self.cmake() if self.instance.status in ["failed", "error"]: pipeline.put({"op": "report", "test": self.instance}) elif self.cmake_only: if self.instance.status is None: self.instance.status = "passed" pipeline.put({"op": "report", "test": self.instance}) else: if self.instance.name in res['filter'] and res['filter'][self.instance.name]: logger.debug("filtering %s" % self.instance.name) self.instance.status = "skipped" self.instance.reason = "filter" results.skipped_runtime += 1 for case in self.instance.testcase.cases: self.instance.results.update({case: 'SKIP'}) pipeline.put({"op": "report", "test": self.instance}) else: pipeline.put({"op": "build", "test": self.instance}) elif op == "build": logger.debug("build test: %s" % self.instance.name) res = self.build() if not res: self.instance.status = "error" self.instance.reason = "Build Failure" pipeline.put({"op": "report", "test": self.instance}) else: # Count skipped cases during build, for example # due to ram/rom overflow. inst = res.get("instance", None) if inst and inst.status == "skipped": results.skipped_runtime += 1 if res.get('returncode', 1) > 0: pipeline.put({"op": "report", "test": self.instance}) else: if self.instance.run and self.instance.handler: pipeline.put({"op": "run", "test": self.instance}) else: pipeline.put({"op": "report", "test": self.instance}) # Run the generated binary using one of the supported handlers elif op == "run": logger.debug("run test: %s" % self.instance.name) self.run() self.instance.status, _ = self.instance.handler.get_state() logger.debug(f"run status: {self.instance.name} {self.instance.status}") # to make it work with pickle self.instance.handler.thread = None self.instance.handler.suite = None pipeline.put({ "op": "report", "test": self.instance, "status": self.instance.status, "reason": self.instance.reason } ) # Report results and output progress to screen elif op == "report": with lock: done.put(self.instance) self.report_out(results) if self.cleanup and not self.coverage and self.instance.status == "passed": pipeline.put({ "op": "cleanup", "test": self.instance }) elif op == "cleanup": if self.device_testing: self.cleanup_device_testing_artifacts() else: self.cleanup_artifacts() def cleanup_artifacts(self, additional_keep=[]): logger.debug("Cleaning up {}".format(self.instance.build_dir)) allow = [ 'zephyr/.config', 'handler.log', 'build.log', 'device.log', 'recording.csv', ] allow += additional_keep allow = [os.path.join(self.instance.build_dir, file) for file in allow] for dirpath, dirnames, filenames in os.walk(self.instance.build_dir, topdown=False): for name in filenames: path = os.path.join(dirpath, name) if path not in allow: os.remove(path) # Remove empty directories and symbolic links to directories for dir in dirnames: path = os.path.join(dirpath, dir) if os.path.islink(path): os.remove(path) elif not os.listdir(path): os.rmdir(path) def cleanup_device_testing_artifacts(self): logger.debug("Cleaning up for Device Testing {}".format(self.instance.build_dir)) sanitizelist = [ 'CMakeCache.txt', 'zephyr/runners.yaml', ] keep = [ 'zephyr/zephyr.hex', 'zephyr/zephyr.bin', 'zephyr/zephyr.elf', ] keep += sanitizelist self.cleanup_artifacts(keep) # sanitize paths so files are relocatable for file in sanitizelist: file = os.path.join(self.instance.build_dir, file) with open(file, "rt") as fin: data = fin.read() data = data.replace(canonical_zephyr_base+"/", "") with open(file, "wt") as fin: fin.write(data) def report_out(self, results): total_to_do = results.total - results.skipped_configs total_tests_width = len(str(total_to_do)) results.done += 1 instance = self.instance if instance.status in ["error", "failed", "timeout", "flash_error"]: if instance.status == "error": results.error += 1 results.failed += 1 if self.verbose: status = Fore.RED + "FAILED " + Fore.RESET + instance.reason else: print("") logger.error( "{:<25} {:<50} {}FAILED{}: {}".format( instance.platform.name, instance.testcase.name, Fore.RED, Fore.RESET, instance.reason)) if not self.verbose: self.log_info_file(self.inline_logs) elif instance.status == "skipped": status = Fore.YELLOW + "SKIPPED" + Fore.RESET elif instance.status == "passed": status = Fore.GREEN + "PASSED" + Fore.RESET else: logger.debug(f"Unknown status = {instance.status}") status = Fore.YELLOW + "UNKNOWN" + Fore.RESET if self.verbose: if self.cmake_only: more_info = "cmake" elif instance.status == "skipped": more_info = instance.reason else: if instance.handler and instance.run: more_info = instance.handler.type_str htime = instance.handler.duration if htime: more_info += " {:.3f}s".format(htime) else: more_info = "build" logger.info("{:>{}}/{} {:<25} {:<50} {} ({})".format( results.done, total_tests_width, total_to_do, instance.platform.name, instance.testcase.name, status, more_info)) if instance.status in ["error", "failed", "timeout"]: self.log_info_file(self.inline_logs) else: completed_perc = 0 if total_to_do > 0: completed_perc = int((float(results.done) / total_to_do) * 100) skipped = results.skipped_configs + results.skipped_runtime sys.stdout.write("\rINFO - Total complete: %s%4d/%4d%s %2d%% skipped: %s%4d%s, failed: %s%4d%s" % ( Fore.GREEN, results.done, total_to_do, Fore.RESET, completed_perc, Fore.YELLOW if skipped > 0 else Fore.RESET, skipped, Fore.RESET, Fore.RED if results.failed > 0 else Fore.RESET, results.failed, Fore.RESET ) ) sys.stdout.flush() def cmake(self): instance = self.instance args = self.testcase.extra_args[:] args += self.extra_args if instance.handler: args += instance.handler.args # merge overlay files into one variable def extract_overlays(args): re_overlay = re.compile('OVERLAY_CONFIG=(.*)') other_args = [] overlays = [] for arg in args: match = re_overlay.search(arg) if match: overlays.append(match.group(1).strip('\'"')) else: other_args.append(arg) args[:] = other_args return overlays overlays = extract_overlays(args) if os.path.exists(os.path.join(instance.build_dir, "twister", "testcase_extra.conf")): overlays.append(os.path.join(instance.build_dir, "twister", "testcase_extra.conf")) if overlays: args.append("OVERLAY_CONFIG=\"%s\"" % (" ".join(overlays))) res = self.run_cmake(args) return res def build(self): res = self.run_build(['--build', self.build_dir]) return res def run(self): instance = self.instance if instance.handler: if instance.handler.type_str == "device": instance.handler.suite = self.suite instance.handler.handle() sys.stdout.flush() class TestSuite(DisablePyTestCollectionMixin): config_re = re.compile('(CONFIG_[A-Za-z0-9_]+)[=]\"?([^\"]*)\"?$') dt_re = re.compile('([A-Za-z0-9_]+)[=]\"?([^\"]*)\"?$') tc_schema = scl.yaml_load( os.path.join(ZEPHYR_BASE, "scripts", "schemas", "twister", "testcase-schema.yaml")) quarantine_schema = scl.yaml_load( os.path.join(ZEPHYR_BASE, "scripts", "schemas", "twister", "quarantine-schema.yaml")) testcase_valid_keys = {"tags": {"type": "set", "required": False}, "type": {"type": "str", "default": "integration"}, "extra_args": {"type": "list"}, "extra_configs": {"type": "list"}, "build_only": {"type": "bool", "default": False}, "build_on_all": {"type": "bool", "default": False}, "skip": {"type": "bool", "default": False}, "slow": {"type": "bool", "default": False}, "timeout": {"type": "int", "default": 60}, "min_ram": {"type": "int", "default": 8}, "depends_on": {"type": "set"}, "min_flash": {"type": "int", "default": 32}, "arch_allow": {"type": "set"}, "arch_exclude": {"type": "set"}, "extra_sections": {"type": "list", "default": []}, "integration_platforms": {"type": "list", "default": []}, "platform_exclude": {"type": "set"}, "platform_allow": {"type": "set"}, "toolchain_exclude": {"type": "set"}, "toolchain_allow": {"type": "set"}, "filter": {"type": "str"}, "harness": {"type": "str"}, "harness_config": {"type": "map", "default": {}} } RELEASE_DATA = os.path.join(ZEPHYR_BASE, "scripts", "release", "twister_last_release.csv") SAMPLE_FILENAME = 'sample.yaml' TESTCASE_FILENAME = 'testcase.yaml' def __init__(self, board_root_list=[], testcase_roots=[], outdir=None): self.roots = testcase_roots if not isinstance(board_root_list, list): self.board_roots = [board_root_list] else: self.board_roots = board_root_list # Testsuite Options self.coverage_platform = [] self.build_only = False self.cmake_only = False self.cleanup = False self.enable_slow = False self.device_testing = False self.fixtures = [] self.enable_coverage = False self.enable_ubsan = False self.enable_lsan = False self.enable_asan = False self.enable_valgrind = False self.extra_args = [] self.inline_logs = False self.enable_sizes_report = False self.west_flash = None self.west_runner = None self.generator = None self.generator_cmd = None self.warnings_as_errors = True self.overflow_as_errors = False self.quarantine_verify = False # Keep track of which test cases we've filtered out and why self.testcases = {} self.quarantine = {} self.platforms = [] self.platform_names = [] self.selected_platforms = [] self.filtered_platforms = [] self.default_platforms = [] self.outdir = os.path.abspath(outdir) self.discards = {} self.load_errors = 0 self.instances = dict() self.total_platforms = 0 self.start_time = 0 self.duration = 0 self.warnings = 0 # hardcoded for now self.duts = [] # run integration tests only self.integration = False # used during creating shorter build paths self.link_dir_counter = 0 self.pipeline = None self.version = "NA" def check_zephyr_version(self): try: subproc = subprocess.run(["git", "describe", "--abbrev=12"], stdout=subprocess.PIPE, universal_newlines=True, cwd=ZEPHYR_BASE) if subproc.returncode == 0: self.version = subproc.stdout.strip() logger.info(f"Zephyr version: {self.version}") except OSError: logger.info("Cannot read zephyr version.") def get_platform_instances(self, platform): filtered_dict = {k:v for k,v in self.instances.items() if k.startswith(platform + os.sep)} return filtered_dict def config(self): logger.info("coverage platform: {}".format(self.coverage_platform)) # Debug Functions @staticmethod def info(what): sys.stdout.write(what + "\n") sys.stdout.flush() def update_counting(self, results=None, initial=False): results.skipped_configs = 0 results.skipped_cases = 0 for instance in self.instances.values(): if initial: results.cases += len(instance.testcase.cases) if instance.status == 'skipped': results.skipped_configs += 1 results.skipped_cases += len(instance.testcase.cases) elif instance.status == "passed": results.passed += 1 for res in instance.results.values(): if res == 'SKIP': results.skipped_cases += 1 def compare_metrics(self, filename): # name, datatype, lower results better interesting_metrics = [("ram_size", int, True), ("rom_size", int, True)] if not os.path.exists(filename): logger.error("Cannot compare metrics, %s not found" % filename) return [] results = [] saved_metrics = {} with open(filename) as fp: cr = csv.DictReader(fp) for row in cr: d = {} for m, _, _ in interesting_metrics: d[m] = row[m] saved_metrics[(row["test"], row["platform"])] = d for instance in self.instances.values(): mkey = (instance.testcase.name, instance.platform.name) if mkey not in saved_metrics: continue sm = saved_metrics[mkey] for metric, mtype, lower_better in interesting_metrics: if metric not in instance.metrics: continue if sm[metric] == "": continue delta = instance.metrics.get(metric, 0) - mtype(sm[metric]) if delta == 0: continue results.append((instance, metric, instance.metrics.get(metric, 0), delta, lower_better)) return results def footprint_reports(self, report, show_footprint, all_deltas, footprint_threshold, last_metrics): if not report: return logger.debug("running footprint_reports") deltas = self.compare_metrics(report) warnings = 0 if deltas and show_footprint: for i, metric, value, delta, lower_better in deltas: if not all_deltas and ((delta < 0 and lower_better) or (delta > 0 and not lower_better)): continue percentage = 0 if value > delta: percentage = (float(delta) / float(value - delta)) if not all_deltas and (percentage < (footprint_threshold / 100.0)): continue logger.info("{:<25} {:<60} {}{}{}: {} {:<+4}, is now {:6} {:+.2%}".format( i.platform.name, i.testcase.name, Fore.YELLOW, "INFO" if all_deltas else "WARNING", Fore.RESET, metric, delta, value, percentage)) warnings += 1 if warnings: logger.warning("Deltas based on metrics from last %s" % ("release" if not last_metrics else "run")) def summary(self, results, unrecognized_sections): failed = 0 run = 0 for instance in self.instances.values(): if instance.status == "failed": failed += 1 elif instance.metrics.get("unrecognized") and not unrecognized_sections: logger.error("%sFAILED%s: %s has unrecognized binary sections: %s" % (Fore.RED, Fore.RESET, instance.name, str(instance.metrics.get("unrecognized", [])))) failed += 1 if instance.metrics.get('handler_time', None): run += 1 if results.total and results.total != results.skipped_configs: pass_rate = (float(results.passed) / float(results.total - results.skipped_configs)) else: pass_rate = 0 logger.info( "{}{} of {}{} test configurations passed ({:.2%}), {}{}{} failed, {} skipped with {}{}{} warnings in {:.2f} seconds".format( Fore.RED if failed else Fore.GREEN, results.passed, results.total - results.skipped_configs, Fore.RESET, pass_rate, Fore.RED if results.failed else Fore.RESET, results.failed, Fore.RESET, results.skipped_configs, Fore.YELLOW if self.warnings else Fore.RESET, self.warnings, Fore.RESET, self.duration)) self.total_platforms = len(self.platforms) # if we are only building, do not report about tests being executed. if self.platforms and not self.build_only: logger.info("In total {} test cases were executed, {} skipped on {} out of total {} platforms ({:02.2f}%)".format( results.cases - results.skipped_cases, results.skipped_cases, len(self.filtered_platforms), self.total_platforms, (100 * len(self.filtered_platforms) / len(self.platforms)) )) logger.info(f"{Fore.GREEN}{run}{Fore.RESET} test configurations executed on platforms, \ {Fore.RED}{results.total - run - results.skipped_configs}{Fore.RESET} test configurations were only built.") def save_reports(self, name, suffix, report_dir, no_update, release, only_failed, platform_reports, json_report): if not self.instances: return logger.info("Saving reports...") if name: report_name = name else: report_name = "twister" if report_dir: os.makedirs(report_dir, exist_ok=True) filename = os.path.join(report_dir, report_name) outdir = report_dir else: filename = os.path.join(self.outdir, report_name) outdir = self.outdir if suffix: filename = "{}_{}".format(filename, suffix) if not no_update: self.xunit_report(filename + ".xml", full_report=False, append=only_failed, version=self.version) self.xunit_report(filename + "_report.xml", full_report=True, append=only_failed, version=self.version) self.csv_report(filename + ".csv") if json_report: self.json_report(filename + ".json", append=only_failed, version=self.version) if platform_reports: self.target_report(outdir, suffix, append=only_failed) if self.discards: self.discard_report(filename + "_discard.csv") if release: self.csv_report(self.RELEASE_DATA) def add_configurations(self): for board_root in self.board_roots: board_root = os.path.abspath(board_root) logger.debug("Reading platform configuration files under %s..." % board_root) for file in glob.glob(os.path.join(board_root, "*", "*", "*.yaml")): try: platform = Platform() platform.load(file) if platform.name in [p.name for p in self.platforms]: logger.error(f"Duplicate platform {platform.name} in {file}") raise Exception(f"Duplicate platform identifier {platform.name} found") if platform.twister: self.platforms.append(platform) if platform.default: self.default_platforms.append(platform.name) except RuntimeError as e: logger.error("E: %s: can't load: %s" % (file, e)) self.load_errors += 1 self.platform_names = [p.name for p in self.platforms] def get_all_tests(self): tests = [] for _, tc in self.testcases.items(): for case in tc.cases: tests.append(case) return tests @staticmethod def get_toolchain(): toolchain_script = Path(ZEPHYR_BASE) / Path('cmake/modules/verify-toolchain.cmake') result = CMake.run_cmake_script([toolchain_script, "FORMAT=json"]) try: if result['returncode']: raise TwisterRuntimeError(f"E: {result['returnmsg']}") except Exception as e: print(str(e)) sys.exit(2) toolchain = json.loads(result['stdout'])['ZEPHYR_TOOLCHAIN_VARIANT'] logger.info(f"Using '{toolchain}' toolchain.") return toolchain def add_testcases(self, testcase_filter=[]): for root in self.roots: root = os.path.abspath(root) logger.debug("Reading test case configuration files under %s..." % root) for dirpath, _, filenames in os.walk(root, topdown=True): if self.SAMPLE_FILENAME in filenames: filename = self.SAMPLE_FILENAME elif self.TESTCASE_FILENAME in filenames: filename = self.TESTCASE_FILENAME else: continue logger.debug("Found possible test case in " + dirpath) tc_path = os.path.join(dirpath, filename) try: parsed_data = TwisterConfigParser(tc_path, self.tc_schema) parsed_data.load() tc_path = os.path.dirname(tc_path) workdir = os.path.relpath(tc_path, root) for name in parsed_data.tests.keys(): tc = TestCase(root, workdir, name) tc_dict = parsed_data.get_test(name, self.testcase_valid_keys) tc.source_dir = tc_path tc.yamlfile = tc_path tc.type = tc_dict["type"] tc.tags = tc_dict["tags"] tc.extra_args = tc_dict["extra_args"] tc.extra_configs = tc_dict["extra_configs"] tc.arch_allow = tc_dict["arch_allow"] tc.arch_exclude = tc_dict["arch_exclude"] tc.skip = tc_dict["skip"] tc.platform_exclude = tc_dict["platform_exclude"] tc.platform_allow = tc_dict["platform_allow"] tc.toolchain_exclude = tc_dict["toolchain_exclude"] tc.toolchain_allow = tc_dict["toolchain_allow"] tc.tc_filter = tc_dict["filter"] tc.timeout = tc_dict["timeout"] tc.harness = tc_dict["harness"] tc.harness_config = tc_dict["harness_config"] if tc.harness == 'console' and not tc.harness_config: raise Exception('Harness config error: console harness defined without a configuration.') tc.build_only = tc_dict["build_only"] tc.build_on_all = tc_dict["build_on_all"] tc.slow = tc_dict["slow"] tc.min_ram = tc_dict["min_ram"] tc.depends_on = tc_dict["depends_on"] tc.min_flash = tc_dict["min_flash"] tc.extra_sections = tc_dict["extra_sections"] tc.integration_platforms = tc_dict["integration_platforms"] tc.parse_subcases(tc_path) if testcase_filter: if tc.name and tc.name in testcase_filter: self.testcases[tc.name] = tc else: self.testcases[tc.name] = tc except Exception as e: logger.error("%s: can't load (skipping): %s" % (tc_path, e)) self.load_errors += 1 return len(self.testcases) def get_platform(self, name): selected_platform = None for platform in self.platforms: if platform.name == name: selected_platform = platform break return selected_platform def load_quarantine(self, file): """ Loads quarantine list from the given yaml file. Creates a dictionary of all tests configurations (platform + scenario: comment) that shall be skipped due to quarantine """ # Load yaml into quarantine_yaml quarantine_yaml = scl.yaml_load_verify(file, self.quarantine_schema) # Create quarantine_list with a product of the listed # platforms and scenarios for each entry in quarantine yaml quarantine_list = [] for quar_dict in quarantine_yaml: if quar_dict['platforms'][0] == "all": plat = self.platform_names else: plat = quar_dict['platforms'] comment = quar_dict.get('comment', "NA") quarantine_list.append([{".".join([p, s]): comment} for p in plat for s in quar_dict['scenarios']]) # Flatten the quarantine_list quarantine_list = [it for sublist in quarantine_list for it in sublist] # Change quarantine_list into a dictionary for d in quarantine_list: self.quarantine.update(d) def load_from_file(self, file, filter_status=[], filter_platform=[]): try: with open(file, "r") as fp: cr = csv.DictReader(fp) instance_list = [] for row in cr: if row["status"] in filter_status: continue test = row["test"] platform = self.get_platform(row["platform"]) if filter_platform and platform.name not in filter_platform: continue instance = TestInstance(self.testcases[test], platform, self.outdir) if self.device_testing: tfilter = 'runnable' else: tfilter = 'buildable' instance.run = instance.check_runnable( self.enable_slow, tfilter, self.fixtures ) instance.create_overlay(platform, self.enable_asan, self.enable_ubsan, self.enable_coverage, self.coverage_platform) instance_list.append(instance) self.add_instances(instance_list) except KeyError as e: logger.error("Key error while parsing tests file.({})".format(str(e))) sys.exit(2) except FileNotFoundError as e: logger.error("Couldn't find input file with list of tests. ({})".format(e)) sys.exit(2) def apply_filters(self, **kwargs): toolchain = self.get_toolchain() discards = {} platform_filter = kwargs.get('platform') exclude_platform = kwargs.get('exclude_platform', []) testcase_filter = kwargs.get('run_individual_tests', []) arch_filter = kwargs.get('arch') tag_filter = kwargs.get('tag') exclude_tag = kwargs.get('exclude_tag') all_filter = kwargs.get('all') runnable = kwargs.get('runnable') force_toolchain = kwargs.get('force_toolchain') force_platform = kwargs.get('force_platform') emu_filter = kwargs.get('emulation_only') logger.debug("platform filter: " + str(platform_filter)) logger.debug(" arch_filter: " + str(arch_filter)) logger.debug(" tag_filter: " + str(tag_filter)) logger.debug(" exclude_tag: " + str(exclude_tag)) default_platforms = False emulation_platforms = False if all_filter: logger.info("Selecting all possible platforms per test case") # When --all used, any --platform arguments ignored platform_filter = [] elif not platform_filter and not emu_filter: logger.info("Selecting default platforms per test case") default_platforms = True elif emu_filter: logger.info("Selecting emulation platforms per test case") emulation_platforms = True if platform_filter: self.verify_platforms_existence(platform_filter, f"platform_filter") platforms = list(filter(lambda p: p.name in platform_filter, self.platforms)) elif emu_filter: platforms = list(filter(lambda p: p.simulation != 'na', self.platforms)) elif arch_filter: platforms = list(filter(lambda p: p.arch in arch_filter, self.platforms)) elif default_platforms: platforms = list(filter(lambda p: p.default, self.platforms)) else: platforms = self.platforms logger.info("Building initial testcase list...") for tc_name, tc in self.testcases.items(): if tc.build_on_all and not platform_filter: platform_scope = self.platforms elif tc.integration_platforms and self.integration: self.verify_platforms_existence( tc.integration_platforms, f"{tc_name} - integration_platforms") platform_scope = list(filter(lambda item: item.name in tc.integration_platforms, \ self.platforms)) else: platform_scope = platforms integration = self.integration and tc.integration_platforms # If there isn't any overlap between the platform_allow list and the platform_scope # we set the scope to the platform_allow list if tc.platform_allow and not platform_filter and not integration: self.verify_platforms_existence( tc.platform_allow, f"{tc_name} - platform_allow") a = set(platform_scope) b = set(filter(lambda item: item.name in tc.platform_allow, self.platforms)) c = a.intersection(b) if not c: platform_scope = list(filter(lambda item: item.name in tc.platform_allow, \ self.platforms)) # list of instances per testcase, aka configurations. instance_list = [] for plat in platform_scope: instance = TestInstance(tc, plat, self.outdir) if runnable: tfilter = 'runnable' else: tfilter = 'buildable' instance.run = instance.check_runnable( self.enable_slow, tfilter, self.fixtures ) for t in tc.cases: instance.results[t] = None if runnable and self.duts: for h in self.duts: if h.platform == plat.name: if tc.harness_config.get('fixture') in h.fixtures: instance.run = True if not force_platform and plat.name in exclude_platform: discards[instance] = discards.get(instance, "Platform is excluded on command line.") if (plat.arch == "unit") != (tc.type == "unit"): # Discard silently continue if runnable and not instance.run: discards[instance] = discards.get(instance, "Not runnable on device") if self.integration and tc.integration_platforms and plat.name not in tc.integration_platforms: discards[instance] = discards.get(instance, "Not part of integration platforms") if tc.skip: discards[instance] = discards.get(instance, "Skip filter") if tag_filter and not tc.tags.intersection(tag_filter): discards[instance] = discards.get(instance, "Command line testcase tag filter") if exclude_tag and tc.tags.intersection(exclude_tag): discards[instance] = discards.get(instance, "Command line testcase exclude filter") if testcase_filter and tc_name not in testcase_filter: discards[instance] = discards.get(instance, "Testcase name filter") if arch_filter and plat.arch not in arch_filter: discards[instance] = discards.get(instance, "Command line testcase arch filter") if not force_platform: if tc.arch_allow and plat.arch not in tc.arch_allow: discards[instance] = discards.get(instance, "Not in test case arch allow list") if tc.arch_exclude and plat.arch in tc.arch_exclude: discards[instance] = discards.get(instance, "In test case arch exclude") if tc.platform_exclude and plat.name in tc.platform_exclude: discards[instance] = discards.get(instance, "In test case platform exclude") if tc.toolchain_exclude and toolchain in tc.toolchain_exclude: discards[instance] = discards.get(instance, "In test case toolchain exclude") if platform_filter and plat.name not in platform_filter: discards[instance] = discards.get(instance, "Command line platform filter") if tc.platform_allow and plat.name not in tc.platform_allow: discards[instance] = discards.get(instance, "Not in testcase platform allow list") if tc.toolchain_allow and toolchain not in tc.toolchain_allow: discards[instance] = discards.get(instance, "Not in testcase toolchain allow list") if not plat.env_satisfied: discards[instance] = discards.get(instance, "Environment ({}) not satisfied".format(", ".join(plat.env))) if not force_toolchain \ and toolchain and (toolchain not in plat.supported_toolchains) \ and "host" not in plat.supported_toolchains \ and tc.type != 'unit': discards[instance] = discards.get(instance, "Not supported by the toolchain") if plat.ram < tc.min_ram: discards[instance] = discards.get(instance, "Not enough RAM") if tc.depends_on: dep_intersection = tc.depends_on.intersection(set(plat.supported)) if dep_intersection != set(tc.depends_on): discards[instance] = discards.get(instance, "No hardware support") if plat.flash < tc.min_flash: discards[instance] = discards.get(instance, "Not enough FLASH") if set(plat.ignore_tags) & tc.tags: discards[instance] = discards.get(instance, "Excluded tags per platform (exclude_tags)") if plat.only_tags and not set(plat.only_tags) & tc.tags: discards[instance] = discards.get(instance, "Excluded tags per platform (only_tags)") test_configuration = ".".join([instance.platform.name, instance.testcase.id]) # skip quarantined tests if test_configuration in self.quarantine and not self.quarantine_verify: discards[instance] = discards.get(instance, f"Quarantine: {self.quarantine[test_configuration]}") # run only quarantined test to verify their statuses (skip everything else) if self.quarantine_verify and test_configuration not in self.quarantine: discards[instance] = discards.get(instance, "Not under quarantine") # if nothing stopped us until now, it means this configuration # needs to be added. instance_list.append(instance) # no configurations, so jump to next testcase if not instance_list: continue # if twister was launched with no platform options at all, we # take all default platforms if default_platforms and not tc.build_on_all and not integration: if tc.platform_allow: a = set(self.default_platforms) b = set(tc.platform_allow) c = a.intersection(b) if c: aa = list(filter(lambda tc: tc.platform.name in c, instance_list)) self.add_instances(aa) else: self.add_instances(instance_list) else: instances = list(filter(lambda tc: tc.platform.default, instance_list)) self.add_instances(instances) elif integration: instances = list(filter(lambda item: item.platform.name in tc.integration_platforms, instance_list)) self.add_instances(instances) elif emulation_platforms: self.add_instances(instance_list) for instance in list(filter(lambda inst: not inst.platform.simulation != 'na', instance_list)): discards[instance] = discards.get(instance, "Not an emulated platform") else: self.add_instances(instance_list) for _, case in self.instances.items(): case.create_overlay(case.platform, self.enable_asan, self.enable_ubsan, self.enable_coverage, self.coverage_platform) self.discards = discards self.selected_platforms = set(p.platform.name for p in self.instances.values()) remove_from_discards = [] # configurations to be removed from discards. for instance in self.discards: instance.reason = self.discards[instance] # If integration mode is on all skips on integration_platforms are treated as errors. if self.integration and instance.platform.name in instance.testcase.integration_platforms \ and "Quarantine" not in instance.reason: instance.status = "error" instance.reason += " but is one of the integration platforms" instance.fill_results_by_status() self.instances[instance.name] = instance # Such configuration has to be removed from discards to make sure it won't get skipped remove_from_discards.append(instance) else: instance.status = "skipped" instance.fill_results_by_status() self.filtered_platforms = set(p.platform.name for p in self.instances.values() if p.status != "skipped" ) # Remove from discards configururations that must not be discarded (e.g. integration_platforms when --integration was used) for instance in remove_from_discards: del self.discards[instance] return discards def add_instances(self, instance_list): for instance in instance_list: self.instances[instance.name] = instance @staticmethod def calc_one_elf_size(instance): if instance.status not in ["error", "failed", "skipped"]: if instance.platform.type != "native": size_calc = instance.calculate_sizes() instance.metrics["ram_size"] = size_calc.get_ram_size() instance.metrics["rom_size"] = size_calc.get_rom_size() instance.metrics["unrecognized"] = size_calc.unrecognized_sections() else: instance.metrics["ram_size"] = 0 instance.metrics["rom_size"] = 0 instance.metrics["unrecognized"] = [] instance.metrics["handler_time"] = instance.handler.duration if instance.handler else 0 def add_tasks_to_queue(self, pipeline, build_only=False, test_only=False): for instance in self.instances.values(): if build_only: instance.run = False if instance.status not in ['passed', 'skipped', 'error']: logger.debug(f"adding {instance.name}") instance.status = None if test_only and instance.run: pipeline.put({"op": "run", "test": instance}) else: pipeline.put({"op": "cmake", "test": instance}) # If the instance got 'error' status before, proceed to the report stage if instance.status == "error": pipeline.put({"op": "report", "test": instance}) def pipeline_mgr(self, pipeline, done_queue, lock, results): while True: try: task = pipeline.get_nowait() except queue.Empty: break else: test = task['test'] pb = ProjectBuilder(self, test, lsan=self.enable_lsan, asan=self.enable_asan, ubsan=self.enable_ubsan, coverage=self.enable_coverage, extra_args=self.extra_args, device_testing=self.device_testing, cmake_only=self.cmake_only, cleanup=self.cleanup, valgrind=self.enable_valgrind, inline_logs=self.inline_logs, generator=self.generator, generator_cmd=self.generator_cmd, verbose=self.verbose, warnings_as_errors=self.warnings_as_errors, overflow_as_errors=self.overflow_as_errors ) pb.process(pipeline, done_queue, task, lock, results) return True def execute(self, pipeline, done, results): lock = Lock() logger.info("Adding tasks to the queue...") self.add_tasks_to_queue(pipeline, self.build_only, self.test_only) logger.info("Added initial list of jobs to queue") processes = [] for job in range(self.jobs): logger.debug(f"Launch process {job}") p = Process(target=self.pipeline_mgr, args=(pipeline, done, lock, results, )) processes.append(p) p.start() try: for p in processes: p.join() except KeyboardInterrupt: logger.info("Execution interrupted") for p in processes: p.terminate() # FIXME: This needs to move out. if self.enable_size_report and not self.cmake_only: # Parallelize size calculation executor = concurrent.futures.ThreadPoolExecutor(self.jobs) futures = [executor.submit(self.calc_one_elf_size, instance) for instance in self.instances.values()] concurrent.futures.wait(futures) else: for instance in self.instances.values(): instance.metrics["ram_size"] = 0 instance.metrics["rom_size"] = 0 instance.metrics["handler_time"] = instance.handler.duration if instance.handler else 0 instance.metrics["unrecognized"] = [] return results def discard_report(self, filename): try: if not self.discards: raise TwisterRuntimeError("apply_filters() hasn't been run!") except Exception as e: logger.error(str(e)) sys.exit(2) with open(filename, "wt") as csvfile: fieldnames = ["test", "arch", "platform", "reason"] cw = csv.DictWriter(csvfile, fieldnames, lineterminator=os.linesep) cw.writeheader() for instance, reason in sorted(self.discards.items()): rowdict = {"test": instance.testcase.name, "arch": instance.platform.arch, "platform": instance.platform.name, "reason": reason} cw.writerow(rowdict) def target_report(self, outdir, suffix, append=False): platforms = {inst.platform.name for _, inst in self.instances.items()} for platform in platforms: if suffix: filename = os.path.join(outdir,"{}_{}.xml".format(platform, suffix)) else: filename = os.path.join(outdir,"{}.xml".format(platform)) self.xunit_report(filename, platform, full_report=True, append=append, version=self.version) @staticmethod def process_log(log_file): filtered_string = "" if os.path.exists(log_file): with open(log_file, "rb") as f: log = f.read().decode("utf-8") filtered_string = ''.join(filter(lambda x: x in string.printable, log)) return filtered_string def xunit_report(self, filename, platform=None, full_report=False, append=False, version="NA"): total = 0 fails = passes = errors = skips = 0 if platform: selected = [platform] logger.info(f"Writing target report for {platform}...") else: logger.info(f"Writing xunit report {filename}...") selected = self.selected_platforms if os.path.exists(filename) and append: tree = ET.parse(filename) eleTestsuites = tree.getroot() else: eleTestsuites = ET.Element('testsuites') for p in selected: inst = self.get_platform_instances(p) fails = 0 passes = 0 errors = 0 skips = 0 duration = 0 for _, instance in inst.items(): handler_time = instance.metrics.get('handler_time', 0) duration += handler_time if full_report and instance.run: for k in instance.results.keys(): if instance.results[k] == 'PASS': passes += 1 elif instance.results[k] == 'BLOCK': errors += 1 elif instance.results[k] == 'SKIP' or instance.status in ['skipped']: skips += 1 else: fails += 1 else: if instance.status in ["error", "failed", "timeout", "flash_error"]: if instance.reason in ['build_error', 'handler_crash']: errors += 1 else: fails += 1 elif instance.status == 'skipped': skips += 1 elif instance.status == 'passed': passes += 1 else: if instance.status: logger.error(f"{instance.name}: Unknown status {instance.status}") else: logger.error(f"{instance.name}: No status") total = (errors + passes + fails + skips) # do not produce a report if no tests were actually run (only built) if total == 0: continue run = p eleTestsuite = None # When we re-run the tests, we re-use the results and update only with # the newly run tests. if os.path.exists(filename) and append: ts = eleTestsuites.findall(f'testsuite/[@name="{p}"]') if ts: eleTestsuite = ts[0] eleTestsuite.attrib['failures'] = "%d" % fails eleTestsuite.attrib['errors'] = "%d" % errors eleTestsuite.attrib['skipped'] = "%d" % skips else: logger.info(f"Did not find any existing results for {p}") eleTestsuite = ET.SubElement(eleTestsuites, 'testsuite', name=run, time="%f" % duration, tests="%d" % (total), failures="%d" % fails, errors="%d" % (errors), skipped="%s" % (skips)) eleTSPropetries = ET.SubElement(eleTestsuite, 'properties') # Multiple 'property' can be added to 'properties' # differing by name and value ET.SubElement(eleTSPropetries, 'property', name="version", value=version) else: eleTestsuite = ET.SubElement(eleTestsuites, 'testsuite', name=run, time="%f" % duration, tests="%d" % (total), failures="%d" % fails, errors="%d" % (errors), skipped="%s" % (skips)) eleTSPropetries = ET.SubElement(eleTestsuite, 'properties') # Multiple 'property' can be added to 'properties' # differing by name and value ET.SubElement(eleTSPropetries, 'property', name="version", value=version) for _, instance in inst.items(): if full_report: tname = os.path.basename(instance.testcase.name) else: tname = instance.testcase.id handler_time = instance.metrics.get('handler_time', 0) if full_report: for k in instance.results.keys(): # remove testcases that are being re-run from exiting reports for tc in eleTestsuite.findall(f'testcase/[@name="{k}"]'): eleTestsuite.remove(tc) classname = ".".join(tname.split(".")[:2]) eleTestcase = ET.SubElement( eleTestsuite, 'testcase', classname=classname, name="%s" % (k), time="%f" % handler_time) if instance.results[k] in ['FAIL', 'BLOCK'] or \ (not instance.run and instance.status in ["error", "failed", "timeout"]): if instance.results[k] == 'FAIL': el = ET.SubElement( eleTestcase, 'failure', type="failure", message="failed") else: el = ET.SubElement( eleTestcase, 'error', type="failure", message=instance.reason) log_root = os.path.join(self.outdir, instance.platform.name, instance.testcase.name) log_file = os.path.join(log_root, "handler.log") el.text = self.process_log(log_file) elif instance.results[k] == 'PASS' \ or (not instance.run and instance.status in ["passed"]): pass elif instance.results[k] == 'SKIP' or (instance.status in ["skipped"]): el = ET.SubElement(eleTestcase, 'skipped', type="skipped", message=instance.reason) else: el = ET.SubElement( eleTestcase, 'error', type="error", message=f"{instance.reason}") else: if platform: classname = ".".join(instance.testcase.name.split(".")[:2]) else: classname = p + ":" + ".".join(instance.testcase.name.split(".")[:2]) # remove testcases that are being re-run from exiting reports for tc in eleTestsuite.findall(f'testcase/[@classname="{classname}"][@name="{instance.testcase.name}"]'): eleTestsuite.remove(tc) eleTestcase = ET.SubElement(eleTestsuite, 'testcase', classname=classname, name="%s" % (instance.testcase.name), time="%f" % handler_time) if instance.status in ["error", "failed", "timeout", "flash_error"]: failure = ET.SubElement( eleTestcase, 'failure', type="failure", message=instance.reason) log_root = ("%s/%s/%s" % (self.outdir, instance.platform.name, instance.testcase.name)) bl = os.path.join(log_root, "build.log") hl = os.path.join(log_root, "handler.log") log_file = bl if instance.reason != 'Build error': if os.path.exists(hl): log_file = hl else: log_file = bl failure.text = self.process_log(log_file) elif instance.status == "skipped": ET.SubElement(eleTestcase, 'skipped', type="skipped", message="Skipped") result = ET.tostring(eleTestsuites) with open(filename, 'wb') as report: report.write(result) return fails, passes, errors, skips def csv_report(self, filename): with open(filename, "wt") as csvfile: fieldnames = ["test", "arch", "platform", "status", "extra_args", "handler", "handler_time", "ram_size", "rom_size"] cw = csv.DictWriter(csvfile, fieldnames, lineterminator=os.linesep) cw.writeheader() for instance in self.instances.values(): rowdict = {"test": instance.testcase.name, "arch": instance.platform.arch, "platform": instance.platform.name, "extra_args": " ".join(instance.testcase.extra_args), "handler": instance.platform.simulation} rowdict["status"] = instance.status if instance.status not in ["error", "failed", "timeout"]: if instance.handler: rowdict["handler_time"] = instance.metrics.get("handler_time", 0) ram_size = instance.metrics.get("ram_size", 0) rom_size = instance.metrics.get("rom_size", 0) rowdict["ram_size"] = ram_size rowdict["rom_size"] = rom_size cw.writerow(rowdict) def json_report(self, filename, append=False, version="NA"): logger.info(f"Writing JSON report {filename}") report = {} selected = self.selected_platforms report["environment"] = {"os": os.name, "zephyr_version": version, "toolchain": self.get_toolchain() } json_data = {} if os.path.exists(filename) and append: with open(filename, 'r') as json_file: json_data = json.load(json_file) suites = json_data.get("testsuites", []) if suites: suite = suites[0] testcases = suite.get("testcases", []) else: suite = {} testcases = [] for p in selected: inst = self.get_platform_instances(p) for _, instance in inst.items(): testcase = {} handler_log = os.path.join(instance.build_dir, "handler.log") build_log = os.path.join(instance.build_dir, "build.log") device_log = os.path.join(instance.build_dir, "device.log") handler_time = instance.metrics.get('handler_time', 0) ram_size = instance.metrics.get ("ram_size", 0) rom_size = instance.metrics.get("rom_size",0) for k in instance.results.keys(): testcases = list(filter(lambda d: not (d.get('testcase') == k and d.get('platform') == p), testcases )) testcase = {"testcase": k, "arch": instance.platform.arch, "platform": p, } if ram_size: testcase["ram_size"] = ram_size if rom_size: testcase["rom_size"] = rom_size if instance.results[k] in ["SKIP"] or instance.status == 'skipped': testcase["status"] = "skipped" testcase["reason"] = instance.reason elif instance.results[k] in ["PASS"] or instance.status == 'passed': testcase["status"] = "passed" if instance.handler: testcase["execution_time"] = handler_time elif instance.results[k] in ['FAIL', 'BLOCK'] or instance.status in ["error", "failed", "timeout", "flash_error"]: testcase["status"] = "failed" testcase["reason"] = instance.reason testcase["execution_time"] = handler_time if os.path.exists(handler_log): testcase["test_output"] = self.process_log(handler_log) elif os.path.exists(device_log): testcase["device_log"] = self.process_log(device_log) else: testcase["build_log"] = self.process_log(build_log) testcases.append(testcase) suites = [ {"testcases": testcases} ] report["testsuites"] = suites with open(filename, "wt") as json_file: json.dump(report, json_file, indent=4, separators=(',',':')) def get_testcase(self, identifier): results = [] for _, tc in self.testcases.items(): for case in tc.cases: if case == identifier: results.append(tc) return results def verify_platforms_existence(self, platform_names_to_verify, log_info=""): """ Verify if platform name (passed by --platform option, or in yaml file as platform_allow or integration_platforms options) is correct. If not - log and raise error. """ for platform in platform_names_to_verify: if platform in self.platform_names: break else: logger.error(f"{log_info} - unrecognized platform - {platform}") sys.exit(2) def create_build_dir_links(self): """ Iterate through all no-skipped instances in suite and create links for each one build directories. Those links will be passed in the next steps to the CMake command. """ links_dir_name = "twister_links" # folder for all links links_dir_path = os.path.join(self.outdir, links_dir_name) if not os.path.exists(links_dir_path): os.mkdir(links_dir_path) for instance in self.instances.values(): if instance.status != "skipped": self._create_build_dir_link(links_dir_path, instance) def _create_build_dir_link(self, links_dir_path, instance): """ Create build directory with original "long" path. Next take shorter path and link them with original path - create link. At the end replace build_dir to created link. This link will be passed to CMake command. This action helps to limit path length which can be significant during building by CMake on Windows OS. """ os.makedirs(instance.build_dir, exist_ok=True) link_name = f"test_{self.link_dir_counter}" link_path = os.path.join(links_dir_path, link_name) if os.name == "nt": # if OS is Windows command = ["mklink", "/J", f"{link_path}", f"{instance.build_dir}"] subprocess.call(command, shell=True) else: # for Linux and MAC OS os.symlink(instance.build_dir, link_path) # Here original build directory is replaced with symbolic link. It will # be passed to CMake command instance.build_dir = link_path self.link_dir_counter += 1 class CoverageTool: """ Base class for every supported coverage tool """ def __init__(self): self.gcov_tool = None self.base_dir = None @staticmethod def factory(tool): if tool == 'lcov': t = Lcov() elif tool == 'gcovr': t = Gcovr() else: logger.error("Unsupported coverage tool specified: {}".format(tool)) return None logger.debug(f"Select {tool} as the coverage tool...") return t @staticmethod def retrieve_gcov_data(input_file): logger.debug("Working on %s" % input_file) extracted_coverage_info = {} capture_data = False capture_complete = False with open(input_file, 'r') as fp: for line in fp.readlines(): if re.search("GCOV_COVERAGE_DUMP_START", line): capture_data = True continue if re.search("GCOV_COVERAGE_DUMP_END", line): capture_complete = True break # Loop until the coverage data is found. if not capture_data: continue if line.startswith("*"): sp = line.split("<") if len(sp) > 1: # Remove the leading delimiter "*" file_name = sp[0][1:] # Remove the trailing new line char hex_dump = sp[1][:-1] else: continue else: continue extracted_coverage_info.update({file_name: hex_dump}) if not capture_data: capture_complete = True return {'complete': capture_complete, 'data': extracted_coverage_info} @staticmethod def create_gcda_files(extracted_coverage_info): logger.debug("Generating gcda files") for filename, hexdump_val in extracted_coverage_info.items(): # if kobject_hash is given for coverage gcovr fails # hence skipping it problem only in gcovr v4.1 if "kobject_hash" in filename: filename = (filename[:-4]) + "gcno" try: os.remove(filename) except Exception: pass continue with open(filename, 'wb') as fp: fp.write(bytes.fromhex(hexdump_val)) def generate(self, outdir): for filename in glob.glob("%s/**/handler.log" % outdir, recursive=True): gcov_data = self.__class__.retrieve_gcov_data(filename) capture_complete = gcov_data['complete'] extracted_coverage_info = gcov_data['data'] if capture_complete: self.__class__.create_gcda_files(extracted_coverage_info) logger.debug("Gcov data captured: {}".format(filename)) else: logger.error("Gcov data capture incomplete: {}".format(filename)) with open(os.path.join(outdir, "coverage.log"), "a") as coveragelog: ret = self._generate(outdir, coveragelog) if ret == 0: logger.info("HTML report generated: {}".format( os.path.join(outdir, "coverage", "index.html"))) class Lcov(CoverageTool): def __init__(self): super().__init__() self.ignores = [] def add_ignore_file(self, pattern): self.ignores.append('*' + pattern + '*') def add_ignore_directory(self, pattern): self.ignores.append('*/' + pattern + '/*') def _generate(self, outdir, coveragelog): coveragefile = os.path.join(outdir, "coverage.info") ztestfile = os.path.join(outdir, "ztest.info") cmd = ["lcov", "--gcov-tool", self.gcov_tool, "--capture", "--directory", outdir, "--rc", "lcov_branch_coverage=1", "--output-file", coveragefile] cmd_str = " ".join(cmd) logger.debug(f"Running {cmd_str}...") subprocess.call(cmd, stdout=coveragelog) # We want to remove tests/* and tests/ztest/test/* but save tests/ztest subprocess.call(["lcov", "--gcov-tool", self.gcov_tool, "--extract", coveragefile, os.path.join(self.base_dir, "tests", "ztest", "*"), "--output-file", ztestfile, "--rc", "lcov_branch_coverage=1"], stdout=coveragelog) if os.path.exists(ztestfile) and os.path.getsize(ztestfile) > 0: subprocess.call(["lcov", "--gcov-tool", self.gcov_tool, "--remove", ztestfile, os.path.join(self.base_dir, "tests/ztest/test/*"), "--output-file", ztestfile, "--rc", "lcov_branch_coverage=1"], stdout=coveragelog) files = [coveragefile, ztestfile] else: files = [coveragefile] for i in self.ignores: subprocess.call( ["lcov", "--gcov-tool", self.gcov_tool, "--remove", coveragefile, i, "--output-file", coveragefile, "--rc", "lcov_branch_coverage=1"], stdout=coveragelog) # The --ignore-errors source option is added to avoid it exiting due to # samples/application_development/external_lib/ return subprocess.call(["genhtml", "--legend", "--branch-coverage", "--ignore-errors", "source", "-output-directory", os.path.join(outdir, "coverage")] + files, stdout=coveragelog) class Gcovr(CoverageTool): def __init__(self): super().__init__() self.ignores = [] def add_ignore_file(self, pattern): self.ignores.append('.*' + pattern + '.*') def add_ignore_directory(self, pattern): self.ignores.append(".*/" + pattern + '/.*') @staticmethod def _interleave_list(prefix, list): tuple_list = [(prefix, item) for item in list] return [item for sublist in tuple_list for item in sublist] def _generate(self, outdir, coveragelog): coveragefile = os.path.join(outdir, "coverage.json") ztestfile = os.path.join(outdir, "ztest.json") excludes = Gcovr._interleave_list("-e", self.ignores) # We want to remove tests/* and tests/ztest/test/* but save tests/ztest cmd = ["gcovr", "-r", self.base_dir, "--gcov-executable", self.gcov_tool, "-e", "tests/*"] + excludes + ["--json", "-o", coveragefile, outdir] cmd_str = " ".join(cmd) logger.debug(f"Running {cmd_str}...") subprocess.call(cmd, stdout=coveragelog) subprocess.call(["gcovr", "-r", self.base_dir, "--gcov-executable", self.gcov_tool, "-f", "tests/ztest", "-e", "tests/ztest/test/*", "--json", "-o", ztestfile, outdir], stdout=coveragelog) if os.path.exists(ztestfile) and os.path.getsize(ztestfile) > 0: files = [coveragefile, ztestfile] else: files = [coveragefile] subdir = os.path.join(outdir, "coverage") os.makedirs(subdir, exist_ok=True) tracefiles = self._interleave_list("--add-tracefile", files) return subprocess.call(["gcovr", "-r", self.base_dir, "--html", "--html-details"] + tracefiles + ["-o", os.path.join(subdir, "index.html")], stdout=coveragelog) class DUT(object): def __init__(self, id=None, serial=None, serial_baud=None, platform=None, product=None, serial_pty=None, connected=False, pre_script=None, post_script=None, post_flash_script=None, runner=None): self.serial = serial self.baud = serial_baud or 115200 self.platform = platform self.serial_pty = serial_pty self._counter = Value("i", 0) self._available = Value("i", 1) self.connected = connected self.pre_script = pre_script self.id = id self.product = product self.runner = runner self.fixtures = [] self.post_flash_script = post_flash_script self.post_script = post_script self.pre_script = pre_script self.probe_id = None self.notes = None self.lock = Lock() self.match = False @property def available(self): with self._available.get_lock(): return self._available.value @available.setter def available(self, value): with self._available.get_lock(): self._available.value = value @property def counter(self): with self._counter.get_lock(): return self._counter.value @counter.setter def counter(self, value): with self._counter.get_lock(): self._counter.value = value def to_dict(self): d = {} exclude = ['_available', '_counter', 'match'] v = vars(self) for k in v.keys(): if k not in exclude and v[k]: d[k] = v[k] return d def __repr__(self): return f"<{self.platform} ({self.product}) on {self.serial}>" class HardwareMap: schema_path = os.path.join(ZEPHYR_BASE, "scripts", "schemas", "twister", "hwmap-schema.yaml") manufacturer = [ 'ARM', 'SEGGER', 'MBED', 'STMicroelectronics', 'Atmel Corp.', 'Texas Instruments', 'Silicon Labs', 'NXP Semiconductors', 'Microchip Technology Inc.', 'FTDI', 'Digilent' ] runner_mapping = { 'pyocd': [ 'DAPLink CMSIS-DAP', 'MBED CMSIS-DAP' ], 'jlink': [ 'J-Link', 'J-Link OB' ], 'openocd': [ 'STM32 STLink', '^XDS110.*', 'STLINK-V3' ], 'dediprog': [ 'TTL232R-3V3', 'MCP2200 USB Serial Port Emulator' ] } def __init__(self): self.detected = [] self.duts = [] def add_device(self, serial, platform, pre_script, is_pty, baud=None): device = DUT(platform=platform, connected=True, pre_script=pre_script, serial_baud=baud) if is_pty: device.serial_pty = serial else: device.serial = serial self.duts.append(device) def load(self, map_file): hwm_schema = scl.yaml_load(self.schema_path) duts = scl.yaml_load_verify(map_file, hwm_schema) for dut in duts: pre_script = dut.get('pre_script') post_script = dut.get('post_script') post_flash_script = dut.get('post_flash_script') platform = dut.get('platform') id = dut.get('id') runner = dut.get('runner') serial = dut.get('serial') baud = dut.get('baud', None) product = dut.get('product') fixtures = dut.get('fixtures', []) new_dut = DUT(platform=platform, product=product, runner=runner, id=id, serial=serial, serial_baud=baud, connected=serial is not None, pre_script=pre_script, post_script=post_script, post_flash_script=post_flash_script) new_dut.fixtures = fixtures new_dut.counter = 0 self.duts.append(new_dut) def scan(self, persistent=False): from serial.tools import list_ports if persistent and platform.system() == 'Linux': # On Linux, /dev/serial/by-id provides symlinks to # '/dev/ttyACMx' nodes using names which are unique as # long as manufacturers fill out USB metadata nicely. # # This creates a map from '/dev/ttyACMx' device nodes # to '/dev/serial/by-id/usb-...' symlinks. The symlinks # go into the hardware map because they stay the same # even when the user unplugs / replugs the device. # # Some inexpensive USB/serial adapters don't result # in unique names here, though, so use of this feature # requires explicitly setting persistent=True. by_id = Path('/dev/serial/by-id') def readlink(link): return str((by_id / link).resolve()) persistent_map = {readlink(link): str(link) for link in by_id.iterdir()} else: persistent_map = {} serial_devices = list_ports.comports() logger.info("Scanning connected hardware...") for d in serial_devices: if d.manufacturer in self.manufacturer: # TI XDS110 can have multiple serial devices for a single board # assume endpoint 0 is the serial, skip all others if d.manufacturer == 'Texas Instruments' and not d.location.endswith('0'): continue s_dev = DUT(platform="unknown", id=d.serial_number, serial=persistent_map.get(d.device, d.device), product=d.product, runner='unknown', connected=True) for runner, _ in self.runner_mapping.items(): products = self.runner_mapping.get(runner) if d.product in products: s_dev.runner = runner continue # Try regex matching for p in products: if re.match(p, d.product): s_dev.runner = runner s_dev.connected = True s_dev.lock = None self.detected.append(s_dev) else: logger.warning("Unsupported device (%s): %s" % (d.manufacturer, d)) def save(self, hwm_file): # use existing map self.detected.sort(key=lambda x: x.serial or '') if os.path.exists(hwm_file): with open(hwm_file, 'r') as yaml_file: hwm = yaml.load(yaml_file, Loader=SafeLoader) if hwm: hwm.sort(key=lambda x: x['serial'] or '') # disconnect everything for h in hwm: h['connected'] = False h['serial'] = None for _detected in self.detected: for h in hwm: if _detected.id == h['id'] and _detected.product == h['product'] and not _detected.match: h['connected'] = True h['serial'] = _detected.serial _detected.match = True new_duts = list(filter(lambda d: not d.match, self.detected)) new = [] for d in new_duts: new.append(d.to_dict()) if hwm: hwm = hwm + new else: hwm = new with open(hwm_file, 'w') as yaml_file: yaml.dump(hwm, yaml_file, Dumper=Dumper, default_flow_style=False) self.load(hwm_file) logger.info("Registered devices:") self.dump() else: # create new file dl = [] for _connected in self.detected: platform = _connected.platform id = _connected.id runner = _connected.runner serial = _connected.serial product = _connected.product d = { 'platform': platform, 'id': id, 'runner': runner, 'serial': serial, 'product': product, 'connected': _connected.connected } dl.append(d) with open(hwm_file, 'w') as yaml_file: yaml.dump(dl, yaml_file, Dumper=Dumper, default_flow_style=False) logger.info("Detected devices:") self.dump(detected=True) def dump(self, filtered=[], header=[], connected_only=False, detected=False): print("") table = [] if detected: to_show = self.detected else: to_show = self.duts if not header: header = ["Platform", "ID", "Serial device"] for p in to_show: platform = p.platform connected = p.connected if filtered and platform not in filtered: continue if not connected_only or connected: table.append([platform, p.id, p.serial]) print(tabulate(table, headers=header, tablefmt="github"))
"""This file and its contents are licensed under the Apache License 2.0. Please see the included NOTICE for copyright information and LICENSE for a copy of the license. """ import json import logging from django.db.models import Q, Avg, Count, Sum, Value, BooleanField, Case, When from django.conf import settings from django.utils.translation import gettext_lazy as _ from django.db.models import JSONField from django.core.validators import MinLengthValidator, MaxLengthValidator from django.db import transaction, models from annoying.fields import AutoOneToOneField from rest_framework.exceptions import ValidationError from tasks.models import Task, Prediction, Annotation, Q_task_finished_annotations, Q_finished_annotations from core.utils.common import create_hash, pretty_date, sample_query, get_attr_or_item, load_func from core.label_config import ( parse_config, validate_label_config, extract_data_types, get_all_object_tag_names, config_line_stipped, get_sample_task, get_all_labels, get_all_control_tag_tuples, get_annotation_tuple ) logger = logging.getLogger(__name__) class ProjectManager(models.Manager): def for_user(self, user): return self.filter(organization=user.active_organization) def with_counts(self): return self.annotate( task_number=Count('tasks', distinct=True), total_predictions_number=Count('tasks__predictions', distinct=True), total_annotations_number=Count( 'tasks__annotations__id', distinct=True, filter=Q(tasks__annotations__was_cancelled=False) ), useful_annotation_number=Count( 'tasks__annotations__id', distinct=True, filter=Q(tasks__annotations__was_cancelled=False) & Q(tasks__annotations__ground_truth=False) & Q(tasks__annotations__result__isnull=False) ), ground_truth_number=Count( 'tasks__annotations__id', distinct=True, filter=Q(tasks__annotations__ground_truth=True) ), skipped_annotations_number=Count( 'tasks__annotations__id', distinct=True, filter=Q(tasks__annotations__was_cancelled=True) ), ) ProjectMixin = load_func(settings.PROJECT_MIXIN) class Project(ProjectMixin, models.Model): """ """ objects = ProjectManager() __original_label_config = None title = models.CharField(_('title'), null=True, blank=True, default='', max_length=settings.PROJECT_TITLE_MAX_LEN, help_text=f'Project name. Must be between {settings.PROJECT_TITLE_MIN_LEN} and {settings.PROJECT_TITLE_MAX_LEN} characters long.', validators=[MinLengthValidator(settings.PROJECT_TITLE_MIN_LEN), MaxLengthValidator(settings.PROJECT_TITLE_MAX_LEN)]) description = models.TextField(_('description'), blank=True, null=True, default='', help_text='Project description') organization = models.ForeignKey('organizations.Organization', on_delete=models.CASCADE, related_name='projects', null=True) label_config = models.TextField(_('label config'), blank=True, null=True, default='<View></View>', help_text='Label config in XML format. See more about it in documentation') expert_instruction = models.TextField(_('expert instruction'), blank=True, null=True, default='', help_text='Labeling instructions in HTML format') show_instruction = models.BooleanField(_('show instruction'), default=False, help_text='Show instructions to the annotator before they start') show_skip_button = models.BooleanField(_('show skip button'), default=True, help_text='Show a skip button in interface and allow annotators to skip the task') enable_empty_annotation = models.BooleanField(_('enable empty annotation'), default=True, help_text='Allow annotators to submit empty annotations') show_annotation_history = models.BooleanField(_('show annotation history'), default=False, help_text='Show annotation history to annotator') show_collab_predictions = models.BooleanField(_('show predictions to annotator'), default=True, help_text='If set, the annotator can view model predictions') evaluate_predictions_automatically = models.BooleanField(_('evaluate predictions automatically'), default=False, help_text='Retrieve and display predictions when loading a task') token = models.CharField(_('token'), max_length=256, default=create_hash, null=True, blank=True) result_count = models.IntegerField(_('result count'), default=0, help_text='Total results inside of annotations counter') color = models.CharField(_('color'), max_length=16, default='#FFFFFF', null=True, blank=True) created_by = models.ForeignKey( settings.AUTH_USER_MODEL, related_name='created_projects', on_delete=models.SET_NULL, null=True, verbose_name=_('created by') ) maximum_annotations = models.IntegerField(_('maximum annotation number'), default=1, help_text='Maximum number of annotations for one task. ' 'If the number of annotations per task is equal or greater ' 'to this value, the task is completed (is_labeled=True)') min_annotations_to_start_training = models.IntegerField( _('min_annotations_to_start_training'), default=10, help_text='Minimum number of completed tasks after which model training is started' ) control_weights = JSONField(_('control weights'), null=True, default=dict, help_text='Weights for control tags') model_version = models.TextField(_('model version'), blank=True, null=True, default='', help_text='Machine learning model version') data_types = JSONField(_('data_types'), default=dict, null=True) is_draft = models.BooleanField( _('is draft'), default=False, help_text='Whether or not the project is in the middle of being created') is_published = models.BooleanField(_('published'), default=False, help_text='Whether or not the project is published to annotators') created_at = models.DateTimeField(_('created at'), auto_now_add=True) updated_at = models.DateTimeField(_('updated at'), auto_now=True) SEQUENCE = 'Sequential sampling' UNIFORM = 'Uniform sampling' UNCERTAINTY = 'Uncertainty sampling' SAMPLING_CHOICES = ( (SEQUENCE, 'Tasks are ordered by Data manager ordering'), (UNIFORM, 'Tasks are chosen randomly'), (UNCERTAINTY, 'Tasks are chosen according to model uncertainty scores (active learning mode)') ) sampling = models.CharField(max_length=100, choices=SAMPLING_CHOICES, null=True, default=SEQUENCE) show_ground_truth_first = models.BooleanField(_('show ground truth first'), default=True) show_overlap_first = models.BooleanField(_('show overlap first'), default=True) overlap_cohort_percentage = models.IntegerField(_('overlap_cohort_percentage'), default=100) task_data_login = models.CharField( _('task_data_login'), max_length=256, blank=True, null=True, help_text='Task data credentials: login') task_data_password = models.CharField( _('task_data_password'), max_length=256, blank=True, null=True, help_text='Task data credentials: password') def __init__(self, *args, **kwargs): super(Project, self).__init__(*args, **kwargs) self.__original_label_config = self.label_config self.__maximum_annotations = self.maximum_annotations self.__overlap_cohort_percentage = self.overlap_cohort_percentage # TODO: once bugfix with incorrect data types in List # logging.warning('! Please, remove code below after patching of all projects (extract_data_types)') if self.label_config is not None: if self.data_types != extract_data_types(self.label_config): self.data_types = extract_data_types(self.label_config) @property def num_tasks(self): return self.tasks.count() def get_current_predictions(self): return Prediction.objects.filter(Q(task__project=self.id) & Q(model_version=self.model_version)) @property def num_predictions(self): return self.get_current_predictions().count() @property def num_annotations(self): return Annotation.objects.filter(Q(task__project=self) & Q_finished_annotations & Q(ground_truth=False)).count() @property def has_predictions(self): return self.get_current_predictions().exists() @property def has_any_predictions(self): return Prediction.objects.filter(Q(task__project=self.id)).exists() @property def business(self): return self.created_by.business @property def is_private(self): return None @property def has_storages(self): return hasattr(self, 'storages') and self.storages is not None and self.storages.count() > 0 @property def secure_mode(self): return False @property def one_object_in_label_config(self): return len(self.data_types) <= 1 @property def only_undefined_field(self): return self.one_object_in_label_config and self.summary.common_data_columns and self.summary.common_data_columns[0] == settings.DATA_UNDEFINED_NAME @property def get_labeled_count(self): return self.tasks.filter(is_labeled=True).count() @property def get_collected_count(self): return self.tasks.count() @property def num_tasks_with_annotations(self): return self.tasks.filter( Q(annotations__isnull=False) & Q(annotations__ground_truth=False) & Q_task_finished_annotations ).distinct().count() @property def get_total_possible_count(self): """ Tasks has overlap - how many tc should be accepted possible count = sum [ t.overlap for t in tasks] :return: N int total amount of Annotations that should be submitted """ if self.tasks.count() == 0: return 0 return self.tasks.aggregate(Sum('overlap'))['overlap__sum'] @property def get_available_for_labeling(self): return self.get_collected_count - self.get_labeled_count @property def need_annotators(self): return self.maximum_annotations - self.num_annotators @classmethod def find_by_invite_url(cls, url): token = url.strip('/').split('/')[-1] if len(token): return Project.objects.get(token=token) else: raise KeyError(f'Can\'t find Project by invite URL: {url}') def reset_token(self): self.token = create_hash() self.save() def add_collaborator(self, user): created = False with transaction.atomic(): try: ProjectMember.objects.get(user=user, project=self) except ProjectMember.DoesNotExist: ProjectMember.objects.create(user=user, project=self) created = True else: logger.debug(f'Project membership {self} for user {user} already exists') return created def has_collaborator(self, user): return ProjectMember.objects.filter(user=user, project=self).exists() def has_collaborator_enabled(self, user): membership = ProjectMember.objects.filter(user=user, project=self) return membership.exists() and membership.first().enabled def update_tasks_states(self, maximum_annotations_changed, overlap_cohort_percentage_changed, tasks_number_changed): # if only maximum annotations parameter is tweaked if maximum_annotations_changed and not overlap_cohort_percentage_changed: tasks_with_overlap = self.tasks.filter(overlap__gt=1) if tasks_with_overlap.exists(): # if there is a part with overlaped tasks, affect only them tasks_with_overlap.update(overlap=self.maximum_annotations) else: # otherwise affect all tasks self.tasks.update(overlap=self.maximum_annotations) # if cohort slider is tweaked elif overlap_cohort_percentage_changed and self.maximum_annotations > 1: self._rearrange_overlap_cohort() # if adding/deleting tasks and cohort settings are applied elif tasks_number_changed and self.overlap_cohort_percentage < 100 and self.maximum_annotations > 1: self._rearrange_overlap_cohort() def _rearrange_overlap_cohort(self): tasks_with_overlap = self.tasks.filter(overlap__gt=1) tasks_with_overlap_count = tasks_with_overlap.count() total_tasks = self.tasks.count() new_tasks_with_overlap_count = int(self.overlap_cohort_percentage / 100 * total_tasks + 0.5) if tasks_with_overlap_count > new_tasks_with_overlap_count: # TODO: warn if we try to reduce current cohort that is already labeled with overlap reduce_by = tasks_with_overlap_count - new_tasks_with_overlap_count reduce_tasks = sample_query(tasks_with_overlap, reduce_by) reduce_tasks.update(overlap=1) reduced_tasks_ids = reduce_tasks.values_list('id', flat=True) tasks_with_overlap.exclude(id__in=reduced_tasks_ids).update(overlap=self.maximum_annotations) elif tasks_with_overlap_count < new_tasks_with_overlap_count: increase_by = new_tasks_with_overlap_count - tasks_with_overlap_count tasks_without_overlap = self.tasks.filter(overlap=1) increase_tasks = sample_query(tasks_without_overlap, increase_by) increase_tasks.update(overlap=self.maximum_annotations) tasks_with_overlap.update(overlap=self.maximum_annotations) def remove_tasks_by_file_uploads(self, file_upload_ids): self.tasks.filter(file_upload_id__in=file_upload_ids).delete() def advance_onboarding(self): """ Move project to next onboarding step """ po_qs = self.steps_left.order_by('step__order') count = po_qs.count() if count: po = po_qs.first() po.finished = True po.save() return count != 1 def created_at_prettify(self): return self.created_at.strftime("%d %b %Y %H:%M:%S") def onboarding_step_finished(self, step): """ Mark specific step as finished """ pos = ProjectOnboardingSteps.objects.get(code=step) po = ProjectOnboarding.objects.get(project=self, step=pos) po.finished = True po.save() return po def data_types_json(self): return json.dumps(self.data_types) def available_data_keys(self): return sorted(list(self.data_types.keys())) @classmethod def validate_label_config(cls, config_string): validate_label_config(config_string) def validate_config(self, config_string): self.validate_label_config(config_string) if not hasattr(self, 'summary'): return # validate data columns consistency fields_from_config = get_all_object_tag_names(config_string) if not fields_from_config: logger.debug(f'Data fields not found in labeling config') return fields_from_data = set(self.summary.common_data_columns) fields_from_data.discard(settings.DATA_UNDEFINED_NAME) if fields_from_data and not fields_from_config.issubset(fields_from_data): different_fields = list(fields_from_config.difference(fields_from_data)) raise ValidationError(f'These fields are not present in the data: {','.join(different_fields)}') # validate annotations consistency annotations_from_config = set(get_all_control_tag_tuples(config_string)) if not annotations_from_config: logger.debug(f'Annotation schema is not found in config') return annotations_from_data = set(self.summary.created_annotations) if annotations_from_data and not annotations_from_data.issubset(annotations_from_config): different_annotations = list(annotations_from_data.difference(annotations_from_config)) diff_str = [] for ann_tuple in different_annotations: from_name, to_name, t = ann_tuple.split('|') diff_str.append( f'{self.summary.created_annotations[ann_tuple]} ' f'with from_name={from_name}, to_name={to_name}, type={t}') diff_str = '\n'.join(diff_str) raise ValidationError(f'Created annotations are incompatible with provided labeling schema, ' f'we found:\n{diff_str}') # validate labels consistency labels_from_config = get_all_labels(config_string) created_labels = self.summary.created_labels for control_tag_from_data, labels_from_data in created_labels.items(): # Check if labels created in annotations, and their control tag has been removed if labels_from_data and control_tag_from_data not in labels_from_config: raise ValidationError( f'There are {sum(labels_from_data.values(), 0)} annotation(s) created with tag ' f'"{control_tag_from_data}", you can\'t remove it') labels_from_config_by_tag = set(labels_from_config[control_tag_from_data]) if not set(labels_from_data).issubset(set(labels_from_config_by_tag)): different_labels = list(set(labels_from_data).difference(labels_from_config_by_tag)) diff_str = '\n'.join(f'{l} ({labels_from_data[l]} annotations)' for l in different_labels) raise ValidationError(f'These labels still exist in annotations:\n{diff_str}') def _label_config_has_changed(self): return self.label_config != self.__original_label_config def delete_predictions(self): predictions = Prediction.objects.filter(task__project=self) count = predictions.count() predictions.delete() return {'deleted_predictions': count} def get_updated_weights(self): outputs = parse_config(self.label_config) control_weights = {} exclude_control_types = ('Filter',) for control_name in outputs: control_type = outputs[control_name]['type'] if control_type in exclude_control_types: continue control_weights[control_name] = { 'overall': 1.0, 'type': control_type, 'labels': {label: 1.0 for label in outputs[control_name].get('labels', [])} } return control_weights def save(self, *args, recalc=True, **kwargs): exists = True if self.pk else False if self.label_config and (self._label_config_has_changed() or not exists or not self.control_weights): self.control_weights = self.get_updated_weights() super(Project, self).save(*args, **kwargs) project_with_config_just_created = not exists and self.pk and self.label_config if self._label_config_has_changed() or project_with_config_just_created: self.data_types = extract_data_types(self.label_config) if self._label_config_has_changed(): self.__original_label_config = self.label_config if not exists: steps = ProjectOnboardingSteps.objects.all() objs = [ProjectOnboarding(project=self, step=step) for step in steps] ProjectOnboarding.objects.bulk_create(objs) # argument for recalculate project task stats if recalc: self.update_tasks_states( maximum_annotations_changed=self.__maximum_annotations != self.maximum_annotations, overlap_cohort_percentage_changed=self.__overlap_cohort_percentage != self.overlap_cohort_percentage, tasks_number_changed=False ) self.__maximum_annotations = self.maximum_annotations self.__overlap_cohort_percentage = self.overlap_cohort_percentage def get_member_ids(self): if hasattr(self, 'team_link'): # project has defined team scope # TODO: avoid checking team but rather add all project members when creating a project return self.team_link.team.members.values_list('user', flat=True) else: from users.models import User # TODO: may want to return all users from organization return User.objects.none() def has_team_user(self, user): return hasattr(self, 'team_link') and self.team_link.team.has_user(user) def annotators(self): """ Annotators connected to this project including team members """ from users.models import User member_ids = self.get_member_ids() team_members = User.objects.filter(id__in=member_ids).order_by('email') # add members from invited projects project_member_ids = self.members.values_list('user__id', flat=True) project_members = User.objects.filter(id__in=project_member_ids) annotators = team_members | project_members # set annotator.team_member=True if annotator is not an invited user annotators = annotators.annotate( team_member=Case( When(id__in=project_member_ids, then=Value(False)), default=Value(True), output_field=BooleanField(), ) ) return annotators def annotators_with_annotations(self, min_count=500): """ Annotators with annotation number > min_number :param min_count: minimal annotation number to leave an annotators :return: filtered annotators """ annotators = self.annotators() q = Q(annotations__task__project=self) & Q_task_finished_annotations & Q(annotations__ground_truth=False) annotators = annotators.annotate(annotation_count=Count('annotations', filter=q, distinct=True)) return annotators.filter(annotation_count__gte=min_count) def labeled_tasks(self): return self.tasks.filter(is_labeled=True) def has_annotations(self): from tasks.models import Annotation # prevent cycling imports return Annotation.objects.filter(Q(task__project=self) & Q(ground_truth=False)).count() > 0 # [TODO] this should be a template tag or something like this @property def label_config_line(self): c = self.label_config return config_line_stipped(c) def get_sample_task(self, label_config=None): config = label_config or self.label_config task, _, _ = get_sample_task(config) return task def pretty_model_version(self): if not self.model_version: return 'Undefined model version' return pretty_date(self.model_version) def eta(self): """ Show eta for project to be finished eta = avg task annotations finish time * remain annotations task has overlap = amount of task annotations to consider as finished (is_labeled) remain annotations = sum ( task annotations to be done to fulfill each unfinished task overlap) :return: time in seconds """ # finished tasks * overlap finished_tasks = Task.objects.filter(project=self.id, is_labeled=True) # one could make more than need to overlap min_n_finished_annotations = sum([ft.overlap for ft in finished_tasks]) annotations_unfinished_tasks = Annotation.objects.filter( task__project=self.id, task__is_labeled=False, ground_truth=False, result__isnull=False).count() # get minimum remain annotations total_annotations_needed = self.get_total_possible_count annotations_remain = total_annotations_needed - min_n_finished_annotations - annotations_unfinished_tasks # get average time of all finished TC finished_annotations = Annotation.objects.filter( Q(task__project=self.id) & Q(ground_truth=False), result__isnull=False).values('lead_time') avg_lead_time = finished_annotations.aggregate(avg_lead_time=Avg('lead_time'))['avg_lead_time'] if avg_lead_time is None: return None return avg_lead_time * annotations_remain def finished(self): return not self.tasks.filter(is_labeled=False).exists() def annotations_lead_time(self): annotations = Annotation.objects.filter(Q(task__project=self.id) & Q(ground_truth=False)) return annotations.aggregate(avg_lead_time=Avg('lead_time'))['avg_lead_time'] @staticmethod def django_settings(): return settings @staticmethod def max_tasks_file_size(): return settings.TASKS_MAX_FILE_SIZE def get_control_tags_from_config(self): return parse_config(self.label_config) def get_parsed_config(self): return parse_config(self.label_config) def __str__(self): return f'{self.title} (id={self.id})' or _("Business number %d") % self.pk class Meta: db_table = 'project' class ProjectOnboardingSteps(models.Model): """ """ DATA_UPLOAD = "DU" CONF_SETTINGS = "CF" PUBLISH = "PB" INVITE_EXPERTS = "IE" STEPS_CHOICES = ( (DATA_UPLOAD, "Import your data"), (CONF_SETTINGS, "Configure settings"), (PUBLISH, "Publish project"), (INVITE_EXPERTS, "Invite collaborators") ) code = models.CharField(max_length=2, choices=STEPS_CHOICES, null=True) title = models.CharField(_('title'), max_length=1000, null=False) description = models.TextField(_('description'), null=False) order = models.IntegerField(default=0) created_at = models.DateTimeField(_('created at'), auto_now_add=True) updated_at = models.DateTimeField(_('updated at'), auto_now=True) class Meta: ordering = ['order'] class ProjectOnboarding(models.Model): """ """ step = models.ForeignKey(ProjectOnboardingSteps, on_delete=models.CASCADE, related_name="po_through") project = models.ForeignKey(Project, on_delete=models.CASCADE) finished = models.BooleanField(default=False) created_at = models.DateTimeField(_('created at'), auto_now_add=True) updated_at = models.DateTimeField(_('updated at'), auto_now=True) def save(self, *args, **kwargs): super(ProjectOnboarding, self).save(*args, **kwargs) if ProjectOnboarding.objects.filter(project=self.project, finished=True).count() == 4: self.project.skip_onboarding = True self.project.save(recalc=False) class ProjectMember(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='project_memberships', help_text='User ID') # noqa project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='members', help_text='Project ID') enabled = models.BooleanField(default=True, help_text='Project member is enabled') created_at = models.DateTimeField(_('created at'), auto_now_add=True) updated_at = models.DateTimeField(_('updated at'), auto_now=True) class ProjectSummary(models.Model): project = AutoOneToOneField(Project, primary_key=True, on_delete=models.CASCADE, related_name='summary') created_at = models.DateTimeField(_('created at'), auto_now_add=True, help_text='Creation time') # { col1: task_count_with_col1, col2: task_count_with_col2 } all_data_columns = JSONField( _('all data columns'), null=True, default=dict, help_text='All data columns found in imported tasks') # [col1, col2] common_data_columns = JSONField( _('common data columns'), null=True, default=list, help_text='Common data columns found across imported tasks') # { (from_name, to_name, type): annotation_count } created_annotations = JSONField( _('created annotations'), null=True, default=dict, help_text='Unique annotation types identified by tuple (from_name, to_name, type)') # noqa # { from_name: {label1: task_count_with_label1, label2: task_count_with_label2} } created_labels = JSONField( _('created labels'), null=True, default=dict, help_text='Unique labels') def has_permission(self, user): return self.project.has_permission(user) def update_data_columns(self, tasks): common_data_columns = set() all_data_columns = dict(self.all_data_columns) for task in tasks: try: task_data = get_attr_or_item(task, 'data') except KeyError: task_data = task task_data_keys = task_data.keys() for column in task_data_keys: all_data_columns[column] = all_data_columns.get(column, 0) + 1 if not common_data_columns: common_data_columns = set(task_data_keys) else: common_data_columns &= set(task_data_keys) self.all_data_columns = all_data_columns if not self.common_data_columns: self.common_data_columns = list(sorted(common_data_columns)) else: self.common_data_columns = list(sorted(set(self.common_data_columns) & common_data_columns)) self.save() def remove_data_columns(self, tasks): all_data_columns = dict(self.all_data_columns) keys_to_remove = [] for task in tasks: task_data = get_attr_or_item(task, 'data') for key in task_data.keys(): if key in all_data_columns: all_data_columns[key] -= 1 if all_data_columns[key] == 0: keys_to_remove.append(key) all_data_columns.pop(key) self.all_data_columns = all_data_columns if keys_to_remove: common_data_columns = list(self.common_data_columns) for key in keys_to_remove: if key in common_data_columns: common_data_columns.remove(key) self.common_data_columns = common_data_columns self.save() def _get_annotation_key(self, result): result_type = result.get('type') if result_type in ('relation', 'rating', 'pairwise'): return None if 'from_name' not in result or 'to_name' not in result: logger.error( 'Unexpected annotation.result format: "from_name" or "to_name" not found in %r' % result) return None result_from_name = result['from_name'] key = get_annotation_tuple(result_from_name, result['to_name'], result_type or '') return key def _get_labels(self, result): result_type = result.get('type') labels = [] for label in result['value'].get(result_type, []): if isinstance(label, list): labels.extend(label) else: labels.append(label) return labels def update_created_annotations_and_labels(self, annotations): created_annotations = dict(self.created_annotations) labels = dict(self.created_labels) for annotation in annotations: results = get_attr_or_item(annotation, 'result') or [] for result in results: # aggregate annotation types key = self._get_annotation_key(result) if not key: continue created_annotations[key] = created_annotations.get(key, 0) + 1 from_name = result['from_name'] # aggregate labels if from_name not in self.created_labels: labels[from_name] = dict() for label in self._get_labels(result): labels[from_name][label] = labels[from_name].get(label, 0) + 1 self.created_annotations = created_annotations self.created_labels = labels self.save() def remove_created_annotations_and_labels(self, annotations): created_annotations = dict(self.created_annotations) labels = dict(self.created_labels) for annotation in annotations: results = get_attr_or_item(annotation, 'result') or [] for result in results: # reduce annotation counters key = self._get_annotation_key(result) if key in created_annotations: created_annotations[key] -= 1 if created_annotations[key] == 0: created_annotations.pop(key) # reduce labels counters from_name = result.get('from_name') if from_name not in labels: continue for label in self._get_labels(result): if label in labels[from_name]: labels[from_name][label] -= 1 if labels[from_name][label] == 0: labels[from_name].pop(label) if not labels[from_name]: labels.pop(from_name) self.created_annotations = created_annotations self.created_labels = labels self.save()
"""This file and its contents are licensed under the Apache License 2.0. Please see the included NOTICE for copyright information and LICENSE for a copy of the license. """ import json import logging from django.db.models import Q, Avg, Count, Sum, Value, BooleanField, Case, When from django.conf import settings from django.utils.translation import gettext_lazy as _ from django.db.models import JSONField from django.core.validators import MinLengthValidator, MaxLengthValidator from django.db import transaction, models from annoying.fields import AutoOneToOneField from rest_framework.exceptions import ValidationError from tasks.models import Task, Prediction, Annotation, Q_task_finished_annotations, Q_finished_annotations from core.utils.common import create_hash, pretty_date, sample_query, get_attr_or_item, load_func from core.label_config import ( parse_config, validate_label_config, extract_data_types, get_all_object_tag_names, config_line_stipped, get_sample_task, get_all_labels, get_all_control_tag_tuples, get_annotation_tuple ) logger = logging.getLogger(__name__) class ProjectManager(models.Manager): def for_user(self, user): return self.filter(organization=user.active_organization) def with_counts(self): return self.annotate( task_number=Count('tasks', distinct=True), total_predictions_number=Count('tasks__predictions', distinct=True), total_annotations_number=Count( 'tasks__annotations__id', distinct=True, filter=Q(tasks__annotations__was_cancelled=False) ), useful_annotation_number=Count( 'tasks__annotations__id', distinct=True, filter=Q(tasks__annotations__was_cancelled=False) & Q(tasks__annotations__ground_truth=False) & Q(tasks__annotations__result__isnull=False) ), ground_truth_number=Count( 'tasks__annotations__id', distinct=True, filter=Q(tasks__annotations__ground_truth=True) ), skipped_annotations_number=Count( 'tasks__annotations__id', distinct=True, filter=Q(tasks__annotations__was_cancelled=True) ), ) ProjectMixin = load_func(settings.PROJECT_MIXIN) class Project(ProjectMixin, models.Model): """ """ objects = ProjectManager() __original_label_config = None title = models.CharField(_('title'), null=True, blank=True, default='', max_length=settings.PROJECT_TITLE_MAX_LEN, help_text=f'Project name. Must be between {settings.PROJECT_TITLE_MIN_LEN} and {settings.PROJECT_TITLE_MAX_LEN} characters long.', validators=[MinLengthValidator(settings.PROJECT_TITLE_MIN_LEN), MaxLengthValidator(settings.PROJECT_TITLE_MAX_LEN)]) description = models.TextField(_('description'), blank=True, null=True, default='', help_text='Project description') organization = models.ForeignKey('organizations.Organization', on_delete=models.CASCADE, related_name='projects', null=True) label_config = models.TextField(_('label config'), blank=True, null=True, default='<View></View>', help_text='Label config in XML format. See more about it in documentation') expert_instruction = models.TextField(_('expert instruction'), blank=True, null=True, default='', help_text='Labeling instructions in HTML format') show_instruction = models.BooleanField(_('show instruction'), default=False, help_text='Show instructions to the annotator before they start') show_skip_button = models.BooleanField(_('show skip button'), default=True, help_text='Show a skip button in interface and allow annotators to skip the task') enable_empty_annotation = models.BooleanField(_('enable empty annotation'), default=True, help_text='Allow annotators to submit empty annotations') show_annotation_history = models.BooleanField(_('show annotation history'), default=False, help_text='Show annotation history to annotator') show_collab_predictions = models.BooleanField(_('show predictions to annotator'), default=True, help_text='If set, the annotator can view model predictions') evaluate_predictions_automatically = models.BooleanField(_('evaluate predictions automatically'), default=False, help_text='Retrieve and display predictions when loading a task') token = models.CharField(_('token'), max_length=256, default=create_hash, null=True, blank=True) result_count = models.IntegerField(_('result count'), default=0, help_text='Total results inside of annotations counter') color = models.CharField(_('color'), max_length=16, default='#FFFFFF', null=True, blank=True) created_by = models.ForeignKey( settings.AUTH_USER_MODEL, related_name='created_projects', on_delete=models.SET_NULL, null=True, verbose_name=_('created by') ) maximum_annotations = models.IntegerField(_('maximum annotation number'), default=1, help_text='Maximum number of annotations for one task. ' 'If the number of annotations per task is equal or greater ' 'to this value, the task is completed (is_labeled=True)') min_annotations_to_start_training = models.IntegerField( _('min_annotations_to_start_training'), default=10, help_text='Minimum number of completed tasks after which model training is started' ) control_weights = JSONField(_('control weights'), null=True, default=dict, help_text='Weights for control tags') model_version = models.TextField(_('model version'), blank=True, null=True, default='', help_text='Machine learning model version') data_types = JSONField(_('data_types'), default=dict, null=True) is_draft = models.BooleanField( _('is draft'), default=False, help_text='Whether or not the project is in the middle of being created') is_published = models.BooleanField(_('published'), default=False, help_text='Whether or not the project is published to annotators') created_at = models.DateTimeField(_('created at'), auto_now_add=True) updated_at = models.DateTimeField(_('updated at'), auto_now=True) SEQUENCE = 'Sequential sampling' UNIFORM = 'Uniform sampling' UNCERTAINTY = 'Uncertainty sampling' SAMPLING_CHOICES = ( (SEQUENCE, 'Tasks are ordered by Data manager ordering'), (UNIFORM, 'Tasks are chosen randomly'), (UNCERTAINTY, 'Tasks are chosen according to model uncertainty scores (active learning mode)') ) sampling = models.CharField(max_length=100, choices=SAMPLING_CHOICES, null=True, default=SEQUENCE) show_ground_truth_first = models.BooleanField(_('show ground truth first'), default=True) show_overlap_first = models.BooleanField(_('show overlap first'), default=True) overlap_cohort_percentage = models.IntegerField(_('overlap_cohort_percentage'), default=100) task_data_login = models.CharField( _('task_data_login'), max_length=256, blank=True, null=True, help_text='Task data credentials: login') task_data_password = models.CharField( _('task_data_password'), max_length=256, blank=True, null=True, help_text='Task data credentials: password') def __init__(self, *args, **kwargs): super(Project, self).__init__(*args, **kwargs) self.__original_label_config = self.label_config self.__maximum_annotations = self.maximum_annotations self.__overlap_cohort_percentage = self.overlap_cohort_percentage # TODO: once bugfix with incorrect data types in List # logging.warning('! Please, remove code below after patching of all projects (extract_data_types)') if self.label_config is not None: if self.data_types != extract_data_types(self.label_config): self.data_types = extract_data_types(self.label_config) @property def num_tasks(self): return self.tasks.count() def get_current_predictions(self): return Prediction.objects.filter(Q(task__project=self.id) & Q(model_version=self.model_version)) @property def num_predictions(self): return self.get_current_predictions().count() @property def num_annotations(self): return Annotation.objects.filter(Q(task__project=self) & Q_finished_annotations & Q(ground_truth=False)).count() @property def has_predictions(self): return self.get_current_predictions().exists() @property def has_any_predictions(self): return Prediction.objects.filter(Q(task__project=self.id)).exists() @property def business(self): return self.created_by.business @property def is_private(self): return None @property def has_storages(self): return hasattr(self, 'storages') and self.storages is not None and self.storages.count() > 0 @property def secure_mode(self): return False @property def one_object_in_label_config(self): return len(self.data_types) <= 1 @property def only_undefined_field(self): return self.one_object_in_label_config and self.summary.common_data_columns and self.summary.common_data_columns[0] == settings.DATA_UNDEFINED_NAME @property def get_labeled_count(self): return self.tasks.filter(is_labeled=True).count() @property def get_collected_count(self): return self.tasks.count() @property def num_tasks_with_annotations(self): return self.tasks.filter( Q(annotations__isnull=False) & Q(annotations__ground_truth=False) & Q_task_finished_annotations ).distinct().count() @property def get_total_possible_count(self): """ Tasks has overlap - how many tc should be accepted possible count = sum [ t.overlap for t in tasks] :return: N int total amount of Annotations that should be submitted """ if self.tasks.count() == 0: return 0 return self.tasks.aggregate(Sum('overlap'))['overlap__sum'] @property def get_available_for_labeling(self): return self.get_collected_count - self.get_labeled_count @property def need_annotators(self): return self.maximum_annotations - self.num_annotators @classmethod def find_by_invite_url(cls, url): token = url.strip('/').split('/')[-1] if len(token): return Project.objects.get(token=token) else: raise KeyError(f'Can\'t find Project by invite URL: {url}') def reset_token(self): self.token = create_hash() self.save() def add_collaborator(self, user): created = False with transaction.atomic(): try: ProjectMember.objects.get(user=user, project=self) except ProjectMember.DoesNotExist: ProjectMember.objects.create(user=user, project=self) created = True else: logger.debug(f'Project membership {self} for user {user} already exists') return created def has_collaborator(self, user): return ProjectMember.objects.filter(user=user, project=self).exists() def has_collaborator_enabled(self, user): membership = ProjectMember.objects.filter(user=user, project=self) return membership.exists() and membership.first().enabled def update_tasks_states(self, maximum_annotations_changed, overlap_cohort_percentage_changed, tasks_number_changed): # if only maximum annotations parameter is tweaked if maximum_annotations_changed and not overlap_cohort_percentage_changed: tasks_with_overlap = self.tasks.filter(overlap__gt=1) if tasks_with_overlap.exists(): # if there is a part with overlaped tasks, affect only them tasks_with_overlap.update(overlap=self.maximum_annotations) else: # otherwise affect all tasks self.tasks.update(overlap=self.maximum_annotations) # if cohort slider is tweaked elif overlap_cohort_percentage_changed and self.maximum_annotations > 1: self._rearrange_overlap_cohort() # if adding/deleting tasks and cohort settings are applied elif tasks_number_changed and self.overlap_cohort_percentage < 100 and self.maximum_annotations > 1: self._rearrange_overlap_cohort() def _rearrange_overlap_cohort(self): tasks_with_overlap = self.tasks.filter(overlap__gt=1) tasks_with_overlap_count = tasks_with_overlap.count() total_tasks = self.tasks.count() new_tasks_with_overlap_count = int(self.overlap_cohort_percentage / 100 * total_tasks + 0.5) if tasks_with_overlap_count > new_tasks_with_overlap_count: # TODO: warn if we try to reduce current cohort that is already labeled with overlap reduce_by = tasks_with_overlap_count - new_tasks_with_overlap_count reduce_tasks = sample_query(tasks_with_overlap, reduce_by) reduce_tasks.update(overlap=1) reduced_tasks_ids = reduce_tasks.values_list('id', flat=True) tasks_with_overlap.exclude(id__in=reduced_tasks_ids).update(overlap=self.maximum_annotations) elif tasks_with_overlap_count < new_tasks_with_overlap_count: increase_by = new_tasks_with_overlap_count - tasks_with_overlap_count tasks_without_overlap = self.tasks.filter(overlap=1) increase_tasks = sample_query(tasks_without_overlap, increase_by) increase_tasks.update(overlap=self.maximum_annotations) tasks_with_overlap.update(overlap=self.maximum_annotations) def remove_tasks_by_file_uploads(self, file_upload_ids): self.tasks.filter(file_upload_id__in=file_upload_ids).delete() def advance_onboarding(self): """ Move project to next onboarding step """ po_qs = self.steps_left.order_by('step__order') count = po_qs.count() if count: po = po_qs.first() po.finished = True po.save() return count != 1 def created_at_prettify(self): return self.created_at.strftime("%d %b %Y %H:%M:%S") def onboarding_step_finished(self, step): """ Mark specific step as finished """ pos = ProjectOnboardingSteps.objects.get(code=step) po = ProjectOnboarding.objects.get(project=self, step=pos) po.finished = True po.save() return po def data_types_json(self): return json.dumps(self.data_types) def available_data_keys(self): return sorted(list(self.data_types.keys())) @classmethod def validate_label_config(cls, config_string): validate_label_config(config_string) def validate_config(self, config_string): self.validate_label_config(config_string) if not hasattr(self, 'summary'): return # validate data columns consistency fields_from_config = get_all_object_tag_names(config_string) if not fields_from_config: logger.debug(f'Data fields not found in labeling config') return fields_from_data = set(self.summary.common_data_columns) fields_from_data.discard(settings.DATA_UNDEFINED_NAME) if fields_from_data and not fields_from_config.issubset(fields_from_data): different_fields = list(fields_from_config.difference(fields_from_data)) raise ValidationError(f'These fields are not present in the data: {",".join(different_fields)}') # validate annotations consistency annotations_from_config = set(get_all_control_tag_tuples(config_string)) if not annotations_from_config: logger.debug(f'Annotation schema is not found in config') return annotations_from_data = set(self.summary.created_annotations) if annotations_from_data and not annotations_from_data.issubset(annotations_from_config): different_annotations = list(annotations_from_data.difference(annotations_from_config)) diff_str = [] for ann_tuple in different_annotations: from_name, to_name, t = ann_tuple.split('|') diff_str.append( f'{self.summary.created_annotations[ann_tuple]} ' f'with from_name={from_name}, to_name={to_name}, type={t}') diff_str = '\n'.join(diff_str) raise ValidationError(f'Created annotations are incompatible with provided labeling schema, ' f'we found:\n{diff_str}') # validate labels consistency labels_from_config = get_all_labels(config_string) created_labels = self.summary.created_labels for control_tag_from_data, labels_from_data in created_labels.items(): # Check if labels created in annotations, and their control tag has been removed if labels_from_data and control_tag_from_data not in labels_from_config: raise ValidationError( f'There are {sum(labels_from_data.values(), 0)} annotation(s) created with tag ' f'"{control_tag_from_data}", you can\'t remove it') labels_from_config_by_tag = set(labels_from_config[control_tag_from_data]) if not set(labels_from_data).issubset(set(labels_from_config_by_tag)): different_labels = list(set(labels_from_data).difference(labels_from_config_by_tag)) diff_str = '\n'.join(f'{l} ({labels_from_data[l]} annotations)' for l in different_labels) raise ValidationError(f'These labels still exist in annotations:\n{diff_str}') def _label_config_has_changed(self): return self.label_config != self.__original_label_config def delete_predictions(self): predictions = Prediction.objects.filter(task__project=self) count = predictions.count() predictions.delete() return {'deleted_predictions': count} def get_updated_weights(self): outputs = parse_config(self.label_config) control_weights = {} exclude_control_types = ('Filter',) for control_name in outputs: control_type = outputs[control_name]['type'] if control_type in exclude_control_types: continue control_weights[control_name] = { 'overall': 1.0, 'type': control_type, 'labels': {label: 1.0 for label in outputs[control_name].get('labels', [])} } return control_weights def save(self, *args, recalc=True, **kwargs): exists = True if self.pk else False if self.label_config and (self._label_config_has_changed() or not exists or not self.control_weights): self.control_weights = self.get_updated_weights() super(Project, self).save(*args, **kwargs) project_with_config_just_created = not exists and self.pk and self.label_config if self._label_config_has_changed() or project_with_config_just_created: self.data_types = extract_data_types(self.label_config) if self._label_config_has_changed(): self.__original_label_config = self.label_config if not exists: steps = ProjectOnboardingSteps.objects.all() objs = [ProjectOnboarding(project=self, step=step) for step in steps] ProjectOnboarding.objects.bulk_create(objs) # argument for recalculate project task stats if recalc: self.update_tasks_states( maximum_annotations_changed=self.__maximum_annotations != self.maximum_annotations, overlap_cohort_percentage_changed=self.__overlap_cohort_percentage != self.overlap_cohort_percentage, tasks_number_changed=False ) self.__maximum_annotations = self.maximum_annotations self.__overlap_cohort_percentage = self.overlap_cohort_percentage def get_member_ids(self): if hasattr(self, 'team_link'): # project has defined team scope # TODO: avoid checking team but rather add all project members when creating a project return self.team_link.team.members.values_list('user', flat=True) else: from users.models import User # TODO: may want to return all users from organization return User.objects.none() def has_team_user(self, user): return hasattr(self, 'team_link') and self.team_link.team.has_user(user) def annotators(self): """ Annotators connected to this project including team members """ from users.models import User member_ids = self.get_member_ids() team_members = User.objects.filter(id__in=member_ids).order_by('email') # add members from invited projects project_member_ids = self.members.values_list('user__id', flat=True) project_members = User.objects.filter(id__in=project_member_ids) annotators = team_members | project_members # set annotator.team_member=True if annotator is not an invited user annotators = annotators.annotate( team_member=Case( When(id__in=project_member_ids, then=Value(False)), default=Value(True), output_field=BooleanField(), ) ) return annotators def annotators_with_annotations(self, min_count=500): """ Annotators with annotation number > min_number :param min_count: minimal annotation number to leave an annotators :return: filtered annotators """ annotators = self.annotators() q = Q(annotations__task__project=self) & Q_task_finished_annotations & Q(annotations__ground_truth=False) annotators = annotators.annotate(annotation_count=Count('annotations', filter=q, distinct=True)) return annotators.filter(annotation_count__gte=min_count) def labeled_tasks(self): return self.tasks.filter(is_labeled=True) def has_annotations(self): from tasks.models import Annotation # prevent cycling imports return Annotation.objects.filter(Q(task__project=self) & Q(ground_truth=False)).count() > 0 # [TODO] this should be a template tag or something like this @property def label_config_line(self): c = self.label_config return config_line_stipped(c) def get_sample_task(self, label_config=None): config = label_config or self.label_config task, _, _ = get_sample_task(config) return task def pretty_model_version(self): if not self.model_version: return 'Undefined model version' return pretty_date(self.model_version) def eta(self): """ Show eta for project to be finished eta = avg task annotations finish time * remain annotations task has overlap = amount of task annotations to consider as finished (is_labeled) remain annotations = sum ( task annotations to be done to fulfill each unfinished task overlap) :return: time in seconds """ # finished tasks * overlap finished_tasks = Task.objects.filter(project=self.id, is_labeled=True) # one could make more than need to overlap min_n_finished_annotations = sum([ft.overlap for ft in finished_tasks]) annotations_unfinished_tasks = Annotation.objects.filter( task__project=self.id, task__is_labeled=False, ground_truth=False, result__isnull=False).count() # get minimum remain annotations total_annotations_needed = self.get_total_possible_count annotations_remain = total_annotations_needed - min_n_finished_annotations - annotations_unfinished_tasks # get average time of all finished TC finished_annotations = Annotation.objects.filter( Q(task__project=self.id) & Q(ground_truth=False), result__isnull=False).values('lead_time') avg_lead_time = finished_annotations.aggregate(avg_lead_time=Avg('lead_time'))['avg_lead_time'] if avg_lead_time is None: return None return avg_lead_time * annotations_remain def finished(self): return not self.tasks.filter(is_labeled=False).exists() def annotations_lead_time(self): annotations = Annotation.objects.filter(Q(task__project=self.id) & Q(ground_truth=False)) return annotations.aggregate(avg_lead_time=Avg('lead_time'))['avg_lead_time'] @staticmethod def django_settings(): return settings @staticmethod def max_tasks_file_size(): return settings.TASKS_MAX_FILE_SIZE def get_control_tags_from_config(self): return parse_config(self.label_config) def get_parsed_config(self): return parse_config(self.label_config) def __str__(self): return f'{self.title} (id={self.id})' or _("Business number %d") % self.pk class Meta: db_table = 'project' class ProjectOnboardingSteps(models.Model): """ """ DATA_UPLOAD = "DU" CONF_SETTINGS = "CF" PUBLISH = "PB" INVITE_EXPERTS = "IE" STEPS_CHOICES = ( (DATA_UPLOAD, "Import your data"), (CONF_SETTINGS, "Configure settings"), (PUBLISH, "Publish project"), (INVITE_EXPERTS, "Invite collaborators") ) code = models.CharField(max_length=2, choices=STEPS_CHOICES, null=True) title = models.CharField(_('title'), max_length=1000, null=False) description = models.TextField(_('description'), null=False) order = models.IntegerField(default=0) created_at = models.DateTimeField(_('created at'), auto_now_add=True) updated_at = models.DateTimeField(_('updated at'), auto_now=True) class Meta: ordering = ['order'] class ProjectOnboarding(models.Model): """ """ step = models.ForeignKey(ProjectOnboardingSteps, on_delete=models.CASCADE, related_name="po_through") project = models.ForeignKey(Project, on_delete=models.CASCADE) finished = models.BooleanField(default=False) created_at = models.DateTimeField(_('created at'), auto_now_add=True) updated_at = models.DateTimeField(_('updated at'), auto_now=True) def save(self, *args, **kwargs): super(ProjectOnboarding, self).save(*args, **kwargs) if ProjectOnboarding.objects.filter(project=self.project, finished=True).count() == 4: self.project.skip_onboarding = True self.project.save(recalc=False) class ProjectMember(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='project_memberships', help_text='User ID') # noqa project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='members', help_text='Project ID') enabled = models.BooleanField(default=True, help_text='Project member is enabled') created_at = models.DateTimeField(_('created at'), auto_now_add=True) updated_at = models.DateTimeField(_('updated at'), auto_now=True) class ProjectSummary(models.Model): project = AutoOneToOneField(Project, primary_key=True, on_delete=models.CASCADE, related_name='summary') created_at = models.DateTimeField(_('created at'), auto_now_add=True, help_text='Creation time') # { col1: task_count_with_col1, col2: task_count_with_col2 } all_data_columns = JSONField( _('all data columns'), null=True, default=dict, help_text='All data columns found in imported tasks') # [col1, col2] common_data_columns = JSONField( _('common data columns'), null=True, default=list, help_text='Common data columns found across imported tasks') # { (from_name, to_name, type): annotation_count } created_annotations = JSONField( _('created annotations'), null=True, default=dict, help_text='Unique annotation types identified by tuple (from_name, to_name, type)') # noqa # { from_name: {label1: task_count_with_label1, label2: task_count_with_label2} } created_labels = JSONField( _('created labels'), null=True, default=dict, help_text='Unique labels') def has_permission(self, user): return self.project.has_permission(user) def update_data_columns(self, tasks): common_data_columns = set() all_data_columns = dict(self.all_data_columns) for task in tasks: try: task_data = get_attr_or_item(task, 'data') except KeyError: task_data = task task_data_keys = task_data.keys() for column in task_data_keys: all_data_columns[column] = all_data_columns.get(column, 0) + 1 if not common_data_columns: common_data_columns = set(task_data_keys) else: common_data_columns &= set(task_data_keys) self.all_data_columns = all_data_columns if not self.common_data_columns: self.common_data_columns = list(sorted(common_data_columns)) else: self.common_data_columns = list(sorted(set(self.common_data_columns) & common_data_columns)) self.save() def remove_data_columns(self, tasks): all_data_columns = dict(self.all_data_columns) keys_to_remove = [] for task in tasks: task_data = get_attr_or_item(task, 'data') for key in task_data.keys(): if key in all_data_columns: all_data_columns[key] -= 1 if all_data_columns[key] == 0: keys_to_remove.append(key) all_data_columns.pop(key) self.all_data_columns = all_data_columns if keys_to_remove: common_data_columns = list(self.common_data_columns) for key in keys_to_remove: if key in common_data_columns: common_data_columns.remove(key) self.common_data_columns = common_data_columns self.save() def _get_annotation_key(self, result): result_type = result.get('type') if result_type in ('relation', 'rating', 'pairwise'): return None if 'from_name' not in result or 'to_name' not in result: logger.error( 'Unexpected annotation.result format: "from_name" or "to_name" not found in %r' % result) return None result_from_name = result['from_name'] key = get_annotation_tuple(result_from_name, result['to_name'], result_type or '') return key def _get_labels(self, result): result_type = result.get('type') labels = [] for label in result['value'].get(result_type, []): if isinstance(label, list): labels.extend(label) else: labels.append(label) return labels def update_created_annotations_and_labels(self, annotations): created_annotations = dict(self.created_annotations) labels = dict(self.created_labels) for annotation in annotations: results = get_attr_or_item(annotation, 'result') or [] for result in results: # aggregate annotation types key = self._get_annotation_key(result) if not key: continue created_annotations[key] = created_annotations.get(key, 0) + 1 from_name = result['from_name'] # aggregate labels if from_name not in self.created_labels: labels[from_name] = dict() for label in self._get_labels(result): labels[from_name][label] = labels[from_name].get(label, 0) + 1 self.created_annotations = created_annotations self.created_labels = labels self.save() def remove_created_annotations_and_labels(self, annotations): created_annotations = dict(self.created_annotations) labels = dict(self.created_labels) for annotation in annotations: results = get_attr_or_item(annotation, 'result') or [] for result in results: # reduce annotation counters key = self._get_annotation_key(result) if key in created_annotations: created_annotations[key] -= 1 if created_annotations[key] == 0: created_annotations.pop(key) # reduce labels counters from_name = result.get('from_name') if from_name not in labels: continue for label in self._get_labels(result): if label in labels[from_name]: labels[from_name][label] -= 1 if labels[from_name][label] == 0: labels[from_name].pop(label) if not labels[from_name]: labels.pop(from_name) self.created_annotations = created_annotations self.created_labels = labels self.save()
import os from lxml import etree attribute_type = 0 attribute_value = 1 pc_pcf = '/config/web/pcf/line' apd_class = 'gw.web.rules.APDRulesHelper' pmp_class = 'gw.pmp.apd.web.rules.APDRulesHelper_PMP' file_ends = ['PanelSet.pcf', 'Popup.pcf', 'ListDetail.pcf', 'Screen.pcf'] no_process = ['MenuItemSet', 'WizardStepSet'] input_tags = ['TextInput', 'RangeInput', 'PickerInput', 'TextAreaInput', 'TypeKeyInput', 'BooleanRadioInput', 'DateInput', 'MonetaryAmountInput', 'TextCell'] name_change = dict() def check_no_process(in_file_name: str) -> bool: """ There are some instances where the file should no be processed at the moment, by not processing these files defined in the no_process variable there may be some small manual changes needed to get the new PCF files to be used""" for nop in no_process: if in_file_name.count(nop) > 0: return True return False class ProcessPCF: def process_pcf(self): for x in os.listdir(self.pc_policy_dir): print(f'processing : {x}') if not check_no_process(x): self.process_root(self.pc_policy_dir, x) for x in os.listdir(self.pc_policy_file_dir): print(f'processing : {x}') if not check_no_process(x): self.process_root(self.pc_policy_file_dir, x) for x in os.listdir(self.pc_job_dir): print(f'processing : {x}') if not check_no_process(x): self.process_root(self.pc_job_dir, x) def process_root(self, in_dir: str, in_pcf_file: str): """ The PCF file is opened and each of the elements in the PCF file, depending on the element there may be special processing that needs to take place. When a target element is identified the function to process the element is called. """ tree = etree.parse(in_dir + '/' + in_pcf_file) self.root = tree.getroot() for element in self.root.iter(): if element.tag == 'InputSet': self.process_input_set(element) if element.tag == 'WizardStepSet': self.process_id(element, in_pcf_file) if element.tag == 'Page': self.process_id(element, in_pcf_file) self.process_ref(element, 'ScreenRef') if element.tag == 'PanelSet': self.process_id(element, in_pcf_file) self.process_ref(element, 'PanelRef') if element.tag == 'Popup': self.process_id(element, in_pcf_file) if element.tag == 'LocationGroup': self.process_id(element, in_pcf_file) self.process_ref(element, 'LocationRef') if element.tag == 'Screen': self.process_id(element, in_pcf_file) self.process_ref(element, 'PanelRef') if element.tag == 'Variable': self.process_apd_variable(element) if element.tag in input_tags: self.process_tag(element) if element.tag == 'LocationEntryPoint': self.process_location_entry_point(element, in_pcf_file) content = etree.tostring(self.root, pretty_print=True) new_pcf_file = self.new_file_name(in_pcf_file) print(f'writing : {new_pcf_file}') file = open(in_dir + "/" + new_pcf_file, 'w') file.write(content.decode('utf-8')) file.close() def process_apd_variable(self, element): """ APD sets the variables isEditable and isVisible to use in the PCF, the use of these variables gets around the current processing that worked in previous versions of PolicyCenter. To ensure that PMP works correctly the other variables isRequired and isAvailable are added. While these are not added by APD at the moment they may well feature in a future version.""" required_str = None attributes = element.attrib if 'name' in attributes: _name = attributes.get('name') if _name == 'isEditable': self.update_apd_tag(attributes) if _name == 'isVisible': self.update_apd_tag(attributes) if _name == 'isRequired': self.update_apd_tag(attributes) if _name == 'isAvailable': self.update_apd_tag(attributes) def process_location_entry_point(self, element, in_pfc_file: str): attributes = element.attrib if 'signature' in attributes: _sig_name = in_pfc_file.replace('.pcf', '') _new_name = self.new_file_name(in_pfc_file).replace('.pcf', '') _location = attributes.get('signature') attributes['signature'] = _location.replace(_sig_name, _new_name) def process_ref(self, element, in_ref: str): _ref_type = ['ref', 'location', 'def'] for sub_element in element.iter(): if sub_element.tag == in_ref: attributes = sub_element.attrib for ref in _ref_type: if ref in attributes: _location_name = f"{attributes.get(ref).split("(")[0]}.pcf" if _location_name.startswith('OOSEPanelSet'): pass else: _new_name = self.new_file_name(_location_name) _location = attributes.get(ref) attributes[ref] = _location.replace(_location_name.replace('.pcf', ''), _new_name.replace('.pcf', '')) def process_id(self, element, in_pfc_file: str): """ Updates the id associated with the widget from the original to the modified name making use of the _Ext""" attributes = element.attrib if 'id' in attributes: attributes['id'] = self.new_file_name(in_pfc_file).replace('.pcf', '') def process_tag(self, element): attributes = element.attrib if attributes.get('required') is None or ( not attributes.get('required').startswith(pmp_class) and not attributes.get( 'required') == 'isRequired'): self.process_required(attributes) if attributes.get('valueVisible') is not None and ( not attributes.get('valueVisible').startswith(pmp_class) and not attributes.get( 'valueVisible') == 'isVisible'): self.process_value_visible(attributes, attributes.get('valueVisible'), self.get_field(attributes)) if attributes.get('available') is None or ( not attributes.get('available').startswith(pmp_class) and not attributes.get( 'available') == 'isAvailable'): self.process_available(attributes) for sub_element in element.iter(): if sub_element.tag == 'PostOnChange': self.process_post_on_change(sub_element) def process_post_on_change(self, element): """Changes the APD functions used for the post on change to call the PMP equivalent functions. The PMP version of the functions act as a wrapper incorporating the original APD functions""" attributes = element.attrib if attributes.get('disablePostOnEnter') is None or ( not attributes.get('disablePostOnEnter').startswith(pmp_class)): _pmp_code = attributes.get('disablePostOnEnter').replace(apd_class, pmp_class) attributes['disablePostOnEnter'] = _pmp_code if attributes.get('onChange') is None or ( not attributes.get('onChange').startswith(pmp_class)): _pmp_code = attributes.get('onChange').replace(apd_class, pmp_class) attributes['onChange'] = _pmp_code return self def update_apd_tag(self, attributes): if 'initialValue' in attributes: _initialValue = attributes.get('initialValue').replace(apd_class, pmp_class) attributes['initialValue'] = _initialValue return self def get_field(self, attributes): field_str_array = attributes.get('value').split('.') field_str = '' for field in range(len(field_str_array)): if field < len(field_str_array) - 1: if field == 0: field_str = field_str + field_str_array[field] else: field_str = field_str + '.' + field_str_array[field] else: field_str = field_str + '#' + field_str_array[field] if self: return [field_str_array[0], field_str] def process_available(self, attributes): attributes['available'] = 'isAvailable' return self def process_available_variable(self, available_str, value_str): if value_str[1].startswith('#'): return available_str = pmp_class + '.isAvailable(' \ + value_str[0] + '.PolicyLine, ' \ + value_str[0] + ', ' \ + value_str[1] + '.PropertyInfo' \ + ')' if self: return available_str def process_required(self, attributes): attributes['required'] = 'isRequired' return self def process_required_variable(self, required_str, value_str): """ Function to return the PMP function for the isRequired variable""" if value_str[1].startswith('#'): return default_str = 'false' if required_str is not None: default_str = '(' + required_str + ')' required_str = pmp_class + '.isRequired(' \ + value_str[0] + '.PolicyLine, ' \ + value_str[0] + ', ' \ + value_str[1] + '.PropertyInfo, ' \ + default_str \ + ')' if self: return required_str def process_value_visible(self, attributes, visible_str, value_str): if value_str[1].startswith('#'): return default_str = 'false' if visible_str is not None: default_str = '(' + visible_str + ')' visible_str = visible_str.replace(apd_class, pmp_class) attributes['valueVisible'] = visible_str return self def process_input_set(self, original_element): """ To get round the issue of the PCF on change functionality we need to test for the existence of the isRequired variable. If the isEditable and isVisible defined then we are looking in the right place and if there is no isRequired variable it will be added. To add the variable, information from the input needs to be extracted first.""" apd_variables = {'isEditable': False, 'isVisible': False, 'isRequired': False, 'isAvailable': False} input_attributes = None for sub_element in original_element.iter(): # # If there is an input widget in the input set the attributes are stored for later processing # if sub_element.tag in input_tags: input_attributes = sub_element.attrib # # When a variable is found in the input set and it is in the apa_variables dictionary the # item in the dictionary is updated from False to True # if sub_element.tag == 'Variable': attributes = sub_element.attrib if 'name' in attributes: _name = attributes['name'] apd_variables[_name] = True element = sub_element # # if there exists only the isEditable and the isVisible variables and the input widget attributes # have been saved it is assumed the isRequired and isAvailable variables need to be created # if apd_variables['isEditable'] and apd_variables['isVisible'] and input_attributes is not None: if not apd_variables['isRequired']: pmp_function = self.process_required_variable(input_attributes.get('required'), self.get_field(input_attributes)) variable_element = etree.Element('Variable') variable_element.set('initialValue', pmp_function) variable_element.set('name', 'isRequired') variable_element.set('recalculateOnRefresh', 'true') variable_element.set('type', 'Boolean') original_element.insert(0, variable_element) if not apd_variables['isAvailable']: pmp_function = self.process_available_variable(input_attributes.get('required'), self.get_field(input_attributes)) variable_element = etree.Element('Variable') variable_element.set('initialValue', pmp_function) variable_element.set('name', 'isAvailable') variable_element.set('recalculateOnRefresh', 'true') variable_element.set('type', 'Boolean') original_element.insert(0, variable_element) return self def new_file_name(self, in_pfc_file: str) -> str: """Modifications to the originally generated APD PCF files should not be done, to this end this function defines the name of the new PCF file to be created. """ if name_change.get(in_pfc_file) is not None: return name_change.get(in_pfc_file) if in_pfc_file.count('_Ext') > 0: return in_pfc_file new_pcf_file: str = '' for file_ending in file_ends: if in_pfc_file.endswith(file_ending): new_pcf_file = in_pfc_file.replace(file_ending, '_Ext' + file_ending) if new_pcf_file == '': new_pcf_file = in_pfc_file.replace('.pcf', '_Ext.pcf') if in_pfc_file != new_pcf_file: name_change[in_pfc_file] = new_pcf_file if self: return new_pcf_file def __init__(self, in_pc_path, in_pc_product_abbreviation): self.root = None self.pc_path = in_pc_path self.pc_product_abbreviation = in_pc_product_abbreviation self.pc_policy_dir = self.pc_path + pc_pcf + '/' + self.pc_product_abbreviation + '/policy' self.pc_policy_file_dir = self.pc_path + pc_pcf + '/' + self.pc_product_abbreviation + '/policyfile' self.pc_job_dir = self.pc_path + pc_pcf + '/' + self.pc_product_abbreviation + '/job'
import os from lxml import etree attribute_type = 0 attribute_value = 1 pc_pcf = '/config/web/pcf/line' apd_class = 'gw.web.rules.APDRulesHelper' pmp_class = 'gw.pmp.apd.web.rules.APDRulesHelper_PMP' file_ends = ['PanelSet.pcf', 'Popup.pcf', 'ListDetail.pcf', 'Screen.pcf'] no_process = ['MenuItemSet', 'WizardStepSet'] input_tags = ['TextInput', 'RangeInput', 'PickerInput', 'TextAreaInput', 'TypeKeyInput', 'BooleanRadioInput', 'DateInput', 'MonetaryAmountInput', 'TextCell'] name_change = dict() def check_no_process(in_file_name: str) -> bool: """ There are some instances where the file should no be processed at the moment, by not processing these files defined in the no_process variable there may be some small manual changes needed to get the new PCF files to be used""" for nop in no_process: if in_file_name.count(nop) > 0: return True return False class ProcessPCF: def process_pcf(self): for x in os.listdir(self.pc_policy_dir): print(f'processing : {x}') if not check_no_process(x): self.process_root(self.pc_policy_dir, x) for x in os.listdir(self.pc_policy_file_dir): print(f'processing : {x}') if not check_no_process(x): self.process_root(self.pc_policy_file_dir, x) for x in os.listdir(self.pc_job_dir): print(f'processing : {x}') if not check_no_process(x): self.process_root(self.pc_job_dir, x) def process_root(self, in_dir: str, in_pcf_file: str): """ The PCF file is opened and each of the elements in the PCF file, depending on the element there may be special processing that needs to take place. When a target element is identified the function to process the element is called. """ tree = etree.parse(in_dir + '/' + in_pcf_file) self.root = tree.getroot() for element in self.root.iter(): if element.tag == 'InputSet': self.process_input_set(element) if element.tag == 'WizardStepSet': self.process_id(element, in_pcf_file) if element.tag == 'Page': self.process_id(element, in_pcf_file) self.process_ref(element, 'ScreenRef') if element.tag == 'PanelSet': self.process_id(element, in_pcf_file) self.process_ref(element, 'PanelRef') if element.tag == 'Popup': self.process_id(element, in_pcf_file) if element.tag == 'LocationGroup': self.process_id(element, in_pcf_file) self.process_ref(element, 'LocationRef') if element.tag == 'Screen': self.process_id(element, in_pcf_file) self.process_ref(element, 'PanelRef') if element.tag == 'Variable': self.process_apd_variable(element) if element.tag in input_tags: self.process_tag(element) if element.tag == 'LocationEntryPoint': self.process_location_entry_point(element, in_pcf_file) content = etree.tostring(self.root, pretty_print=True) new_pcf_file = self.new_file_name(in_pcf_file) print(f'writing : {new_pcf_file}') file = open(in_dir + "/" + new_pcf_file, 'w') file.write(content.decode('utf-8')) file.close() def process_apd_variable(self, element): """ APD sets the variables isEditable and isVisible to use in the PCF, the use of these variables gets around the current processing that worked in previous versions of PolicyCenter. To ensure that PMP works correctly the other variables isRequired and isAvailable are added. While these are not added by APD at the moment they may well feature in a future version.""" required_str = None attributes = element.attrib if 'name' in attributes: _name = attributes.get('name') if _name == 'isEditable': self.update_apd_tag(attributes) if _name == 'isVisible': self.update_apd_tag(attributes) if _name == 'isRequired': self.update_apd_tag(attributes) if _name == 'isAvailable': self.update_apd_tag(attributes) def process_location_entry_point(self, element, in_pfc_file: str): attributes = element.attrib if 'signature' in attributes: _sig_name = in_pfc_file.replace('.pcf', '') _new_name = self.new_file_name(in_pfc_file).replace('.pcf', '') _location = attributes.get('signature') attributes['signature'] = _location.replace(_sig_name, _new_name) def process_ref(self, element, in_ref: str): _ref_type = ['ref', 'location', 'def'] for sub_element in element.iter(): if sub_element.tag == in_ref: attributes = sub_element.attrib for ref in _ref_type: if ref in attributes: _location_name = f"{attributes.get(ref).split('(')[0]}.pcf" if _location_name.startswith('OOSEPanelSet'): pass else: _new_name = self.new_file_name(_location_name) _location = attributes.get(ref) attributes[ref] = _location.replace(_location_name.replace('.pcf', ''), _new_name.replace('.pcf', '')) def process_id(self, element, in_pfc_file: str): """ Updates the id associated with the widget from the original to the modified name making use of the _Ext""" attributes = element.attrib if 'id' in attributes: attributes['id'] = self.new_file_name(in_pfc_file).replace('.pcf', '') def process_tag(self, element): attributes = element.attrib if attributes.get('required') is None or ( not attributes.get('required').startswith(pmp_class) and not attributes.get( 'required') == 'isRequired'): self.process_required(attributes) if attributes.get('valueVisible') is not None and ( not attributes.get('valueVisible').startswith(pmp_class) and not attributes.get( 'valueVisible') == 'isVisible'): self.process_value_visible(attributes, attributes.get('valueVisible'), self.get_field(attributes)) if attributes.get('available') is None or ( not attributes.get('available').startswith(pmp_class) and not attributes.get( 'available') == 'isAvailable'): self.process_available(attributes) for sub_element in element.iter(): if sub_element.tag == 'PostOnChange': self.process_post_on_change(sub_element) def process_post_on_change(self, element): """Changes the APD functions used for the post on change to call the PMP equivalent functions. The PMP version of the functions act as a wrapper incorporating the original APD functions""" attributes = element.attrib if attributes.get('disablePostOnEnter') is None or ( not attributes.get('disablePostOnEnter').startswith(pmp_class)): _pmp_code = attributes.get('disablePostOnEnter').replace(apd_class, pmp_class) attributes['disablePostOnEnter'] = _pmp_code if attributes.get('onChange') is None or ( not attributes.get('onChange').startswith(pmp_class)): _pmp_code = attributes.get('onChange').replace(apd_class, pmp_class) attributes['onChange'] = _pmp_code return self def update_apd_tag(self, attributes): if 'initialValue' in attributes: _initialValue = attributes.get('initialValue').replace(apd_class, pmp_class) attributes['initialValue'] = _initialValue return self def get_field(self, attributes): field_str_array = attributes.get('value').split('.') field_str = '' for field in range(len(field_str_array)): if field < len(field_str_array) - 1: if field == 0: field_str = field_str + field_str_array[field] else: field_str = field_str + '.' + field_str_array[field] else: field_str = field_str + '#' + field_str_array[field] if self: return [field_str_array[0], field_str] def process_available(self, attributes): attributes['available'] = 'isAvailable' return self def process_available_variable(self, available_str, value_str): if value_str[1].startswith('#'): return available_str = pmp_class + '.isAvailable(' \ + value_str[0] + '.PolicyLine, ' \ + value_str[0] + ', ' \ + value_str[1] + '.PropertyInfo' \ + ')' if self: return available_str def process_required(self, attributes): attributes['required'] = 'isRequired' return self def process_required_variable(self, required_str, value_str): """ Function to return the PMP function for the isRequired variable""" if value_str[1].startswith('#'): return default_str = 'false' if required_str is not None: default_str = '(' + required_str + ')' required_str = pmp_class + '.isRequired(' \ + value_str[0] + '.PolicyLine, ' \ + value_str[0] + ', ' \ + value_str[1] + '.PropertyInfo, ' \ + default_str \ + ')' if self: return required_str def process_value_visible(self, attributes, visible_str, value_str): if value_str[1].startswith('#'): return default_str = 'false' if visible_str is not None: default_str = '(' + visible_str + ')' visible_str = visible_str.replace(apd_class, pmp_class) attributes['valueVisible'] = visible_str return self def process_input_set(self, original_element): """ To get round the issue of the PCF on change functionality we need to test for the existence of the isRequired variable. If the isEditable and isVisible defined then we are looking in the right place and if there is no isRequired variable it will be added. To add the variable, information from the input needs to be extracted first.""" apd_variables = {'isEditable': False, 'isVisible': False, 'isRequired': False, 'isAvailable': False} input_attributes = None for sub_element in original_element.iter(): # # If there is an input widget in the input set the attributes are stored for later processing # if sub_element.tag in input_tags: input_attributes = sub_element.attrib # # When a variable is found in the input set and it is in the apa_variables dictionary the # item in the dictionary is updated from False to True # if sub_element.tag == 'Variable': attributes = sub_element.attrib if 'name' in attributes: _name = attributes['name'] apd_variables[_name] = True element = sub_element # # if there exists only the isEditable and the isVisible variables and the input widget attributes # have been saved it is assumed the isRequired and isAvailable variables need to be created # if apd_variables['isEditable'] and apd_variables['isVisible'] and input_attributes is not None: if not apd_variables['isRequired']: pmp_function = self.process_required_variable(input_attributes.get('required'), self.get_field(input_attributes)) variable_element = etree.Element('Variable') variable_element.set('initialValue', pmp_function) variable_element.set('name', 'isRequired') variable_element.set('recalculateOnRefresh', 'true') variable_element.set('type', 'Boolean') original_element.insert(0, variable_element) if not apd_variables['isAvailable']: pmp_function = self.process_available_variable(input_attributes.get('required'), self.get_field(input_attributes)) variable_element = etree.Element('Variable') variable_element.set('initialValue', pmp_function) variable_element.set('name', 'isAvailable') variable_element.set('recalculateOnRefresh', 'true') variable_element.set('type', 'Boolean') original_element.insert(0, variable_element) return self def new_file_name(self, in_pfc_file: str) -> str: """Modifications to the originally generated APD PCF files should not be done, to this end this function defines the name of the new PCF file to be created. """ if name_change.get(in_pfc_file) is not None: return name_change.get(in_pfc_file) if in_pfc_file.count('_Ext') > 0: return in_pfc_file new_pcf_file: str = '' for file_ending in file_ends: if in_pfc_file.endswith(file_ending): new_pcf_file = in_pfc_file.replace(file_ending, '_Ext' + file_ending) if new_pcf_file == '': new_pcf_file = in_pfc_file.replace('.pcf', '_Ext.pcf') if in_pfc_file != new_pcf_file: name_change[in_pfc_file] = new_pcf_file if self: return new_pcf_file def __init__(self, in_pc_path, in_pc_product_abbreviation): self.root = None self.pc_path = in_pc_path self.pc_product_abbreviation = in_pc_product_abbreviation self.pc_policy_dir = self.pc_path + pc_pcf + '/' + self.pc_product_abbreviation + '/policy' self.pc_policy_file_dir = self.pc_path + pc_pcf + '/' + self.pc_product_abbreviation + '/policyfile' self.pc_job_dir = self.pc_path + pc_pcf + '/' + self.pc_product_abbreviation + '/job'
import datetime from telethon.tl.tlobject import TLObject from telethon.tl.types import MessageEntityPre from telethon.utils import add_surrogate def mentionuser(name, userid): return f"[{name}](tg://user?id={userid})" def htmlmentionuser(name, userid): return f"<a href='tg://user?id={userid}'>{name}</a>" # kanged from uniborg @spechide # https://github.com/SpEcHiDe/UniBorg/blob/d8b852ee9c29315a53fb27055e54df90d0197f0b/uniborg/utils.py#L250 def parse_pre(text): text = text.strip() return ( text, [MessageEntityPre(offset=0, length=len(add_surrogate(text)), language="")], ) def yaml_format(obj, indent=0, max_str_len=256, max_byte_len=64): """ Pretty formats the given object as a YAML string which is returned. (based on TLObject.pretty_format) """ result = [] if isinstance(obj, TLObject): obj = obj.to_dict() if isinstance(obj, dict): if not obj: return "dict:" items = obj.items() has_items = len(items) > 1 has_multiple_items = len(items) > 2 result.append(obj.get("_", "dict") + (":" if has_items else "")) if has_multiple_items: result.append("\n") indent += 2 for k, v in items: if k == "_" or v is None: continue formatted = yaml_format(v, indent) if not formatted.strip(): continue result.append(" " * (indent if has_multiple_items else 1)) result.append(f"{k}:") if not formatted[0].isspace(): result.append(" ") result.append(f"{formatted}") result.append("\n") if has_items: result.pop() if has_multiple_items: indent -= 2 elif isinstance(obj, str): # truncate long strings and display elipsis result = repr(obj[:max_str_len]) if len(obj) > max_str_len: result += "…" return result elif isinstance(obj, bytes): # repr() bytes if it's printable, hex like "FF EE BB" otherwise if all(0x20 <= c < 0x7F for c in obj): return repr(obj) else: return ( "<…>" if len(obj) > max_byte_len else " ".join(f"{b:02X}" for b in obj) ) elif isinstance(obj, datetime.datetime): # ISO-8601 without timezone offset (telethon dates are always UTC) return obj.strftime("%Y-%m-%d %H:%M:%S") elif hasattr(obj, "__iter__"): # display iterables one after another at the base indentation level result.append("\n") indent += 2 for x in obj: result.append(f"{" " * indent}- {yaml_format(x, indent + 2)}") result.append("\n") result.pop() indent -= 2 else: return repr(obj) return "".join(result)
import datetime from telethon.tl.tlobject import TLObject from telethon.tl.types import MessageEntityPre from telethon.utils import add_surrogate def mentionuser(name, userid): return f"[{name}](tg://user?id={userid})" def htmlmentionuser(name, userid): return f"<a href='tg://user?id={userid}'>{name}</a>" # kanged from uniborg @spechide # https://github.com/SpEcHiDe/UniBorg/blob/d8b852ee9c29315a53fb27055e54df90d0197f0b/uniborg/utils.py#L250 def parse_pre(text): text = text.strip() return ( text, [MessageEntityPre(offset=0, length=len(add_surrogate(text)), language="")], ) def yaml_format(obj, indent=0, max_str_len=256, max_byte_len=64): """ Pretty formats the given object as a YAML string which is returned. (based on TLObject.pretty_format) """ result = [] if isinstance(obj, TLObject): obj = obj.to_dict() if isinstance(obj, dict): if not obj: return "dict:" items = obj.items() has_items = len(items) > 1 has_multiple_items = len(items) > 2 result.append(obj.get("_", "dict") + (":" if has_items else "")) if has_multiple_items: result.append("\n") indent += 2 for k, v in items: if k == "_" or v is None: continue formatted = yaml_format(v, indent) if not formatted.strip(): continue result.append(" " * (indent if has_multiple_items else 1)) result.append(f"{k}:") if not formatted[0].isspace(): result.append(" ") result.append(f"{formatted}") result.append("\n") if has_items: result.pop() if has_multiple_items: indent -= 2 elif isinstance(obj, str): # truncate long strings and display elipsis result = repr(obj[:max_str_len]) if len(obj) > max_str_len: result += "…" return result elif isinstance(obj, bytes): # repr() bytes if it's printable, hex like "FF EE BB" otherwise if all(0x20 <= c < 0x7F for c in obj): return repr(obj) else: return ( "<…>" if len(obj) > max_byte_len else " ".join(f"{b:02X}" for b in obj) ) elif isinstance(obj, datetime.datetime): # ISO-8601 without timezone offset (telethon dates are always UTC) return obj.strftime("%Y-%m-%d %H:%M:%S") elif hasattr(obj, "__iter__"): # display iterables one after another at the base indentation level result.append("\n") indent += 2 for x in obj: result.append(f"{' ' * indent}- {yaml_format(x, indent + 2)}") result.append("\n") result.pop() indent -= 2 else: return repr(obj) return "".join(result)
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import re import time from dataclasses import dataclass from functools import partial from typing import ( TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Pattern, Type, Union, ) from semver import VersionInfo from lisa.base_tools import Cat, Wget from lisa.executable import Tool from lisa.util import BaseClassMixin, LisaException, get_matched_str from lisa.util.logger import get_logger from lisa.util.perf_timer import create_timer from lisa.util.subclasses import Factory if TYPE_CHECKING: from lisa.node import Node _get_init_logger = partial(get_logger, name="os") # Red Hat Enterprise Linux Server 7.8 (Maipo) => Maipo _redhat_release_pattern_bracket = re.compile(r"^.*\(([^ ]*).*\)$") @dataclass # OsVersion - To have full distro info. # GetOSVersion() method at below link was useful to get distro info. # https://github.com/microsoft/lisa/blob/master/Testscripts/Linux/utils.sh class OsVersion: # Vendor/Distributor vendor: str # Release/Version release: str = "" # Codename for the release codename: str = "" # Update available update: str = "" class OperatingSystem: __lsb_release_pattern = re.compile(r"^Description:[ \t]+([\w]+)[ ]+$", re.M) __os_release_pattern_name = re.compile( r"^NAME=\"?([^\" \r\n]+)[^\" \n]*\"?\r?$", re.M ) # For example, the ID and ID_LIKE in /etc/os-release of AlmaLinux is: # ID="almalinux" # ID_LIKE="rhel centos fedora" # The __os_release_pattern_id can match "almalinux" # The __os_release_pattern_idlike can match "rhel" __os_release_pattern_id = re.compile(r"^ID=\"?([^\" \r\n]+)[^\" \n]*\"?\r?$", re.M) __os_release_pattern_idlike = re.compile( r"^ID_LIKE=\"?([^\" \r\n]+)[^\"\n]*\"?\r?$", re.M ) __redhat_release_pattern_header = re.compile(r"^([^ ]*) .*$") __debian_issue_pattern = re.compile(r"^([^ ]+) ?.*$") __release_pattern = re.compile(r"^DISTRIB_ID='?([^ \n']+).*$", re.M) __suse_release_pattern = re.compile(r"^(SUSE).*$", re.M) __posix_factory: Optional[Factory[Any]] = None def __init__(self, node: "Node", is_posix: bool) -> None: super().__init__() self._node: Node = node self._is_posix = is_posix self._log = get_logger(name="os", parent=self._node.log) self._os_version: Optional[OsVersion] = None @classmethod def create(cls, node: "Node") -> Any: log = _get_init_logger(parent=node.log) result: Optional[OperatingSystem] = None detected_info = "" if node.shell.is_posix: # delay create factory to make sure it's late than loading extensions if cls.__posix_factory is None: cls.__posix_factory = Factory[Posix](Posix) cls.__posix_factory.initialize() # cast type for easy to use posix_factory: Factory[Posix] = cls.__posix_factory matched = False os_infos: List[str] = [] for os_info_item in cls._get_detect_string(node): if os_info_item: os_infos.append(os_info_item) for sub_type in posix_factory.values(): posix_type: Type[Posix] = sub_type pattern = posix_type.name_pattern() if pattern.findall(os_info_item): detected_info = os_info_item result = posix_type(node) matched = True break if matched: break if not os_infos: raise LisaException( "unknown posix distro, no os info found. " "it may cause by not support basic commands like `cat`" ) elif not result: raise LisaException( f"unknown posix distro names '{os_infos}', " f"support it in operating_system." ) else: result = Windows(node) log.debug( f"detected OS: '{result.__class__.__name__}' by pattern '{detected_info}'" ) return result @property def is_windows(self) -> bool: return not self._is_posix @property def is_posix(self) -> bool: return self._is_posix @property def os_version(self) -> OsVersion: if not self._os_version: self._os_version = self._get_os_version() return self._os_version @classmethod def _get_detect_string(cls, node: Any) -> Iterable[str]: typed_node: Node = node cmd_result = typed_node.execute(cmd="lsb_release -d", no_error_log=True) yield get_matched_str(cmd_result.stdout, cls.__lsb_release_pattern) cmd_result = typed_node.execute(cmd="cat /etc/os-release", no_error_log=True) yield get_matched_str(cmd_result.stdout, cls.__os_release_pattern_name) yield get_matched_str(cmd_result.stdout, cls.__os_release_pattern_id) cmd_result_os_release = cmd_result # for RedHat, CentOS 6.x cmd_result = typed_node.execute( cmd="cat /etc/redhat-release", no_error_log=True ) yield get_matched_str(cmd_result.stdout, cls.__redhat_release_pattern_header) yield get_matched_str(cmd_result.stdout, _redhat_release_pattern_bracket) # for FreeBSD cmd_result = typed_node.execute(cmd="uname", no_error_log=True) yield cmd_result.stdout # for Debian cmd_result = typed_node.execute(cmd="cat /etc/issue", no_error_log=True) yield get_matched_str(cmd_result.stdout, cls.__debian_issue_pattern) # note, cat /etc/*release doesn't work in some images, so try them one by one # try best for other distros, like Sapphire cmd_result = typed_node.execute(cmd="cat /etc/release", no_error_log=True) yield get_matched_str(cmd_result.stdout, cls.__release_pattern) # try best for other distros, like VeloCloud cmd_result = typed_node.execute(cmd="cat /etc/lsb-release", no_error_log=True) yield get_matched_str(cmd_result.stdout, cls.__release_pattern) # try best for some suse derives, like netiq cmd_result = typed_node.execute(cmd="cat /etc/SuSE-release", no_error_log=True) yield get_matched_str(cmd_result.stdout, cls.__suse_release_pattern) # try best from distros'family through ID_LIKE yield get_matched_str( cmd_result_os_release.stdout, cls.__os_release_pattern_idlike ) def _get_os_version(self) -> OsVersion: raise NotImplementedError class Windows(OperatingSystem): __windows_version_pattern = re.compile( r"^OS Version:[\"\']?\s+(?P<value>.*?)[\"\']?$" ) def __init__(self, node: Any) -> None: super().__init__(node, is_posix=False) def _get_os_version(self) -> OsVersion: os_version = OsVersion("Microsoft Corporation") cmd_result = self._node.execute( cmd='systeminfo | findstr /B /C:"OS Version"', no_error_log=True, ) if cmd_result.exit_code == 0 and cmd_result.stdout != "": os_version.release = get_matched_str( cmd_result.stdout, self.__windows_version_pattern ) if os_version.release == "": raise LisaException("OS version information not found") else: raise LisaException( "Error getting OS version info from systeminfo command" f"exit_code: {cmd_result.exit_code} stderr: {cmd_result.stderr}" ) return os_version class Posix(OperatingSystem, BaseClassMixin): BASEVERSION = re.compile( r"""[vV]? (?P<major>0|[1-9]\d*) (\.\-\_ (?P<minor>0|[1-9]\d*) (\.\-\_ (?P<patch>0|[1-9]\d*) )? )?""", re.VERBOSE, ) __os_info_pattern = re.compile( r"^(?P<name>.*)=[\"\']?(?P<value>.*?)[\"\']?$", re.MULTILINE ) # output of /etc/fedora-release - Fedora release 22 (Twenty Two) # output of /etc/redhat-release - Scientific Linux release 7.1 (Nitrogen) # output of /etc/os-release - # NAME="Debian GNU/Linux" # VERSION_ID="7" # VERSION="7 (wheezy)" # output of lsb_release -a # LSB Version: :base-4.0-amd64:base-4.0-noarch:core-4.0-amd64:core-4.0-noarch # Distributor ID: Scientific # Description: Scientific Linux release 6.7 (Carbon) # In most of the distros, the text in the brackets is the codename. # This regex gets the codename for the ditsro __distro_codename_pattern = re.compile(r"^.*\(([^)]+)") def __init__(self, node: Any) -> None: super().__init__(node, is_posix=True) self._first_time_installation: bool = True @classmethod def type_name(cls) -> str: return cls.__name__ @classmethod def name_pattern(cls) -> Pattern[str]: return re.compile(f"^{cls.type_name()}$") @property def release_version(self) -> VersionInfo: release_version = self._get_os_version().release if VersionInfo.isvalid(release_version): return VersionInfo.parse(release_version) return self._coerce_version(release_version) def _coerce_version(self, version: str) -> VersionInfo: """ Convert an incomplete version string into a semver-compatible Version object source - https://python-semver.readthedocs.io/en/latest/usage.html#dealing-with-invalid-versions * Tries to detect a "basic" version string (``major.minor.patch``). * If not enough components can be found, missing components are set to zero to obtain a valid semver version. :param str version: the version string to convert :return: a tuple with a :class:`Version` instance (or ``None`` if it's not a version) and the rest of the string which doesn't belong to a basic version. :rtype: tuple(:class:`Version` | None, str) """ match = self.BASEVERSION.search(version) if not match: raise LisaException("The OS version release is not in a valid format") ver: Dict[str, Any] = { key: 0 if value is None else int(value) for key, value in match.groupdict().items() } release_version = VersionInfo(**ver) rest = match.string[match.end() :] # noqa:E203 release_version.build = rest return release_version def _install_packages( self, packages: Union[List[str]], signed: bool = True ) -> None: raise NotImplementedError() def _update_packages(self, packages: Optional[Union[List[str]]] = None) -> None: raise NotImplementedError() def _package_exists(self, package: str, signed: bool = True) -> bool: raise NotImplementedError() def _initialize_package_installation(self) -> None: # sub os can override it, but it's optional pass def _get_os_version(self) -> OsVersion: os_version = OsVersion("") # try to set OsVersion from info in /etc/os-release. cmd_result = self._node.execute(cmd="cat /etc/os-release", no_error_log=True) if cmd_result.exit_code != 0: raise LisaException( "Error in running command 'cat /etc/os-release'" f"exit_code: {cmd_result.exit_code} stderr: {cmd_result.stderr}" ) for row in cmd_result.stdout.splitlines(): os_release_info = self.__os_info_pattern.match(row) if not os_release_info: continue if os_release_info.group("name") == "NAME": os_version.vendor = os_release_info.group("value") elif os_release_info.group("name") == "VERSION_ID": os_version.release = os_release_info.group("value") elif os_release_info.group("name") == "VERSION": os_version.codename = get_matched_str( os_release_info.group("value"), self.__distro_codename_pattern, ) if os_version.vendor == "": raise LisaException("OS version information not found") return os_version def _get_package_list( self, packages: Union[str, Tool, Type[Tool], List[Union[str, Tool, Type[Tool]]]] ) -> List[str]: package_names: List[str] = [] if not isinstance(packages, list): packages = [packages] assert isinstance(packages, list), f"actual:{type(packages)}" for item in packages: package_names.append(self.__resolve_package_name(item)) if self._first_time_installation: self._first_time_installation = False self._initialize_package_installation() return package_names def _install_package_from_url( self, package: str, signed: bool = True, ) -> None: """ Used if the package to be installed needs to be downloaded from a url first. """ # when package is URL, download the package first at the working path. wget_tool = self._node.tools[Wget] pkg = wget_tool.get(package, str(self._node.working_path)) self.install_packages(pkg, signed) def install_packages( self, packages: Union[str, Tool, Type[Tool], List[Union[str, Tool, Type[Tool]]]], signed: bool = True, ) -> None: package_names = self._get_package_list(packages) self._install_packages(package_names, signed) def package_exists( self, package: Union[str, Tool, Type[Tool]], signed: bool = True ) -> bool: """ Query if a package/tool is installed on the node. Return Value - bool """ package_name = self.__resolve_package_name(package) return self._package_exists(package_name) def update_packages( self, packages: Union[str, Tool, Type[Tool], List[Union[str, Tool, Type[Tool]]]] ) -> None: package_names = self._get_package_list(packages) self._update_packages(package_names) def __resolve_package_name(self, package: Union[str, Tool, Type[Tool]]) -> str: """ A package can be a string or a tool or a type of tool. Resolve it to a standard package_name so it can be installed. """ if isinstance(package, str): package_name = package elif isinstance(package, Tool): package_name = package.package_name else: assert isinstance(package, type), f"actual:{type(package)}" # Create a temp object, it doesn't query. # So they can be queried together. tool = package.create(self._node) package_name = tool.package_name return package_name class BSD(Posix): ... class Linux(Posix): ... class Debian(Linux): __lsb_os_info_pattern = re.compile( r"^(?P<name>.*):(\s+)(?P<value>.*?)?$", re.MULTILINE ) @classmethod def name_pattern(cls) -> Pattern[str]: return re.compile("^debian|Forcepoint|Kali$") def get_apt_error(self, stdout: str) -> List[str]: error_lines: List[str] = [] for line in stdout.splitlines(keepends=False): if line.startswith("E: "): error_lines.append(line) return error_lines def wait_running_package_process(self) -> None: # wait for 5 minutes timeout = 60 * 5 timer = create_timer() while timeout > timer.elapsed(False): cmd_result = self._node.execute("pidof dpkg") if cmd_result.exit_code == 1: # not found dpkg process, it's ok to exit. break time.sleep(1) if timeout < timer.elapsed(): raise Exception("timeout to wait previous dpkg process stop.") def _initialize_package_installation(self) -> None: self.wait_running_package_process() self._node.execute("apt-get update", sudo=True) def _install_packages( self, packages: Union[List[str]], signed: bool = True ) -> None: command = ( f"DEBIAN_FRONTEND=noninteractive " f"apt-get -y install {" ".join(packages)}" ) if not signed: command += " --allow-unauthenticated" self.wait_running_package_process() install_result = self._node.execute(command, sudo=True) # get error lines. if install_result.exit_code != 0: install_result.assert_exit_code( 0, f"Failed to install {packages}, " f"please check the package name and repo are correct or not.\n" + "\n".join(self.get_apt_error(install_result.stdout)) + "\n", ) def _package_exists(self, package: str, signed: bool = True) -> bool: command = "dpkg --get-selections" result = self._node.execute(command, sudo=True, shell=True) package_pattern = re.compile(f"{package}([ \t]+)install") # Not installed package not shown in the output # Uninstall package will show as deinstall # vim deinstall # vim-common install if len(list(filter(package_pattern.match, result.stdout.splitlines()))) == 1: return True return False def _get_os_version(self) -> OsVersion: os_version = OsVersion("") cmd_result = self._node.execute( cmd="lsb_release -a", shell=True, no_error_log=True ) if cmd_result.exit_code == 0 and cmd_result.stdout != "": for row in cmd_result.stdout.splitlines(): os_release_info = self.__lsb_os_info_pattern.match(row) if os_release_info: if os_release_info.group("name") == "Distributor ID": os_version.vendor = os_release_info.group("value") elif os_release_info.group("name") == "Release": os_version.release = os_release_info.group("value") elif os_release_info.group("name") == "Codename": os_version.codename = os_release_info.group("value") if os_version.vendor == "": raise LisaException("OS version information not found") else: raise LisaException( f"Command 'lsb_release -a' failed. " f"exit_code:{cmd_result.exit_code} stderr: {cmd_result.stderr}" ) return os_version def _update_packages(self, packages: Optional[Union[List[str]]] = None) -> None: command = ( "DEBIAN_FRONTEND=noninteractive apt-get upgrade -y " '-o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" ' ) if packages: command += " ".join(packages) self._node.execute(command, sudo=True, timeout=3600) class Ubuntu(Debian): @classmethod def name_pattern(cls) -> Pattern[str]: return re.compile("^Ubuntu|ubuntu$") def set_boot_entry(self, entry: str) -> None: self._log.debug(f"set boot entry to: {entry}") self._node.execute( f"sed -i.bak \"s/GRUB_DEFAULT=.*/GRUB_DEFAULT='{entry}'/g\" " f"/etc/default/grub", sudo=True, shell=True, ) # output to log for troubleshooting cat = self._node.tools[Cat] cat.run("/etc/default/grub") class FreeBSD(BSD): ... class OpenBSD(BSD): ... class Fedora(Linux): # Red Hat Enterprise Linux Server 7.8 (Maipo) => 7.8 _fedora_release_pattern_version = re.compile(r"^.*release\s+([0-9\.]+).*$") @classmethod def name_pattern(cls) -> Pattern[str]: return re.compile("^Fedora|fedora$") def _install_packages( self, packages: Union[List[str]], signed: bool = True ) -> None: command = f"dnf install -y {" ".join(packages)}" if not signed: command += " --nogpgcheck" install_result = self._node.execute(command, sudo=True) install_result.assert_exit_code(0, f"Failed to install {packages}.") self._log.debug(f"{packages} is/are installed successfully.") def _package_exists(self, package: str, signed: bool = True) -> bool: command = f"dnf list installed {package}" result = self._node.execute(command, sudo=True) if result.exit_code == 0: for row in result.stdout.splitlines(): if package in row: return True return False def _get_os_version(self) -> OsVersion: os_version = OsVersion("") cmd_result = self._node.execute( # Typical output of 'cat /etc/fedora-release' is - # Fedora release 22 (Twenty Two) cmd="cat /etc/fedora-release", no_error_log=True, ) if cmd_result.exit_code == 0 and cmd_result.stdout != "": if "Fedora" not in cmd_result.stdout: raise LisaException("OS version information not found") os_version.vendor = "Fedora" os_version.release = get_matched_str( cmd_result.stdout, self._fedora_release_pattern_version ) os_version.codename = get_matched_str( cmd_result.stdout, self.__distro_codename_pattern ) else: raise LisaException( "Error in running command 'cat /etc/fedora-release'" f"exit_code: {cmd_result.exit_code} stderr: {cmd_result.stderr}" ) return os_version class Redhat(Fedora): @classmethod def name_pattern(cls) -> Pattern[str]: return re.compile("^rhel|Red|AlmaLinux|Rocky|Scientific|acronis|Actifio$") def _initialize_package_installation(self) -> None: cmd_result = self._node.execute("yum makecache", sudo=True) os_version = self._get_os_version() # We may hit issue when run any yum command, caused by out of date # rhui-microsoft-azure-rhel package. # Use below command to update rhui-microsoft-azure-rhel package from microsoft # repo to resolve the issue. # Details please refer https://docs.microsoft.com/en-us/azure/virtual-machines/workloads/redhat/redhat-rhui#azure-rhui-infrastructure # noqa: E501 if "Red Hat" == os_version.vendor and cmd_result.exit_code != 0: cmd_result = self._node.execute( "yum update -y --disablerepo='*' --enablerepo='*microsoft*' ", sudo=True ) cmd_result = self._node.execute("yum makecache", sudo=True) def _install_packages( self, packages: Union[List[str]], signed: bool = True ) -> None: command = f"yum install -y {" ".join(packages)}" if not signed: command += " --nogpgcheck" install_result = self._node.execute(command, sudo=True) # yum returns exit_code=1 if package is already installed. # We do not want to fail if exit_code=1. if install_result.exit_code == 1: self._log.debug(f"{packages} is/are already installed.") elif install_result.exit_code == 0: self._log.debug(f"{packages} is/are installed successfully.") else: raise LisaException( f"Failed to install {packages}. exit_code: {install_result.exit_code}, " f"stderr: {install_result.stderr}" ) def _package_exists(self, package: str, signed: bool = True) -> bool: command = f"yum list installed {package}" result = self._node.execute(command, sudo=True) if result.exit_code == 0: return True return False def _get_os_version(self) -> OsVersion: os_version = OsVersion("") cmd_result = self._node.execute( cmd="cat /etc/redhat-release", no_error_log=True ) if cmd_result.exit_code == 0 and cmd_result.stdout != "": for vendor in [ "Red Hat", "CentOS", "XenServer", "AlmaLinux", "Rocky Linux", ]: if vendor not in cmd_result.stdout: continue os_version.vendor = vendor os_version.release = get_matched_str( cmd_result.stdout, Fedora._fedora_release_pattern_version, ) os_version.codename = get_matched_str( cmd_result.stdout, _redhat_release_pattern_bracket, ) break if os_version.vendor == "": raise LisaException("OS version information not found") else: raise LisaException( "Error in running command 'cat /etc/redhat-release'" f"exit_code: {cmd_result.exit_code} stderr: {cmd_result.stderr}" ) return os_version def _update_packages(self, packages: Optional[Union[List[str]]] = None) -> None: command = "yum -y --nogpgcheck update " if packages: command += " ".join(packages) # older images cost much longer time when update packages # smaller sizes cost much longer time when update packages, e.g. # Basic_A1, Standard_A5, Standard_A1_v2, Standard_D1 # redhat rhel 7-lvm 7.7.2019102813 Basic_A1 cost 2371.568 seconds # redhat rhel 8.1 8.1.2020020415 Basic_A0 cost 2409.116 seconds self._node.execute(command, sudo=True, timeout=3600) class CentOs(Redhat): @classmethod def name_pattern(cls) -> Pattern[str]: return re.compile("^CentOS|Centos|centos|clear-linux-os$") class Oracle(Redhat): pass class CoreOs(Redhat): @classmethod def name_pattern(cls) -> Pattern[str]: return re.compile("^coreos|Flatcar|flatcar$") class Suse(Linux): @classmethod def name_pattern(cls) -> Pattern[str]: return re.compile("^SLES|SUSE|sles|sle-hpc|sle_hpc|opensuse-leap$") def _initialize_package_installation(self) -> None: self._node.execute( "zypper --non-interactive --gpg-auto-import-keys refresh", sudo=True ) def _install_packages( self, packages: Union[List[str]], signed: bool = True ) -> None: command = f"zypper --non-interactive in {" ".join(packages)}" if not signed: command += " --no-gpg-checks" install_result = self._node.execute(command, sudo=True) if install_result.exit_code in (1, 100): raise LisaException( f"Failed to install {packages}. exit_code: {install_result.exit_code}, " f"stderr: {install_result.stderr}" ) elif install_result.exit_code == 0: self._log.debug(f"{packages} is/are installed successfully.") else: self._log.debug( f"{packages} is/are installed." " A system reboot or package manager restart might be required." ) def _update_packages(self, packages: Optional[Union[List[str]]] = None) -> None: command = "zypper --non-interactive --gpg-auto-import-keys update " if packages: command += " ".join(packages) self._node.execute(command, sudo=True, timeout=3600) class NixOS(Linux): pass class OtherLinux(Linux): @classmethod def name_pattern(cls) -> Pattern[str]: """ FMOS - firemon firemon_sip_azure firemon_sip_azure_byol 9.1.3 idms - linuxbasedsystemsdesignltd1580878904727 idmslinux idmslinux_nosla 2020.0703.1 RecoveryOS - unitrends unitrends-enterprise-backup-azure ueb9-azure-trial 1.0.9 sinefa - sinefa sinefa-probe sf-va-msa 26.6.3 """ return re.compile( "^Sapphire|Buildroot|OpenWrt|BloombaseOS|FMOS|idms|RecoveryOS|sinefa$" )
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import re import time from dataclasses import dataclass from functools import partial from typing import ( TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Pattern, Type, Union, ) from semver import VersionInfo from lisa.base_tools import Cat, Wget from lisa.executable import Tool from lisa.util import BaseClassMixin, LisaException, get_matched_str from lisa.util.logger import get_logger from lisa.util.perf_timer import create_timer from lisa.util.subclasses import Factory if TYPE_CHECKING: from lisa.node import Node _get_init_logger = partial(get_logger, name="os") # Red Hat Enterprise Linux Server 7.8 (Maipo) => Maipo _redhat_release_pattern_bracket = re.compile(r"^.*\(([^ ]*).*\)$") @dataclass # OsVersion - To have full distro info. # GetOSVersion() method at below link was useful to get distro info. # https://github.com/microsoft/lisa/blob/master/Testscripts/Linux/utils.sh class OsVersion: # Vendor/Distributor vendor: str # Release/Version release: str = "" # Codename for the release codename: str = "" # Update available update: str = "" class OperatingSystem: __lsb_release_pattern = re.compile(r"^Description:[ \t]+([\w]+)[ ]+$", re.M) __os_release_pattern_name = re.compile( r"^NAME=\"?([^\" \r\n]+)[^\" \n]*\"?\r?$", re.M ) # For example, the ID and ID_LIKE in /etc/os-release of AlmaLinux is: # ID="almalinux" # ID_LIKE="rhel centos fedora" # The __os_release_pattern_id can match "almalinux" # The __os_release_pattern_idlike can match "rhel" __os_release_pattern_id = re.compile(r"^ID=\"?([^\" \r\n]+)[^\" \n]*\"?\r?$", re.M) __os_release_pattern_idlike = re.compile( r"^ID_LIKE=\"?([^\" \r\n]+)[^\"\n]*\"?\r?$", re.M ) __redhat_release_pattern_header = re.compile(r"^([^ ]*) .*$") __debian_issue_pattern = re.compile(r"^([^ ]+) ?.*$") __release_pattern = re.compile(r"^DISTRIB_ID='?([^ \n']+).*$", re.M) __suse_release_pattern = re.compile(r"^(SUSE).*$", re.M) __posix_factory: Optional[Factory[Any]] = None def __init__(self, node: "Node", is_posix: bool) -> None: super().__init__() self._node: Node = node self._is_posix = is_posix self._log = get_logger(name="os", parent=self._node.log) self._os_version: Optional[OsVersion] = None @classmethod def create(cls, node: "Node") -> Any: log = _get_init_logger(parent=node.log) result: Optional[OperatingSystem] = None detected_info = "" if node.shell.is_posix: # delay create factory to make sure it's late than loading extensions if cls.__posix_factory is None: cls.__posix_factory = Factory[Posix](Posix) cls.__posix_factory.initialize() # cast type for easy to use posix_factory: Factory[Posix] = cls.__posix_factory matched = False os_infos: List[str] = [] for os_info_item in cls._get_detect_string(node): if os_info_item: os_infos.append(os_info_item) for sub_type in posix_factory.values(): posix_type: Type[Posix] = sub_type pattern = posix_type.name_pattern() if pattern.findall(os_info_item): detected_info = os_info_item result = posix_type(node) matched = True break if matched: break if not os_infos: raise LisaException( "unknown posix distro, no os info found. " "it may cause by not support basic commands like `cat`" ) elif not result: raise LisaException( f"unknown posix distro names '{os_infos}', " f"support it in operating_system." ) else: result = Windows(node) log.debug( f"detected OS: '{result.__class__.__name__}' by pattern '{detected_info}'" ) return result @property def is_windows(self) -> bool: return not self._is_posix @property def is_posix(self) -> bool: return self._is_posix @property def os_version(self) -> OsVersion: if not self._os_version: self._os_version = self._get_os_version() return self._os_version @classmethod def _get_detect_string(cls, node: Any) -> Iterable[str]: typed_node: Node = node cmd_result = typed_node.execute(cmd="lsb_release -d", no_error_log=True) yield get_matched_str(cmd_result.stdout, cls.__lsb_release_pattern) cmd_result = typed_node.execute(cmd="cat /etc/os-release", no_error_log=True) yield get_matched_str(cmd_result.stdout, cls.__os_release_pattern_name) yield get_matched_str(cmd_result.stdout, cls.__os_release_pattern_id) cmd_result_os_release = cmd_result # for RedHat, CentOS 6.x cmd_result = typed_node.execute( cmd="cat /etc/redhat-release", no_error_log=True ) yield get_matched_str(cmd_result.stdout, cls.__redhat_release_pattern_header) yield get_matched_str(cmd_result.stdout, _redhat_release_pattern_bracket) # for FreeBSD cmd_result = typed_node.execute(cmd="uname", no_error_log=True) yield cmd_result.stdout # for Debian cmd_result = typed_node.execute(cmd="cat /etc/issue", no_error_log=True) yield get_matched_str(cmd_result.stdout, cls.__debian_issue_pattern) # note, cat /etc/*release doesn't work in some images, so try them one by one # try best for other distros, like Sapphire cmd_result = typed_node.execute(cmd="cat /etc/release", no_error_log=True) yield get_matched_str(cmd_result.stdout, cls.__release_pattern) # try best for other distros, like VeloCloud cmd_result = typed_node.execute(cmd="cat /etc/lsb-release", no_error_log=True) yield get_matched_str(cmd_result.stdout, cls.__release_pattern) # try best for some suse derives, like netiq cmd_result = typed_node.execute(cmd="cat /etc/SuSE-release", no_error_log=True) yield get_matched_str(cmd_result.stdout, cls.__suse_release_pattern) # try best from distros'family through ID_LIKE yield get_matched_str( cmd_result_os_release.stdout, cls.__os_release_pattern_idlike ) def _get_os_version(self) -> OsVersion: raise NotImplementedError class Windows(OperatingSystem): __windows_version_pattern = re.compile( r"^OS Version:[\"\']?\s+(?P<value>.*?)[\"\']?$" ) def __init__(self, node: Any) -> None: super().__init__(node, is_posix=False) def _get_os_version(self) -> OsVersion: os_version = OsVersion("Microsoft Corporation") cmd_result = self._node.execute( cmd='systeminfo | findstr /B /C:"OS Version"', no_error_log=True, ) if cmd_result.exit_code == 0 and cmd_result.stdout != "": os_version.release = get_matched_str( cmd_result.stdout, self.__windows_version_pattern ) if os_version.release == "": raise LisaException("OS version information not found") else: raise LisaException( "Error getting OS version info from systeminfo command" f"exit_code: {cmd_result.exit_code} stderr: {cmd_result.stderr}" ) return os_version class Posix(OperatingSystem, BaseClassMixin): BASEVERSION = re.compile( r"""[vV]? (?P<major>0|[1-9]\d*) (\.\-\_ (?P<minor>0|[1-9]\d*) (\.\-\_ (?P<patch>0|[1-9]\d*) )? )?""", re.VERBOSE, ) __os_info_pattern = re.compile( r"^(?P<name>.*)=[\"\']?(?P<value>.*?)[\"\']?$", re.MULTILINE ) # output of /etc/fedora-release - Fedora release 22 (Twenty Two) # output of /etc/redhat-release - Scientific Linux release 7.1 (Nitrogen) # output of /etc/os-release - # NAME="Debian GNU/Linux" # VERSION_ID="7" # VERSION="7 (wheezy)" # output of lsb_release -a # LSB Version: :base-4.0-amd64:base-4.0-noarch:core-4.0-amd64:core-4.0-noarch # Distributor ID: Scientific # Description: Scientific Linux release 6.7 (Carbon) # In most of the distros, the text in the brackets is the codename. # This regex gets the codename for the ditsro __distro_codename_pattern = re.compile(r"^.*\(([^)]+)") def __init__(self, node: Any) -> None: super().__init__(node, is_posix=True) self._first_time_installation: bool = True @classmethod def type_name(cls) -> str: return cls.__name__ @classmethod def name_pattern(cls) -> Pattern[str]: return re.compile(f"^{cls.type_name()}$") @property def release_version(self) -> VersionInfo: release_version = self._get_os_version().release if VersionInfo.isvalid(release_version): return VersionInfo.parse(release_version) return self._coerce_version(release_version) def _coerce_version(self, version: str) -> VersionInfo: """ Convert an incomplete version string into a semver-compatible Version object source - https://python-semver.readthedocs.io/en/latest/usage.html#dealing-with-invalid-versions * Tries to detect a "basic" version string (``major.minor.patch``). * If not enough components can be found, missing components are set to zero to obtain a valid semver version. :param str version: the version string to convert :return: a tuple with a :class:`Version` instance (or ``None`` if it's not a version) and the rest of the string which doesn't belong to a basic version. :rtype: tuple(:class:`Version` | None, str) """ match = self.BASEVERSION.search(version) if not match: raise LisaException("The OS version release is not in a valid format") ver: Dict[str, Any] = { key: 0 if value is None else int(value) for key, value in match.groupdict().items() } release_version = VersionInfo(**ver) rest = match.string[match.end() :] # noqa:E203 release_version.build = rest return release_version def _install_packages( self, packages: Union[List[str]], signed: bool = True ) -> None: raise NotImplementedError() def _update_packages(self, packages: Optional[Union[List[str]]] = None) -> None: raise NotImplementedError() def _package_exists(self, package: str, signed: bool = True) -> bool: raise NotImplementedError() def _initialize_package_installation(self) -> None: # sub os can override it, but it's optional pass def _get_os_version(self) -> OsVersion: os_version = OsVersion("") # try to set OsVersion from info in /etc/os-release. cmd_result = self._node.execute(cmd="cat /etc/os-release", no_error_log=True) if cmd_result.exit_code != 0: raise LisaException( "Error in running command 'cat /etc/os-release'" f"exit_code: {cmd_result.exit_code} stderr: {cmd_result.stderr}" ) for row in cmd_result.stdout.splitlines(): os_release_info = self.__os_info_pattern.match(row) if not os_release_info: continue if os_release_info.group("name") == "NAME": os_version.vendor = os_release_info.group("value") elif os_release_info.group("name") == "VERSION_ID": os_version.release = os_release_info.group("value") elif os_release_info.group("name") == "VERSION": os_version.codename = get_matched_str( os_release_info.group("value"), self.__distro_codename_pattern, ) if os_version.vendor == "": raise LisaException("OS version information not found") return os_version def _get_package_list( self, packages: Union[str, Tool, Type[Tool], List[Union[str, Tool, Type[Tool]]]] ) -> List[str]: package_names: List[str] = [] if not isinstance(packages, list): packages = [packages] assert isinstance(packages, list), f"actual:{type(packages)}" for item in packages: package_names.append(self.__resolve_package_name(item)) if self._first_time_installation: self._first_time_installation = False self._initialize_package_installation() return package_names def _install_package_from_url( self, package: str, signed: bool = True, ) -> None: """ Used if the package to be installed needs to be downloaded from a url first. """ # when package is URL, download the package first at the working path. wget_tool = self._node.tools[Wget] pkg = wget_tool.get(package, str(self._node.working_path)) self.install_packages(pkg, signed) def install_packages( self, packages: Union[str, Tool, Type[Tool], List[Union[str, Tool, Type[Tool]]]], signed: bool = True, ) -> None: package_names = self._get_package_list(packages) self._install_packages(package_names, signed) def package_exists( self, package: Union[str, Tool, Type[Tool]], signed: bool = True ) -> bool: """ Query if a package/tool is installed on the node. Return Value - bool """ package_name = self.__resolve_package_name(package) return self._package_exists(package_name) def update_packages( self, packages: Union[str, Tool, Type[Tool], List[Union[str, Tool, Type[Tool]]]] ) -> None: package_names = self._get_package_list(packages) self._update_packages(package_names) def __resolve_package_name(self, package: Union[str, Tool, Type[Tool]]) -> str: """ A package can be a string or a tool or a type of tool. Resolve it to a standard package_name so it can be installed. """ if isinstance(package, str): package_name = package elif isinstance(package, Tool): package_name = package.package_name else: assert isinstance(package, type), f"actual:{type(package)}" # Create a temp object, it doesn't query. # So they can be queried together. tool = package.create(self._node) package_name = tool.package_name return package_name class BSD(Posix): ... class Linux(Posix): ... class Debian(Linux): __lsb_os_info_pattern = re.compile( r"^(?P<name>.*):(\s+)(?P<value>.*?)?$", re.MULTILINE ) @classmethod def name_pattern(cls) -> Pattern[str]: return re.compile("^debian|Forcepoint|Kali$") def get_apt_error(self, stdout: str) -> List[str]: error_lines: List[str] = [] for line in stdout.splitlines(keepends=False): if line.startswith("E: "): error_lines.append(line) return error_lines def wait_running_package_process(self) -> None: # wait for 5 minutes timeout = 60 * 5 timer = create_timer() while timeout > timer.elapsed(False): cmd_result = self._node.execute("pidof dpkg") if cmd_result.exit_code == 1: # not found dpkg process, it's ok to exit. break time.sleep(1) if timeout < timer.elapsed(): raise Exception("timeout to wait previous dpkg process stop.") def _initialize_package_installation(self) -> None: self.wait_running_package_process() self._node.execute("apt-get update", sudo=True) def _install_packages( self, packages: Union[List[str]], signed: bool = True ) -> None: command = ( f"DEBIAN_FRONTEND=noninteractive " f"apt-get -y install {' '.join(packages)}" ) if not signed: command += " --allow-unauthenticated" self.wait_running_package_process() install_result = self._node.execute(command, sudo=True) # get error lines. if install_result.exit_code != 0: install_result.assert_exit_code( 0, f"Failed to install {packages}, " f"please check the package name and repo are correct or not.\n" + "\n".join(self.get_apt_error(install_result.stdout)) + "\n", ) def _package_exists(self, package: str, signed: bool = True) -> bool: command = "dpkg --get-selections" result = self._node.execute(command, sudo=True, shell=True) package_pattern = re.compile(f"{package}([ \t]+)install") # Not installed package not shown in the output # Uninstall package will show as deinstall # vim deinstall # vim-common install if len(list(filter(package_pattern.match, result.stdout.splitlines()))) == 1: return True return False def _get_os_version(self) -> OsVersion: os_version = OsVersion("") cmd_result = self._node.execute( cmd="lsb_release -a", shell=True, no_error_log=True ) if cmd_result.exit_code == 0 and cmd_result.stdout != "": for row in cmd_result.stdout.splitlines(): os_release_info = self.__lsb_os_info_pattern.match(row) if os_release_info: if os_release_info.group("name") == "Distributor ID": os_version.vendor = os_release_info.group("value") elif os_release_info.group("name") == "Release": os_version.release = os_release_info.group("value") elif os_release_info.group("name") == "Codename": os_version.codename = os_release_info.group("value") if os_version.vendor == "": raise LisaException("OS version information not found") else: raise LisaException( f"Command 'lsb_release -a' failed. " f"exit_code:{cmd_result.exit_code} stderr: {cmd_result.stderr}" ) return os_version def _update_packages(self, packages: Optional[Union[List[str]]] = None) -> None: command = ( "DEBIAN_FRONTEND=noninteractive apt-get upgrade -y " '-o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" ' ) if packages: command += " ".join(packages) self._node.execute(command, sudo=True, timeout=3600) class Ubuntu(Debian): @classmethod def name_pattern(cls) -> Pattern[str]: return re.compile("^Ubuntu|ubuntu$") def set_boot_entry(self, entry: str) -> None: self._log.debug(f"set boot entry to: {entry}") self._node.execute( f"sed -i.bak \"s/GRUB_DEFAULT=.*/GRUB_DEFAULT='{entry}'/g\" " f"/etc/default/grub", sudo=True, shell=True, ) # output to log for troubleshooting cat = self._node.tools[Cat] cat.run("/etc/default/grub") class FreeBSD(BSD): ... class OpenBSD(BSD): ... class Fedora(Linux): # Red Hat Enterprise Linux Server 7.8 (Maipo) => 7.8 _fedora_release_pattern_version = re.compile(r"^.*release\s+([0-9\.]+).*$") @classmethod def name_pattern(cls) -> Pattern[str]: return re.compile("^Fedora|fedora$") def _install_packages( self, packages: Union[List[str]], signed: bool = True ) -> None: command = f"dnf install -y {' '.join(packages)}" if not signed: command += " --nogpgcheck" install_result = self._node.execute(command, sudo=True) install_result.assert_exit_code(0, f"Failed to install {packages}.") self._log.debug(f"{packages} is/are installed successfully.") def _package_exists(self, package: str, signed: bool = True) -> bool: command = f"dnf list installed {package}" result = self._node.execute(command, sudo=True) if result.exit_code == 0: for row in result.stdout.splitlines(): if package in row: return True return False def _get_os_version(self) -> OsVersion: os_version = OsVersion("") cmd_result = self._node.execute( # Typical output of 'cat /etc/fedora-release' is - # Fedora release 22 (Twenty Two) cmd="cat /etc/fedora-release", no_error_log=True, ) if cmd_result.exit_code == 0 and cmd_result.stdout != "": if "Fedora" not in cmd_result.stdout: raise LisaException("OS version information not found") os_version.vendor = "Fedora" os_version.release = get_matched_str( cmd_result.stdout, self._fedora_release_pattern_version ) os_version.codename = get_matched_str( cmd_result.stdout, self.__distro_codename_pattern ) else: raise LisaException( "Error in running command 'cat /etc/fedora-release'" f"exit_code: {cmd_result.exit_code} stderr: {cmd_result.stderr}" ) return os_version class Redhat(Fedora): @classmethod def name_pattern(cls) -> Pattern[str]: return re.compile("^rhel|Red|AlmaLinux|Rocky|Scientific|acronis|Actifio$") def _initialize_package_installation(self) -> None: cmd_result = self._node.execute("yum makecache", sudo=True) os_version = self._get_os_version() # We may hit issue when run any yum command, caused by out of date # rhui-microsoft-azure-rhel package. # Use below command to update rhui-microsoft-azure-rhel package from microsoft # repo to resolve the issue. # Details please refer https://docs.microsoft.com/en-us/azure/virtual-machines/workloads/redhat/redhat-rhui#azure-rhui-infrastructure # noqa: E501 if "Red Hat" == os_version.vendor and cmd_result.exit_code != 0: cmd_result = self._node.execute( "yum update -y --disablerepo='*' --enablerepo='*microsoft*' ", sudo=True ) cmd_result = self._node.execute("yum makecache", sudo=True) def _install_packages( self, packages: Union[List[str]], signed: bool = True ) -> None: command = f"yum install -y {' '.join(packages)}" if not signed: command += " --nogpgcheck" install_result = self._node.execute(command, sudo=True) # yum returns exit_code=1 if package is already installed. # We do not want to fail if exit_code=1. if install_result.exit_code == 1: self._log.debug(f"{packages} is/are already installed.") elif install_result.exit_code == 0: self._log.debug(f"{packages} is/are installed successfully.") else: raise LisaException( f"Failed to install {packages}. exit_code: {install_result.exit_code}, " f"stderr: {install_result.stderr}" ) def _package_exists(self, package: str, signed: bool = True) -> bool: command = f"yum list installed {package}" result = self._node.execute(command, sudo=True) if result.exit_code == 0: return True return False def _get_os_version(self) -> OsVersion: os_version = OsVersion("") cmd_result = self._node.execute( cmd="cat /etc/redhat-release", no_error_log=True ) if cmd_result.exit_code == 0 and cmd_result.stdout != "": for vendor in [ "Red Hat", "CentOS", "XenServer", "AlmaLinux", "Rocky Linux", ]: if vendor not in cmd_result.stdout: continue os_version.vendor = vendor os_version.release = get_matched_str( cmd_result.stdout, Fedora._fedora_release_pattern_version, ) os_version.codename = get_matched_str( cmd_result.stdout, _redhat_release_pattern_bracket, ) break if os_version.vendor == "": raise LisaException("OS version information not found") else: raise LisaException( "Error in running command 'cat /etc/redhat-release'" f"exit_code: {cmd_result.exit_code} stderr: {cmd_result.stderr}" ) return os_version def _update_packages(self, packages: Optional[Union[List[str]]] = None) -> None: command = "yum -y --nogpgcheck update " if packages: command += " ".join(packages) # older images cost much longer time when update packages # smaller sizes cost much longer time when update packages, e.g. # Basic_A1, Standard_A5, Standard_A1_v2, Standard_D1 # redhat rhel 7-lvm 7.7.2019102813 Basic_A1 cost 2371.568 seconds # redhat rhel 8.1 8.1.2020020415 Basic_A0 cost 2409.116 seconds self._node.execute(command, sudo=True, timeout=3600) class CentOs(Redhat): @classmethod def name_pattern(cls) -> Pattern[str]: return re.compile("^CentOS|Centos|centos|clear-linux-os$") class Oracle(Redhat): pass class CoreOs(Redhat): @classmethod def name_pattern(cls) -> Pattern[str]: return re.compile("^coreos|Flatcar|flatcar$") class Suse(Linux): @classmethod def name_pattern(cls) -> Pattern[str]: return re.compile("^SLES|SUSE|sles|sle-hpc|sle_hpc|opensuse-leap$") def _initialize_package_installation(self) -> None: self._node.execute( "zypper --non-interactive --gpg-auto-import-keys refresh", sudo=True ) def _install_packages( self, packages: Union[List[str]], signed: bool = True ) -> None: command = f"zypper --non-interactive in {' '.join(packages)}" if not signed: command += " --no-gpg-checks" install_result = self._node.execute(command, sudo=True) if install_result.exit_code in (1, 100): raise LisaException( f"Failed to install {packages}. exit_code: {install_result.exit_code}, " f"stderr: {install_result.stderr}" ) elif install_result.exit_code == 0: self._log.debug(f"{packages} is/are installed successfully.") else: self._log.debug( f"{packages} is/are installed." " A system reboot or package manager restart might be required." ) def _update_packages(self, packages: Optional[Union[List[str]]] = None) -> None: command = "zypper --non-interactive --gpg-auto-import-keys update " if packages: command += " ".join(packages) self._node.execute(command, sudo=True, timeout=3600) class NixOS(Linux): pass class OtherLinux(Linux): @classmethod def name_pattern(cls) -> Pattern[str]: """ FMOS - firemon firemon_sip_azure firemon_sip_azure_byol 9.1.3 idms - linuxbasedsystemsdesignltd1580878904727 idmslinux idmslinux_nosla 2020.0703.1 RecoveryOS - unitrends unitrends-enterprise-backup-azure ueb9-azure-trial 1.0.9 sinefa - sinefa sinefa-probe sf-va-msa 26.6.3 """ return re.compile( "^Sapphire|Buildroot|OpenWrt|BloombaseOS|FMOS|idms|RecoveryOS|sinefa$" )
import contextlib import collections import pickle import re import sys import warnings from unittest import TestCase, main, skipUnless, skip from copy import copy, deepcopy from typing import Any, NoReturn from typing import TypeVar, AnyStr from typing import T, KT, VT # Not in __all__. from typing import Union, Optional, Literal from typing import Tuple, List, Dict, MutableMapping from typing import Callable from typing import Generic, ClassVar, Final, final, Protocol from typing import cast, runtime_checkable from typing import get_type_hints from typing import get_origin, get_args from typing import is_typeddict from typing import no_type_check, no_type_check_decorator from typing import Type from typing import NewType from typing import NamedTuple, TypedDict from typing import IO, TextIO, BinaryIO from typing import Pattern, Match from typing import Annotated, ForwardRef from typing import TypeAlias from typing import ParamSpec, Concatenate, ParamSpecArgs, ParamSpecKwargs from typing import TypeGuard import abc import typing import weakref import types from test.support import import_helper from test import mod_generics_cache from test import _typed_dict_helper py_typing = import_helper.import_fresh_module('typing', blocked=['_typing']) c_typing = import_helper.import_fresh_module('typing', fresh=['_typing']) class BaseTestCase(TestCase): def assertIsSubclass(self, cls, class_or_tuple, msg=None): if not issubclass(cls, class_or_tuple): message = '%r is not a subclass of %r' % (cls, class_or_tuple) if msg is not None: message += ' : %s' % msg raise self.failureException(message) def assertNotIsSubclass(self, cls, class_or_tuple, msg=None): if issubclass(cls, class_or_tuple): message = '%r is a subclass of %r' % (cls, class_or_tuple) if msg is not None: message += ' : %s' % msg raise self.failureException(message) def clear_caches(self): for f in typing._cleanups: f() class Employee: pass class Manager(Employee): pass class Founder(Employee): pass class ManagingFounder(Manager, Founder): pass class AnyTests(BaseTestCase): def test_any_instance_type_error(self): with self.assertRaises(TypeError): isinstance(42, Any) def test_any_subclass_type_error(self): with self.assertRaises(TypeError): issubclass(Employee, Any) with self.assertRaises(TypeError): issubclass(Any, Employee) def test_repr(self): self.assertEqual(repr(Any), 'typing.Any') def test_errors(self): with self.assertRaises(TypeError): issubclass(42, Any) with self.assertRaises(TypeError): Any[int] # Any is not a generic type. def test_cannot_subclass(self): with self.assertRaises(TypeError): class A(Any): pass with self.assertRaises(TypeError): class A(type(Any)): pass def test_cannot_instantiate(self): with self.assertRaises(TypeError): Any() with self.assertRaises(TypeError): type(Any)() def test_any_works_with_alias(self): # These expressions must simply not fail. typing.Match[Any] typing.Pattern[Any] typing.IO[Any] class NoReturnTests(BaseTestCase): def test_noreturn_instance_type_error(self): with self.assertRaises(TypeError): isinstance(42, NoReturn) def test_noreturn_subclass_type_error(self): with self.assertRaises(TypeError): issubclass(Employee, NoReturn) with self.assertRaises(TypeError): issubclass(NoReturn, Employee) def test_repr(self): self.assertEqual(repr(NoReturn), 'typing.NoReturn') def test_not_generic(self): with self.assertRaises(TypeError): NoReturn[int] def test_cannot_subclass(self): with self.assertRaises(TypeError): class A(NoReturn): pass with self.assertRaises(TypeError): class A(type(NoReturn)): pass def test_cannot_instantiate(self): with self.assertRaises(TypeError): NoReturn() with self.assertRaises(TypeError): type(NoReturn)() class TypeVarTests(BaseTestCase): def test_basic_plain(self): T = TypeVar('T') # T equals itself. self.assertEqual(T, T) # T is an instance of TypeVar self.assertIsInstance(T, TypeVar) def test_typevar_instance_type_error(self): T = TypeVar('T') with self.assertRaises(TypeError): isinstance(42, T) def test_typevar_subclass_type_error(self): T = TypeVar('T') with self.assertRaises(TypeError): issubclass(int, T) with self.assertRaises(TypeError): issubclass(T, int) def test_constrained_error(self): with self.assertRaises(TypeError): X = TypeVar('X', int) X def test_union_unique(self): X = TypeVar('X') Y = TypeVar('Y') self.assertNotEqual(X, Y) self.assertEqual(Union[X], X) self.assertNotEqual(Union[X], Union[X, Y]) self.assertEqual(Union[X, X], X) self.assertNotEqual(Union[X, int], Union[X]) self.assertNotEqual(Union[X, int], Union[int]) self.assertEqual(Union[X, int].__args__, (X, int)) self.assertEqual(Union[X, int].__parameters__, (X,)) self.assertIs(Union[X, int].__origin__, Union) def test_or(self): X = TypeVar('X') # use a string because str doesn't implement # __or__/__ror__ itself self.assertEqual(X | "x", Union[X, "x"]) self.assertEqual("x" | X, Union["x", X]) # make sure the order is correct self.assertEqual(get_args(X | "x"), (X, ForwardRef("x"))) self.assertEqual(get_args("x" | X), (ForwardRef("x"), X)) def test_union_constrained(self): A = TypeVar('A', str, bytes) self.assertNotEqual(Union[A, str], Union[A]) def test_repr(self): self.assertEqual(repr(T), '~T') self.assertEqual(repr(KT), '~KT') self.assertEqual(repr(VT), '~VT') self.assertEqual(repr(AnyStr), '~AnyStr') T_co = TypeVar('T_co', covariant=True) self.assertEqual(repr(T_co), '+T_co') T_contra = TypeVar('T_contra', contravariant=True) self.assertEqual(repr(T_contra), '-T_contra') def test_no_redefinition(self): self.assertNotEqual(TypeVar('T'), TypeVar('T')) self.assertNotEqual(TypeVar('T', int, str), TypeVar('T', int, str)) def test_cannot_subclass_vars(self): with self.assertRaises(TypeError): class V(TypeVar('T')): pass def test_cannot_subclass_var_itself(self): with self.assertRaises(TypeError): class V(TypeVar): pass def test_cannot_instantiate_vars(self): with self.assertRaises(TypeError): TypeVar('A')() def test_bound_errors(self): with self.assertRaises(TypeError): TypeVar('X', bound=42) with self.assertRaises(TypeError): TypeVar('X', str, float, bound=Employee) def test_missing__name__(self): # See bpo-39942 code = ("import typing\n" "T = typing.TypeVar('T')\n" ) exec(code, {}) def test_no_bivariant(self): with self.assertRaises(ValueError): TypeVar('T', covariant=True, contravariant=True) class UnionTests(BaseTestCase): def test_basics(self): u = Union[int, float] self.assertNotEqual(u, Union) def test_subclass_error(self): with self.assertRaises(TypeError): issubclass(int, Union) with self.assertRaises(TypeError): issubclass(Union, int) with self.assertRaises(TypeError): issubclass(Union[int, str], int) def test_union_any(self): u = Union[Any] self.assertEqual(u, Any) u1 = Union[int, Any] u2 = Union[Any, int] u3 = Union[Any, object] self.assertEqual(u1, u2) self.assertNotEqual(u1, Any) self.assertNotEqual(u2, Any) self.assertNotEqual(u3, Any) def test_union_object(self): u = Union[object] self.assertEqual(u, object) u1 = Union[int, object] u2 = Union[object, int] self.assertEqual(u1, u2) self.assertNotEqual(u1, object) self.assertNotEqual(u2, object) def test_unordered(self): u1 = Union[int, float] u2 = Union[float, int] self.assertEqual(u1, u2) def test_single_class_disappears(self): t = Union[Employee] self.assertIs(t, Employee) def test_base_class_kept(self): u = Union[Employee, Manager] self.assertNotEqual(u, Employee) self.assertIn(Employee, u.__args__) self.assertIn(Manager, u.__args__) def test_union_union(self): u = Union[int, float] v = Union[u, Employee] self.assertEqual(v, Union[int, float, Employee]) def test_repr(self): self.assertEqual(repr(Union), 'typing.Union') u = Union[Employee, int] self.assertEqual(repr(u), 'typing.Union[%s.Employee, int]' % __name__) u = Union[int, Employee] self.assertEqual(repr(u), 'typing.Union[int, %s.Employee]' % __name__) T = TypeVar('T') u = Union[T, int][int] self.assertEqual(repr(u), repr(int)) u = Union[List[int], int] self.assertEqual(repr(u), 'typing.Union[typing.List[int], int]') u = Union[list[int], dict[str, float]] self.assertEqual(repr(u), 'typing.Union[list[int], dict[str, float]]') u = Union[int | float] self.assertEqual(repr(u), 'typing.Union[int, float]') def test_cannot_subclass(self): with self.assertRaises(TypeError): class C(Union): pass with self.assertRaises(TypeError): class C(type(Union)): pass with self.assertRaises(TypeError): class C(Union[int, str]): pass def test_cannot_instantiate(self): with self.assertRaises(TypeError): Union() with self.assertRaises(TypeError): type(Union)() u = Union[int, float] with self.assertRaises(TypeError): u() with self.assertRaises(TypeError): type(u)() def test_union_generalization(self): self.assertFalse(Union[str, typing.Iterable[int]] == str) self.assertFalse(Union[str, typing.Iterable[int]] == typing.Iterable[int]) self.assertIn(str, Union[str, typing.Iterable[int]].__args__) self.assertIn(typing.Iterable[int], Union[str, typing.Iterable[int]].__args__) def test_union_compare_other(self): self.assertNotEqual(Union, object) self.assertNotEqual(Union, Any) self.assertNotEqual(ClassVar, Union) self.assertNotEqual(Optional, Union) self.assertNotEqual([None], Optional) self.assertNotEqual(Optional, typing.Mapping) self.assertNotEqual(Optional[typing.MutableMapping], Union) def test_optional(self): o = Optional[int] u = Union[int, None] self.assertEqual(o, u) def test_empty(self): with self.assertRaises(TypeError): Union[()] def test_no_eval_union(self): u = Union[int, str] def f(x: u): ... self.assertIs(get_type_hints(f)['x'], u) def test_function_repr_union(self): def fun() -> int: ... self.assertEqual(repr(Union[fun, int]), 'typing.Union[fun, int]') def test_union_str_pattern(self): # Shouldn't crash; see http://bugs.python.org/issue25390 A = Union[str, Pattern] A def test_etree(self): # See https://github.com/python/typing/issues/229 # (Only relevant for Python 2.) from xml.etree.ElementTree import Element Union[Element, str] # Shouldn't crash def Elem(*args): return Element(*args) Union[Elem, str] # Nor should this class TupleTests(BaseTestCase): def test_basics(self): with self.assertRaises(TypeError): issubclass(Tuple, Tuple[int, str]) with self.assertRaises(TypeError): issubclass(tuple, Tuple[int, str]) class TP(tuple): ... self.assertIsSubclass(tuple, Tuple) self.assertIsSubclass(TP, Tuple) def test_equality(self): self.assertEqual(Tuple[int], Tuple[int]) self.assertEqual(Tuple[int, ...], Tuple[int, ...]) self.assertNotEqual(Tuple[int], Tuple[int, int]) self.assertNotEqual(Tuple[int], Tuple[int, ...]) def test_tuple_subclass(self): class MyTuple(tuple): pass self.assertIsSubclass(MyTuple, Tuple) def test_tuple_instance_type_error(self): with self.assertRaises(TypeError): isinstance((0, 0), Tuple[int, int]) self.assertIsInstance((0, 0), Tuple) def test_repr(self): self.assertEqual(repr(Tuple), 'typing.Tuple') self.assertEqual(repr(Tuple[()]), 'typing.Tuple[()]') self.assertEqual(repr(Tuple[int, float]), 'typing.Tuple[int, float]') self.assertEqual(repr(Tuple[int, ...]), 'typing.Tuple[int, ...]') self.assertEqual(repr(Tuple[list[int]]), 'typing.Tuple[list[int]]') def test_errors(self): with self.assertRaises(TypeError): issubclass(42, Tuple) with self.assertRaises(TypeError): issubclass(42, Tuple[int]) class BaseCallableTests: def test_self_subclass(self): Callable = self.Callable with self.assertRaises(TypeError): issubclass(types.FunctionType, Callable[[int], int]) self.assertIsSubclass(types.FunctionType, Callable) def test_eq_hash(self): Callable = self.Callable C = Callable[[int], int] self.assertEqual(C, Callable[[int], int]) self.assertEqual(len({C, Callable[[int], int]}), 1) self.assertNotEqual(C, Callable[[int], str]) self.assertNotEqual(C, Callable[[str], int]) self.assertNotEqual(C, Callable[[int, int], int]) self.assertNotEqual(C, Callable[[], int]) self.assertNotEqual(C, Callable[..., int]) self.assertNotEqual(C, Callable) def test_cannot_instantiate(self): Callable = self.Callable with self.assertRaises(TypeError): Callable() with self.assertRaises(TypeError): type(Callable)() c = Callable[[int], str] with self.assertRaises(TypeError): c() with self.assertRaises(TypeError): type(c)() def test_callable_wrong_forms(self): Callable = self.Callable with self.assertRaises(TypeError): Callable[int] def test_callable_instance_works(self): Callable = self.Callable def f(): pass self.assertIsInstance(f, Callable) self.assertNotIsInstance(None, Callable) def test_callable_instance_type_error(self): Callable = self.Callable def f(): pass with self.assertRaises(TypeError): self.assertIsInstance(f, Callable[[], None]) with self.assertRaises(TypeError): self.assertIsInstance(f, Callable[[], Any]) with self.assertRaises(TypeError): self.assertNotIsInstance(None, Callable[[], None]) with self.assertRaises(TypeError): self.assertNotIsInstance(None, Callable[[], Any]) def test_repr(self): Callable = self.Callable fullname = f'{Callable.__module__}.Callable' ct0 = Callable[[], bool] self.assertEqual(repr(ct0), f'{fullname}[[], bool]') ct2 = Callable[[str, float], int] self.assertEqual(repr(ct2), f'{fullname}[[str, float], int]') ctv = Callable[..., str] self.assertEqual(repr(ctv), f'{fullname}[..., str]') ct3 = Callable[[str, float], list[int]] self.assertEqual(repr(ct3), f'{fullname}[[str, float], list[int]]') def test_callable_with_ellipsis(self): Callable = self.Callable def foo(a: Callable[..., T]): pass self.assertEqual(get_type_hints(foo, globals(), locals()), {'a': Callable[..., T]}) def test_ellipsis_in_generic(self): Callable = self.Callable # Shouldn't crash; see https://github.com/python/typing/issues/259 typing.List[Callable[..., str]] def test_basic(self): Callable = self.Callable alias = Callable[[int, str], float] if Callable is collections.abc.Callable: self.assertIsInstance(alias, types.GenericAlias) self.assertIs(alias.__origin__, collections.abc.Callable) self.assertEqual(alias.__args__, (int, str, float)) self.assertEqual(alias.__parameters__, ()) def test_weakref(self): Callable = self.Callable alias = Callable[[int, str], float] self.assertEqual(weakref.ref(alias)(), alias) def test_pickle(self): Callable = self.Callable alias = Callable[[int, str], float] for proto in range(pickle.HIGHEST_PROTOCOL + 1): s = pickle.dumps(alias, proto) loaded = pickle.loads(s) self.assertEqual(alias.__origin__, loaded.__origin__) self.assertEqual(alias.__args__, loaded.__args__) self.assertEqual(alias.__parameters__, loaded.__parameters__) def test_var_substitution(self): Callable = self.Callable fullname = f"{Callable.__module__}.Callable" C1 = Callable[[int, T], T] C2 = Callable[[KT, T], VT] C3 = Callable[..., T] self.assertEqual(C1[str], Callable[[int, str], str]) self.assertEqual(C2[int, float, str], Callable[[int, float], str]) self.assertEqual(C3[int], Callable[..., int]) # multi chaining C4 = C2[int, VT, str] self.assertEqual(repr(C4), f"{fullname}[[int, ~VT], str]") self.assertEqual(repr(C4[dict]), f"{fullname}[[int, dict], str]") self.assertEqual(C4[dict], Callable[[int, dict], str]) # substitute a nested GenericAlias (both typing and the builtin # version) C5 = Callable[[typing.List[T], tuple[KT, T], VT], int] self.assertEqual(C5[int, str, float], Callable[[typing.List[int], tuple[str, int], float], int]) def test_type_erasure(self): Callable = self.Callable class C1(Callable): def __call__(self): return None a = C1[[int], T] self.assertIs(a().__class__, C1) self.assertEqual(a().__orig_class__, C1[[int], T]) def test_paramspec(self): Callable = self.Callable fullname = f"{Callable.__module__}.Callable" P = ParamSpec('P') P2 = ParamSpec('P2') C1 = Callable[P, T] # substitution self.assertEqual(C1[[int], str], Callable[[int], str]) self.assertEqual(C1[[int, str], str], Callable[[int, str], str]) self.assertEqual(C1[[], str], Callable[[], str]) self.assertEqual(C1[..., str], Callable[..., str]) self.assertEqual(C1[P2, str], Callable[P2, str]) self.assertEqual(C1[Concatenate[int, P2], str], Callable[Concatenate[int, P2], str]) self.assertEqual(repr(C1), f"{fullname}[~P, ~T]") self.assertEqual(repr(C1[[int, str], str]), f"{fullname}[[int, str], str]") with self.assertRaises(TypeError): C1[int, str] C2 = Callable[P, int] self.assertEqual(C2[[int]], Callable[[int], int]) self.assertEqual(C2[[int, str]], Callable[[int, str], int]) self.assertEqual(C2[[]], Callable[[], int]) self.assertEqual(C2[...], Callable[..., int]) self.assertEqual(C2[P2], Callable[P2, int]) self.assertEqual(C2[Concatenate[int, P2]], Callable[Concatenate[int, P2], int]) # special case in PEP 612 where # X[int, str, float] == X[[int, str, float]] self.assertEqual(C2[int], Callable[[int], int]) self.assertEqual(C2[int, str], Callable[[int, str], int]) self.assertEqual(repr(C2), f"{fullname}[~P, int]") self.assertEqual(repr(C2[int, str]), f"{fullname}[[int, str], int]") def test_concatenate(self): Callable = self.Callable fullname = f"{Callable.__module__}.Callable" P = ParamSpec('P') C1 = Callable[typing.Concatenate[int, P], int] self.assertEqual(repr(C1), f"{fullname}[typing.Concatenate[int, ~P], int]") def test_errors(self): Callable = self.Callable alias = Callable[[int, str], float] with self.assertRaisesRegex(TypeError, "is not a generic class"): alias[int] P = ParamSpec('P') C1 = Callable[P, T] with self.assertRaisesRegex(TypeError, "many arguments for"): C1[int, str, str] with self.assertRaisesRegex(TypeError, "few arguments for"): C1[int] class TypingCallableTests(BaseCallableTests, BaseTestCase): Callable = typing.Callable def test_consistency(self): # bpo-42195 # Testing collections.abc.Callable's consistency with typing.Callable c1 = typing.Callable[[int, str], dict] c2 = collections.abc.Callable[[int, str], dict] self.assertEqual(c1.__args__, c2.__args__) self.assertEqual(hash(c1.__args__), hash(c2.__args__)) class CollectionsCallableTests(BaseCallableTests, BaseTestCase): Callable = collections.abc.Callable class LiteralTests(BaseTestCase): def test_basics(self): # All of these are allowed. Literal[1] Literal[1, 2, 3] Literal["x", "y", "z"] Literal[None] Literal[True] Literal[1, "2", False] Literal[Literal[1, 2], Literal[4, 5]] Literal[b"foo", u"bar"] def test_illegal_parameters_do_not_raise_runtime_errors(self): # Type checkers should reject these types, but we do not # raise errors at runtime to maintain maximum flexibility. Literal[int] Literal[3j + 2, ..., ()] Literal[{"foo": 3, "bar": 4}] Literal[T] def test_literals_inside_other_types(self): List[Literal[1, 2, 3]] List[Literal[("foo", "bar", "baz")]] def test_repr(self): self.assertEqual(repr(Literal[1]), "typing.Literal[1]") self.assertEqual(repr(Literal[1, True, "foo"]), "typing.Literal[1, True, 'foo']") self.assertEqual(repr(Literal[int]), "typing.Literal[int]") self.assertEqual(repr(Literal), "typing.Literal") self.assertEqual(repr(Literal[None]), "typing.Literal[None]") self.assertEqual(repr(Literal[1, 2, 3, 3]), "typing.Literal[1, 2, 3]") def test_cannot_init(self): with self.assertRaises(TypeError): Literal() with self.assertRaises(TypeError): Literal[1]() with self.assertRaises(TypeError): type(Literal)() with self.assertRaises(TypeError): type(Literal[1])() def test_no_isinstance_or_issubclass(self): with self.assertRaises(TypeError): isinstance(1, Literal[1]) with self.assertRaises(TypeError): isinstance(int, Literal[1]) with self.assertRaises(TypeError): issubclass(1, Literal[1]) with self.assertRaises(TypeError): issubclass(int, Literal[1]) def test_no_subclassing(self): with self.assertRaises(TypeError): class Foo(Literal[1]): pass with self.assertRaises(TypeError): class Bar(Literal): pass def test_no_multiple_subscripts(self): with self.assertRaises(TypeError): Literal[1][1] def test_equal(self): self.assertNotEqual(Literal[0], Literal[False]) self.assertNotEqual(Literal[True], Literal[1]) self.assertNotEqual(Literal[1], Literal[2]) self.assertNotEqual(Literal[1, True], Literal[1]) self.assertEqual(Literal[1], Literal[1]) self.assertEqual(Literal[1, 2], Literal[2, 1]) self.assertEqual(Literal[1, 2, 3], Literal[1, 2, 3, 3]) def test_hash(self): self.assertEqual(hash(Literal[1]), hash(Literal[1])) self.assertEqual(hash(Literal[1, 2]), hash(Literal[2, 1])) self.assertEqual(hash(Literal[1, 2, 3]), hash(Literal[1, 2, 3, 3])) def test_args(self): self.assertEqual(Literal[1, 2, 3].__args__, (1, 2, 3)) self.assertEqual(Literal[1, 2, 3, 3].__args__, (1, 2, 3)) self.assertEqual(Literal[1, Literal[2], Literal[3, 4]].__args__, (1, 2, 3, 4)) # Mutable arguments will not be deduplicated self.assertEqual(Literal[[], []].__args__, ([], [])) def test_flatten(self): l1 = Literal[Literal[1], Literal[2], Literal[3]] l2 = Literal[Literal[1, 2], 3] l3 = Literal[Literal[1, 2, 3]] for l in l1, l2, l3: self.assertEqual(l, Literal[1, 2, 3]) self.assertEqual(l.__args__, (1, 2, 3)) XK = TypeVar('XK', str, bytes) XV = TypeVar('XV') class SimpleMapping(Generic[XK, XV]): def __getitem__(self, key: XK) -> XV: ... def __setitem__(self, key: XK, value: XV): ... def get(self, key: XK, default: XV = None) -> XV: ... class MySimpleMapping(SimpleMapping[XK, XV]): def __init__(self): self.store = {} def __getitem__(self, key: str): return self.store[key] def __setitem__(self, key: str, value): self.store[key] = value def get(self, key: str, default=None): try: return self.store[key] except KeyError: return default class Coordinate(Protocol): x: int y: int @runtime_checkable class Point(Coordinate, Protocol): label: str class MyPoint: x: int y: int label: str class XAxis(Protocol): x: int class YAxis(Protocol): y: int @runtime_checkable class Position(XAxis, YAxis, Protocol): pass @runtime_checkable class Proto(Protocol): attr: int def meth(self, arg: str) -> int: ... class Concrete(Proto): pass class Other: attr: int = 1 def meth(self, arg: str) -> int: if arg == 'this': return 1 return 0 class NT(NamedTuple): x: int y: int @runtime_checkable class HasCallProtocol(Protocol): __call__: typing.Callable class ProtocolTests(BaseTestCase): def test_basic_protocol(self): @runtime_checkable class P(Protocol): def meth(self): pass class C: pass class D: def meth(self): pass def f(): pass self.assertIsSubclass(D, P) self.assertIsInstance(D(), P) self.assertNotIsSubclass(C, P) self.assertNotIsInstance(C(), P) self.assertNotIsSubclass(types.FunctionType, P) self.assertNotIsInstance(f, P) def test_everything_implements_empty_protocol(self): @runtime_checkable class Empty(Protocol): pass class C: pass def f(): pass for thing in (object, type, tuple, C, types.FunctionType): self.assertIsSubclass(thing, Empty) for thing in (object(), 1, (), typing, f): self.assertIsInstance(thing, Empty) def test_function_implements_protocol(self): def f(): pass self.assertIsInstance(f, HasCallProtocol) def test_no_inheritance_from_nominal(self): class C: pass class BP(Protocol): pass with self.assertRaises(TypeError): class P(C, Protocol): pass with self.assertRaises(TypeError): class P(Protocol, C): pass with self.assertRaises(TypeError): class P(BP, C, Protocol): pass class D(BP, C): pass class E(C, BP): pass self.assertNotIsInstance(D(), E) self.assertNotIsInstance(E(), D) def test_no_instantiation(self): class P(Protocol): pass with self.assertRaises(TypeError): P() class C(P): pass self.assertIsInstance(C(), C) with self.assertRaises(TypeError): C(42) T = TypeVar('T') class PG(Protocol[T]): pass with self.assertRaises(TypeError): PG() with self.assertRaises(TypeError): PG[int]() with self.assertRaises(TypeError): PG[T]() class CG(PG[T]): pass self.assertIsInstance(CG[int](), CG) with self.assertRaises(TypeError): CG[int](42) def test_cannot_instantiate_abstract(self): @runtime_checkable class P(Protocol): @abc.abstractmethod def ameth(self) -> int: raise NotImplementedError class B(P): pass class C(B): def ameth(self) -> int: return 26 with self.assertRaises(TypeError): B() self.assertIsInstance(C(), P) def test_subprotocols_extending(self): class P1(Protocol): def meth1(self): pass @runtime_checkable class P2(P1, Protocol): def meth2(self): pass class C: def meth1(self): pass def meth2(self): pass class C1: def meth1(self): pass class C2: def meth2(self): pass self.assertNotIsInstance(C1(), P2) self.assertNotIsInstance(C2(), P2) self.assertNotIsSubclass(C1, P2) self.assertNotIsSubclass(C2, P2) self.assertIsInstance(C(), P2) self.assertIsSubclass(C, P2) def test_subprotocols_merging(self): class P1(Protocol): def meth1(self): pass class P2(Protocol): def meth2(self): pass @runtime_checkable class P(P1, P2, Protocol): pass class C: def meth1(self): pass def meth2(self): pass class C1: def meth1(self): pass class C2: def meth2(self): pass self.assertNotIsInstance(C1(), P) self.assertNotIsInstance(C2(), P) self.assertNotIsSubclass(C1, P) self.assertNotIsSubclass(C2, P) self.assertIsInstance(C(), P) self.assertIsSubclass(C, P) def test_protocols_issubclass(self): T = TypeVar('T') @runtime_checkable class P(Protocol): def x(self): ... @runtime_checkable class PG(Protocol[T]): def x(self): ... class BadP(Protocol): def x(self): ... class BadPG(Protocol[T]): def x(self): ... class C: def x(self): ... self.assertIsSubclass(C, P) self.assertIsSubclass(C, PG) self.assertIsSubclass(BadP, PG) with self.assertRaises(TypeError): issubclass(C, PG[T]) with self.assertRaises(TypeError): issubclass(C, PG[C]) with self.assertRaises(TypeError): issubclass(C, BadP) with self.assertRaises(TypeError): issubclass(C, BadPG) with self.assertRaises(TypeError): issubclass(P, PG[T]) with self.assertRaises(TypeError): issubclass(PG, PG[int]) def test_protocols_issubclass_non_callable(self): class C: x = 1 @runtime_checkable class PNonCall(Protocol): x = 1 with self.assertRaises(TypeError): issubclass(C, PNonCall) self.assertIsInstance(C(), PNonCall) PNonCall.register(C) with self.assertRaises(TypeError): issubclass(C, PNonCall) self.assertIsInstance(C(), PNonCall) # check that non-protocol subclasses are not affected class D(PNonCall): ... self.assertNotIsSubclass(C, D) self.assertNotIsInstance(C(), D) D.register(C) self.assertIsSubclass(C, D) self.assertIsInstance(C(), D) with self.assertRaises(TypeError): issubclass(D, PNonCall) def test_protocols_isinstance(self): T = TypeVar('T') @runtime_checkable class P(Protocol): def meth(x): ... @runtime_checkable class PG(Protocol[T]): def meth(x): ... class BadP(Protocol): def meth(x): ... class BadPG(Protocol[T]): def meth(x): ... class C: def meth(x): ... self.assertIsInstance(C(), P) self.assertIsInstance(C(), PG) with self.assertRaises(TypeError): isinstance(C(), PG[T]) with self.assertRaises(TypeError): isinstance(C(), PG[C]) with self.assertRaises(TypeError): isinstance(C(), BadP) with self.assertRaises(TypeError): isinstance(C(), BadPG) def test_protocols_isinstance_py36(self): class APoint: def __init__(self, x, y, label): self.x = x self.y = y self.label = label class BPoint: label = 'B' def __init__(self, x, y): self.x = x self.y = y class C: def __init__(self, attr): self.attr = attr def meth(self, arg): return 0 class Bad: pass self.assertIsInstance(APoint(1, 2, 'A'), Point) self.assertIsInstance(BPoint(1, 2), Point) self.assertNotIsInstance(MyPoint(), Point) self.assertIsInstance(BPoint(1, 2), Position) self.assertIsInstance(Other(), Proto) self.assertIsInstance(Concrete(), Proto) self.assertIsInstance(C(42), Proto) self.assertNotIsInstance(Bad(), Proto) self.assertNotIsInstance(Bad(), Point) self.assertNotIsInstance(Bad(), Position) self.assertNotIsInstance(Bad(), Concrete) self.assertNotIsInstance(Other(), Concrete) self.assertIsInstance(NT(1, 2), Position) def test_protocols_isinstance_init(self): T = TypeVar('T') @runtime_checkable class P(Protocol): x = 1 @runtime_checkable class PG(Protocol[T]): x = 1 class C: def __init__(self, x): self.x = x self.assertIsInstance(C(1), P) self.assertIsInstance(C(1), PG) def test_protocol_checks_after_subscript(self): class P(Protocol[T]): pass class C(P[T]): pass class Other1: pass class Other2: pass CA = C[Any] self.assertNotIsInstance(Other1(), C) self.assertNotIsSubclass(Other2, C) class D1(C[Any]): pass class D2(C[Any]): pass CI = C[int] self.assertIsInstance(D1(), C) self.assertIsSubclass(D2, C) def test_protocols_support_register(self): @runtime_checkable class P(Protocol): x = 1 class PM(Protocol): def meth(self): pass class D(PM): pass class C: pass D.register(C) P.register(C) self.assertIsInstance(C(), P) self.assertIsInstance(C(), D) def test_none_on_non_callable_doesnt_block_implementation(self): @runtime_checkable class P(Protocol): x = 1 class A: x = 1 class B(A): x = None class C: def __init__(self): self.x = None self.assertIsInstance(B(), P) self.assertIsInstance(C(), P) def test_none_on_callable_blocks_implementation(self): @runtime_checkable class P(Protocol): def x(self): ... class A: def x(self): ... class B(A): x = None class C: def __init__(self): self.x = None self.assertNotIsInstance(B(), P) self.assertNotIsInstance(C(), P) def test_non_protocol_subclasses(self): class P(Protocol): x = 1 @runtime_checkable class PR(Protocol): def meth(self): pass class NonP(P): x = 1 class NonPR(PR): pass class C: x = 1 class D: def meth(self): pass self.assertNotIsInstance(C(), NonP) self.assertNotIsInstance(D(), NonPR) self.assertNotIsSubclass(C, NonP) self.assertNotIsSubclass(D, NonPR) self.assertIsInstance(NonPR(), PR) self.assertIsSubclass(NonPR, PR) def test_custom_subclasshook(self): class P(Protocol): x = 1 class OKClass: pass class BadClass: x = 1 class C(P): @classmethod def __subclasshook__(cls, other): return other.__name__.startswith("OK") self.assertIsInstance(OKClass(), C) self.assertNotIsInstance(BadClass(), C) self.assertIsSubclass(OKClass, C) self.assertNotIsSubclass(BadClass, C) def test_issubclass_fails_correctly(self): @runtime_checkable class P(Protocol): x = 1 class C: pass with self.assertRaises(TypeError): issubclass(C(), P) def test_defining_generic_protocols(self): T = TypeVar('T') S = TypeVar('S') @runtime_checkable class PR(Protocol[T, S]): def meth(self): pass class P(PR[int, T], Protocol[T]): y = 1 with self.assertRaises(TypeError): PR[int] with self.assertRaises(TypeError): P[int, str] class C(PR[int, T]): pass self.assertIsInstance(C[str](), C) def test_defining_generic_protocols_old_style(self): T = TypeVar('T') S = TypeVar('S') @runtime_checkable class PR(Protocol, Generic[T, S]): def meth(self): pass class P(PR[int, str], Protocol): y = 1 with self.assertRaises(TypeError): issubclass(PR[int, str], PR) self.assertIsSubclass(P, PR) with self.assertRaises(TypeError): PR[int] class P1(Protocol, Generic[T]): def bar(self, x: T) -> str: ... class P2(Generic[T], Protocol): def bar(self, x: T) -> str: ... @runtime_checkable class PSub(P1[str], Protocol): x = 1 class Test: x = 1 def bar(self, x: str) -> str: return x self.assertIsInstance(Test(), PSub) def test_init_called(self): T = TypeVar('T') class P(Protocol[T]): pass class C(P[T]): def __init__(self): self.test = 'OK' self.assertEqual(C[int]().test, 'OK') class B: def __init__(self): self.test = 'OK' class D1(B, P[T]): pass self.assertEqual(D1[int]().test, 'OK') class D2(P[T], B): pass self.assertEqual(D2[int]().test, 'OK') def test_new_called(self): T = TypeVar('T') class P(Protocol[T]): pass class C(P[T]): def __new__(cls, *args): self = super().__new__(cls, *args) self.test = 'OK' return self self.assertEqual(C[int]().test, 'OK') with self.assertRaises(TypeError): C[int](42) with self.assertRaises(TypeError): C[int](a=42) def test_protocols_bad_subscripts(self): T = TypeVar('T') S = TypeVar('S') with self.assertRaises(TypeError): class P(Protocol[T, T]): pass with self.assertRaises(TypeError): class P(Protocol[int]): pass with self.assertRaises(TypeError): class P(Protocol[T], Protocol[S]): pass with self.assertRaises(TypeError): class P(typing.Mapping[T, S], Protocol[T]): pass def test_generic_protocols_repr(self): T = TypeVar('T') S = TypeVar('S') class P(Protocol[T, S]): pass self.assertTrue(repr(P[T, S]).endswith('P[~T, ~S]')) self.assertTrue(repr(P[int, str]).endswith('P[int, str]')) def test_generic_protocols_eq(self): T = TypeVar('T') S = TypeVar('S') class P(Protocol[T, S]): pass self.assertEqual(P, P) self.assertEqual(P[int, T], P[int, T]) self.assertEqual(P[T, T][Tuple[T, S]][int, str], P[Tuple[int, str], Tuple[int, str]]) def test_generic_protocols_special_from_generic(self): T = TypeVar('T') class P(Protocol[T]): pass self.assertEqual(P.__parameters__, (T,)) self.assertEqual(P[int].__parameters__, ()) self.assertEqual(P[int].__args__, (int,)) self.assertIs(P[int].__origin__, P) def test_generic_protocols_special_from_protocol(self): @runtime_checkable class PR(Protocol): x = 1 class P(Protocol): def meth(self): pass T = TypeVar('T') class PG(Protocol[T]): x = 1 def meth(self): pass self.assertTrue(P._is_protocol) self.assertTrue(PR._is_protocol) self.assertTrue(PG._is_protocol) self.assertFalse(P._is_runtime_protocol) self.assertTrue(PR._is_runtime_protocol) self.assertTrue(PG[int]._is_protocol) self.assertEqual(typing._get_protocol_attrs(P), {'meth'}) self.assertEqual(typing._get_protocol_attrs(PR), {'x'}) self.assertEqual(frozenset(typing._get_protocol_attrs(PG)), frozenset({'x', 'meth'})) def test_no_runtime_deco_on_nominal(self): with self.assertRaises(TypeError): @runtime_checkable class C: pass class Proto(Protocol): x = 1 with self.assertRaises(TypeError): @runtime_checkable class Concrete(Proto): pass def test_none_treated_correctly(self): @runtime_checkable class P(Protocol): x = None # type: int class B(object): pass self.assertNotIsInstance(B(), P) class C: x = 1 class D: x = None self.assertIsInstance(C(), P) self.assertIsInstance(D(), P) class CI: def __init__(self): self.x = 1 class DI: def __init__(self): self.x = None self.assertIsInstance(C(), P) self.assertIsInstance(D(), P) def test_protocols_in_unions(self): class P(Protocol): x = None # type: int Alias = typing.Union[typing.Iterable, P] Alias2 = typing.Union[P, typing.Iterable] self.assertEqual(Alias, Alias2) def test_protocols_pickleable(self): global P, CP # pickle wants to reference the class by name T = TypeVar('T') @runtime_checkable class P(Protocol[T]): x = 1 class CP(P[int]): pass c = CP() c.foo = 42 c.bar = 'abc' for proto in range(pickle.HIGHEST_PROTOCOL + 1): z = pickle.dumps(c, proto) x = pickle.loads(z) self.assertEqual(x.foo, 42) self.assertEqual(x.bar, 'abc') self.assertEqual(x.x, 1) self.assertEqual(x.__dict__, {'foo': 42, 'bar': 'abc'}) s = pickle.dumps(P) D = pickle.loads(s) class E: x = 1 self.assertIsInstance(E(), D) def test_supports_int(self): self.assertIsSubclass(int, typing.SupportsInt) self.assertNotIsSubclass(str, typing.SupportsInt) def test_supports_float(self): self.assertIsSubclass(float, typing.SupportsFloat) self.assertNotIsSubclass(str, typing.SupportsFloat) def test_supports_complex(self): class C: def __complex__(self): return 0j self.assertIsSubclass(complex, typing.SupportsComplex) self.assertIsSubclass(C, typing.SupportsComplex) self.assertNotIsSubclass(str, typing.SupportsComplex) def test_supports_bytes(self): class B: def __bytes__(self): return b'' self.assertIsSubclass(bytes, typing.SupportsBytes) self.assertIsSubclass(B, typing.SupportsBytes) self.assertNotIsSubclass(str, typing.SupportsBytes) def test_supports_abs(self): self.assertIsSubclass(float, typing.SupportsAbs) self.assertIsSubclass(int, typing.SupportsAbs) self.assertNotIsSubclass(str, typing.SupportsAbs) def test_supports_round(self): issubclass(float, typing.SupportsRound) self.assertIsSubclass(float, typing.SupportsRound) self.assertIsSubclass(int, typing.SupportsRound) self.assertNotIsSubclass(str, typing.SupportsRound) def test_reversible(self): self.assertIsSubclass(list, typing.Reversible) self.assertNotIsSubclass(int, typing.Reversible) def test_supports_index(self): self.assertIsSubclass(int, typing.SupportsIndex) self.assertNotIsSubclass(str, typing.SupportsIndex) def test_bundled_protocol_instance_works(self): self.assertIsInstance(0, typing.SupportsAbs) class C1(typing.SupportsInt): def __int__(self) -> int: return 42 class C2(C1): pass c = C2() self.assertIsInstance(c, C1) def test_collections_protocols_allowed(self): @runtime_checkable class Custom(collections.abc.Iterable, Protocol): def close(self): ... class A: pass class B: def __iter__(self): return [] def close(self): return 0 self.assertIsSubclass(B, Custom) self.assertNotIsSubclass(A, Custom) def test_builtin_protocol_allowlist(self): with self.assertRaises(TypeError): class CustomProtocol(TestCase, Protocol): pass class CustomContextManager(typing.ContextManager, Protocol): pass def test_non_runtime_protocol_isinstance_check(self): class P(Protocol): x: int with self.assertRaisesRegex(TypeError, "@runtime_checkable"): isinstance(1, P) def test_super_call_init(self): class P(Protocol): x: int class Foo(P): def __init__(self): super().__init__() Foo() # Previously triggered RecursionError class GenericTests(BaseTestCase): def test_basics(self): X = SimpleMapping[str, Any] self.assertEqual(X.__parameters__, ()) with self.assertRaises(TypeError): X[str] with self.assertRaises(TypeError): X[str, str] Y = SimpleMapping[XK, str] self.assertEqual(Y.__parameters__, (XK,)) Y[str] with self.assertRaises(TypeError): Y[str, str] SM1 = SimpleMapping[str, int] with self.assertRaises(TypeError): issubclass(SM1, SimpleMapping) self.assertIsInstance(SM1(), SimpleMapping) T = TypeVar("T") self.assertEqual(List[list[T] | float].__parameters__, (T,)) def test_generic_errors(self): T = TypeVar('T') S = TypeVar('S') with self.assertRaises(TypeError): Generic[T][T] with self.assertRaises(TypeError): Generic[T][S] with self.assertRaises(TypeError): class C(Generic[T], Generic[T]): ... with self.assertRaises(TypeError): isinstance([], List[int]) with self.assertRaises(TypeError): issubclass(list, List[int]) with self.assertRaises(TypeError): class NewGeneric(Generic): ... with self.assertRaises(TypeError): class MyGeneric(Generic[T], Generic[S]): ... with self.assertRaises(TypeError): class MyGeneric(List[T], Generic[S]): ... def test_init(self): T = TypeVar('T') S = TypeVar('S') with self.assertRaises(TypeError): Generic[T, T] with self.assertRaises(TypeError): Generic[T, S, T] def test_init_subclass(self): class X(typing.Generic[T]): def __init_subclass__(cls, **kwargs): super().__init_subclass__(**kwargs) cls.attr = 42 class Y(X): pass self.assertEqual(Y.attr, 42) with self.assertRaises(AttributeError): X.attr X.attr = 1 Y.attr = 2 class Z(Y): pass class W(X[int]): pass self.assertEqual(Y.attr, 2) self.assertEqual(Z.attr, 42) self.assertEqual(W.attr, 42) def test_repr(self): self.assertEqual(repr(SimpleMapping), f"<class '{__name__}.SimpleMapping'>") self.assertEqual(repr(MySimpleMapping), f"<class '{__name__}.MySimpleMapping'>") def test_chain_repr(self): T = TypeVar('T') S = TypeVar('S') class C(Generic[T]): pass X = C[Tuple[S, T]] self.assertEqual(X, C[Tuple[S, T]]) self.assertNotEqual(X, C[Tuple[T, S]]) Y = X[T, int] self.assertEqual(Y, X[T, int]) self.assertNotEqual(Y, X[S, int]) self.assertNotEqual(Y, X[T, str]) Z = Y[str] self.assertEqual(Z, Y[str]) self.assertNotEqual(Z, Y[int]) self.assertNotEqual(Z, Y[T]) self.assertTrue(str(Z).endswith( '.C[typing.Tuple[str, int]]')) def test_new_repr(self): T = TypeVar('T') U = TypeVar('U', covariant=True) S = TypeVar('S') self.assertEqual(repr(List), 'typing.List') self.assertEqual(repr(List[T]), 'typing.List[~T]') self.assertEqual(repr(List[U]), 'typing.List[+U]') self.assertEqual(repr(List[S][T][int]), 'typing.List[int]') self.assertEqual(repr(List[int]), 'typing.List[int]') def test_new_repr_complex(self): T = TypeVar('T') TS = TypeVar('TS') self.assertEqual(repr(typing.Mapping[T, TS][TS, T]), 'typing.Mapping[~TS, ~T]') self.assertEqual(repr(List[Tuple[T, TS]][int, T]), 'typing.List[typing.Tuple[int, ~T]]') self.assertEqual( repr(List[Tuple[T, T]][List[int]]), 'typing.List[typing.Tuple[typing.List[int], typing.List[int]]]' ) def test_new_repr_bare(self): T = TypeVar('T') self.assertEqual(repr(Generic[T]), 'typing.Generic[~T]') self.assertEqual(repr(typing.Protocol[T]), 'typing.Protocol[~T]') class C(typing.Dict[Any, Any]): ... # this line should just work repr(C.__mro__) def test_dict(self): T = TypeVar('T') class B(Generic[T]): pass b = B() b.foo = 42 self.assertEqual(b.__dict__, {'foo': 42}) class C(B[int]): pass c = C() c.bar = 'abc' self.assertEqual(c.__dict__, {'bar': 'abc'}) def test_subscripted_generics_as_proxies(self): T = TypeVar('T') class C(Generic[T]): x = 'def' self.assertEqual(C[int].x, 'def') self.assertEqual(C[C[int]].x, 'def') C[C[int]].x = 'changed' self.assertEqual(C.x, 'changed') self.assertEqual(C[str].x, 'changed') C[List[str]].z = 'new' self.assertEqual(C.z, 'new') self.assertEqual(C[Tuple[int]].z, 'new') self.assertEqual(C().x, 'changed') self.assertEqual(C[Tuple[str]]().z, 'new') class D(C[T]): pass self.assertEqual(D[int].x, 'changed') self.assertEqual(D.z, 'new') D.z = 'from derived z' D[int].x = 'from derived x' self.assertEqual(C.x, 'changed') self.assertEqual(C[int].z, 'new') self.assertEqual(D.x, 'from derived x') self.assertEqual(D[str].z, 'from derived z') def test_abc_registry_kept(self): T = TypeVar('T') class C(collections.abc.Mapping, Generic[T]): ... C.register(int) self.assertIsInstance(1, C) C[int] self.assertIsInstance(1, C) C._abc_registry_clear() C._abc_caches_clear() # To keep refleak hunting mode clean def test_false_subclasses(self): class MyMapping(MutableMapping[str, str]): pass self.assertNotIsInstance({}, MyMapping) self.assertNotIsSubclass(dict, MyMapping) def test_abc_bases(self): class MM(MutableMapping[str, str]): def __getitem__(self, k): return None def __setitem__(self, k, v): pass def __delitem__(self, k): pass def __iter__(self): return iter(()) def __len__(self): return 0 # this should just work MM().update() self.assertIsInstance(MM(), collections.abc.MutableMapping) self.assertIsInstance(MM(), MutableMapping) self.assertNotIsInstance(MM(), List) self.assertNotIsInstance({}, MM) def test_multiple_bases(self): class MM1(MutableMapping[str, str], collections.abc.MutableMapping): pass class MM2(collections.abc.MutableMapping, MutableMapping[str, str]): pass self.assertEqual(MM2.__bases__, (collections.abc.MutableMapping, Generic)) def test_orig_bases(self): T = TypeVar('T') class C(typing.Dict[str, T]): ... self.assertEqual(C.__orig_bases__, (typing.Dict[str, T],)) def test_naive_runtime_checks(self): def naive_dict_check(obj, tp): # Check if a dictionary conforms to Dict type if len(tp.__parameters__) > 0: raise NotImplementedError if tp.__args__: KT, VT = tp.__args__ return all( isinstance(k, KT) and isinstance(v, VT) for k, v in obj.items() ) self.assertTrue(naive_dict_check({'x': 1}, typing.Dict[str, int])) self.assertFalse(naive_dict_check({1: 'x'}, typing.Dict[str, int])) with self.assertRaises(NotImplementedError): naive_dict_check({1: 'x'}, typing.Dict[str, T]) def naive_generic_check(obj, tp): # Check if an instance conforms to the generic class if not hasattr(obj, '__orig_class__'): raise NotImplementedError return obj.__orig_class__ == tp class Node(Generic[T]): ... self.assertTrue(naive_generic_check(Node[int](), Node[int])) self.assertFalse(naive_generic_check(Node[str](), Node[int])) self.assertFalse(naive_generic_check(Node[str](), List)) with self.assertRaises(NotImplementedError): naive_generic_check([1, 2, 3], Node[int]) def naive_list_base_check(obj, tp): # Check if list conforms to a List subclass return all(isinstance(x, tp.__orig_bases__[0].__args__[0]) for x in obj) class C(List[int]): ... self.assertTrue(naive_list_base_check([1, 2, 3], C)) self.assertFalse(naive_list_base_check(['a', 'b'], C)) def test_multi_subscr_base(self): T = TypeVar('T') U = TypeVar('U') V = TypeVar('V') class C(List[T][U][V]): ... class D(C, List[T][U][V]): ... self.assertEqual(C.__parameters__, (V,)) self.assertEqual(D.__parameters__, (V,)) self.assertEqual(C[int].__parameters__, ()) self.assertEqual(D[int].__parameters__, ()) self.assertEqual(C[int].__args__, (int,)) self.assertEqual(D[int].__args__, (int,)) self.assertEqual(C.__bases__, (list, Generic)) self.assertEqual(D.__bases__, (C, list, Generic)) self.assertEqual(C.__orig_bases__, (List[T][U][V],)) self.assertEqual(D.__orig_bases__, (C, List[T][U][V])) def test_subscript_meta(self): T = TypeVar('T') class Meta(type): ... self.assertEqual(Type[Meta], Type[Meta]) self.assertEqual(Union[T, int][Meta], Union[Meta, int]) self.assertEqual(Callable[..., Meta].__args__, (Ellipsis, Meta)) def test_generic_hashes(self): class A(Generic[T]): ... class B(Generic[T]): class A(Generic[T]): ... self.assertEqual(A, A) self.assertEqual(mod_generics_cache.A[str], mod_generics_cache.A[str]) self.assertEqual(B.A, B.A) self.assertEqual(mod_generics_cache.B.A[B.A[str]], mod_generics_cache.B.A[B.A[str]]) self.assertNotEqual(A, B.A) self.assertNotEqual(A, mod_generics_cache.A) self.assertNotEqual(A, mod_generics_cache.B.A) self.assertNotEqual(B.A, mod_generics_cache.A) self.assertNotEqual(B.A, mod_generics_cache.B.A) self.assertNotEqual(A[str], B.A[str]) self.assertNotEqual(A[List[Any]], B.A[List[Any]]) self.assertNotEqual(A[str], mod_generics_cache.A[str]) self.assertNotEqual(A[str], mod_generics_cache.B.A[str]) self.assertNotEqual(B.A[int], mod_generics_cache.A[int]) self.assertNotEqual(B.A[List[Any]], mod_generics_cache.B.A[List[Any]]) self.assertNotEqual(Tuple[A[str]], Tuple[B.A[str]]) self.assertNotEqual(Tuple[A[List[Any]]], Tuple[B.A[List[Any]]]) self.assertNotEqual(Union[str, A[str]], Union[str, mod_generics_cache.A[str]]) self.assertNotEqual(Union[A[str], A[str]], Union[A[str], mod_generics_cache.A[str]]) self.assertNotEqual(typing.FrozenSet[A[str]], typing.FrozenSet[mod_generics_cache.B.A[str]]) if sys.version_info[:2] > (3, 2): self.assertTrue(repr(Tuple[A[str]]).endswith('<locals>.A[str]]')) self.assertTrue(repr(Tuple[B.A[str]]).endswith('<locals>.B.A[str]]')) self.assertTrue(repr(Tuple[mod_generics_cache.A[str]]) .endswith('mod_generics_cache.A[str]]')) self.assertTrue(repr(Tuple[mod_generics_cache.B.A[str]]) .endswith('mod_generics_cache.B.A[str]]')) def test_extended_generic_rules_eq(self): T = TypeVar('T') U = TypeVar('U') self.assertEqual(Tuple[T, T][int], Tuple[int, int]) self.assertEqual(typing.Iterable[Tuple[T, T]][T], typing.Iterable[Tuple[T, T]]) with self.assertRaises(TypeError): Tuple[T, int][()] self.assertEqual(Union[T, int][int], int) self.assertEqual(Union[T, U][int, Union[int, str]], Union[int, str]) class Base: ... class Derived(Base): ... self.assertEqual(Union[T, Base][Union[Base, Derived]], Union[Base, Derived]) with self.assertRaises(TypeError): Union[T, int][1] self.assertEqual(Callable[[T], T][KT], Callable[[KT], KT]) self.assertEqual(Callable[..., List[T]][int], Callable[..., List[int]]) def test_extended_generic_rules_repr(self): T = TypeVar('T') self.assertEqual(repr(Union[Tuple, Callable]).replace('typing.', ''), 'Union[Tuple, Callable]') self.assertEqual(repr(Union[Tuple, Tuple[int]]).replace('typing.', ''), 'Union[Tuple, Tuple[int]]') self.assertEqual(repr(Callable[..., Optional[T]][int]).replace('typing.', ''), 'Callable[..., Optional[int]]') self.assertEqual(repr(Callable[[], List[T]][int]).replace('typing.', ''), 'Callable[[], List[int]]') def test_generic_forward_ref(self): def foobar(x: List[List['CC']]): ... def foobar2(x: list[list[ForwardRef('CC')]]): ... def foobar3(x: list[ForwardRef('CC | int')] | int): ... class CC: ... self.assertEqual( get_type_hints(foobar, globals(), locals()), {'x': List[List[CC]]} ) self.assertEqual( get_type_hints(foobar2, globals(), locals()), {'x': list[list[CC]]} ) self.assertEqual( get_type_hints(foobar3, globals(), locals()), {'x': list[CC | int] | int} ) T = TypeVar('T') AT = Tuple[T, ...] def barfoo(x: AT): ... self.assertIs(get_type_hints(barfoo, globals(), locals())['x'], AT) CT = Callable[..., List[T]] def barfoo2(x: CT): ... self.assertIs(get_type_hints(barfoo2, globals(), locals())['x'], CT) def test_extended_generic_rules_subclassing(self): class T1(Tuple[T, KT]): ... class T2(Tuple[T, ...]): ... class C1(typing.Container[T]): def __contains__(self, item): return False self.assertEqual(T1.__parameters__, (T, KT)) self.assertEqual(T1[int, str].__args__, (int, str)) self.assertEqual(T1[int, T].__origin__, T1) self.assertEqual(T2.__parameters__, (T,)) # These don't work because of tuple.__class_item__ ## with self.assertRaises(TypeError): ## T1[int] ## with self.assertRaises(TypeError): ## T2[int, str] self.assertEqual(repr(C1[int]).split('.')[-1], 'C1[int]') self.assertEqual(C1.__parameters__, (T,)) self.assertIsInstance(C1(), collections.abc.Container) self.assertIsSubclass(C1, collections.abc.Container) self.assertIsInstance(T1(), tuple) self.assertIsSubclass(T2, tuple) with self.assertRaises(TypeError): issubclass(Tuple[int, ...], typing.Sequence) with self.assertRaises(TypeError): issubclass(Tuple[int, ...], typing.Iterable) def test_fail_with_bare_union(self): with self.assertRaises(TypeError): List[Union] with self.assertRaises(TypeError): Tuple[Optional] with self.assertRaises(TypeError): ClassVar[ClassVar] with self.assertRaises(TypeError): List[ClassVar[int]] def test_fail_with_bare_generic(self): T = TypeVar('T') with self.assertRaises(TypeError): List[Generic] with self.assertRaises(TypeError): Tuple[Generic[T]] with self.assertRaises(TypeError): List[typing.Protocol] def test_type_erasure_special(self): T = TypeVar('T') # this is the only test that checks type caching self.clear_caches() class MyTup(Tuple[T, T]): ... self.assertIs(MyTup[int]().__class__, MyTup) self.assertEqual(MyTup[int]().__orig_class__, MyTup[int]) class MyDict(typing.Dict[T, T]): ... self.assertIs(MyDict[int]().__class__, MyDict) self.assertEqual(MyDict[int]().__orig_class__, MyDict[int]) class MyDef(typing.DefaultDict[str, T]): ... self.assertIs(MyDef[int]().__class__, MyDef) self.assertEqual(MyDef[int]().__orig_class__, MyDef[int]) # ChainMap was added in 3.3 if sys.version_info >= (3, 3): class MyChain(typing.ChainMap[str, T]): ... self.assertIs(MyChain[int]().__class__, MyChain) self.assertEqual(MyChain[int]().__orig_class__, MyChain[int]) def test_all_repr_eq_any(self): objs = (getattr(typing, el) for el in typing.__all__) for obj in objs: self.assertNotEqual(repr(obj), '') self.assertEqual(obj, obj) if getattr(obj, '__parameters__', None) and len(obj.__parameters__) == 1: self.assertEqual(obj[Any].__args__, (Any,)) if isinstance(obj, type): for base in obj.__mro__: self.assertNotEqual(repr(base), '') self.assertEqual(base, base) def test_pickle(self): global C # pickle wants to reference the class by name T = TypeVar('T') class B(Generic[T]): pass class C(B[int]): pass c = C() c.foo = 42 c.bar = 'abc' for proto in range(pickle.HIGHEST_PROTOCOL + 1): z = pickle.dumps(c, proto) x = pickle.loads(z) self.assertEqual(x.foo, 42) self.assertEqual(x.bar, 'abc') self.assertEqual(x.__dict__, {'foo': 42, 'bar': 'abc'}) samples = [Any, Union, Tuple, Callable, ClassVar, Union[int, str], ClassVar[List], Tuple[int, ...], Callable[[str], bytes], typing.DefaultDict, typing.FrozenSet[int]] for s in samples: for proto in range(pickle.HIGHEST_PROTOCOL + 1): z = pickle.dumps(s, proto) x = pickle.loads(z) self.assertEqual(s, x) more_samples = [List, typing.Iterable, typing.Type, List[int], typing.Type[typing.Mapping], typing.AbstractSet[Tuple[int, str]]] for s in more_samples: for proto in range(pickle.HIGHEST_PROTOCOL + 1): z = pickle.dumps(s, proto) x = pickle.loads(z) self.assertEqual(s, x) def test_copy_and_deepcopy(self): T = TypeVar('T') class Node(Generic[T]): ... things = [Union[T, int], Tuple[T, int], Callable[..., T], Callable[[int], int], Tuple[Any, Any], Node[T], Node[int], Node[Any], typing.Iterable[T], typing.Iterable[Any], typing.Iterable[int], typing.Dict[int, str], typing.Dict[T, Any], ClassVar[int], ClassVar[List[T]], Tuple['T', 'T'], Union['T', int], List['T'], typing.Mapping['T', int]] for t in things + [Any]: self.assertEqual(t, copy(t)) self.assertEqual(t, deepcopy(t)) def test_immutability_by_copy_and_pickle(self): # Special forms like Union, Any, etc., generic aliases to containers like List, # Mapping, etc., and type variabcles are considered immutable by copy and pickle. global TP, TPB, TPV # for pickle TP = TypeVar('TP') TPB = TypeVar('TPB', bound=int) TPV = TypeVar('TPV', bytes, str) for X in [TP, TPB, TPV, List, typing.Mapping, ClassVar, typing.Iterable, Union, Any, Tuple, Callable]: self.assertIs(copy(X), X) self.assertIs(deepcopy(X), X) self.assertIs(pickle.loads(pickle.dumps(X)), X) # Check that local type variables are copyable. TL = TypeVar('TL') TLB = TypeVar('TLB', bound=int) TLV = TypeVar('TLV', bytes, str) for X in [TL, TLB, TLV]: self.assertIs(copy(X), X) self.assertIs(deepcopy(X), X) def test_copy_generic_instances(self): T = TypeVar('T') class C(Generic[T]): def __init__(self, attr: T) -> None: self.attr = attr c = C(42) self.assertEqual(copy(c).attr, 42) self.assertEqual(deepcopy(c).attr, 42) self.assertIsNot(copy(c), c) self.assertIsNot(deepcopy(c), c) c.attr = 1 self.assertEqual(copy(c).attr, 1) self.assertEqual(deepcopy(c).attr, 1) ci = C[int](42) self.assertEqual(copy(ci).attr, 42) self.assertEqual(deepcopy(ci).attr, 42) self.assertIsNot(copy(ci), ci) self.assertIsNot(deepcopy(ci), ci) ci.attr = 1 self.assertEqual(copy(ci).attr, 1) self.assertEqual(deepcopy(ci).attr, 1) self.assertEqual(ci.__orig_class__, C[int]) def test_weakref_all(self): T = TypeVar('T') things = [Any, Union[T, int], Callable[..., T], Tuple[Any, Any], Optional[List[int]], typing.Mapping[int, str], typing.Match[bytes], typing.Iterable['whatever']] for t in things: self.assertEqual(weakref.ref(t)(), t) def test_parameterized_slots(self): T = TypeVar('T') class C(Generic[T]): __slots__ = ('potato',) c = C() c_int = C[int]() c.potato = 0 c_int.potato = 0 with self.assertRaises(AttributeError): c.tomato = 0 with self.assertRaises(AttributeError): c_int.tomato = 0 def foo(x: C['C']): ... self.assertEqual(get_type_hints(foo, globals(), locals())['x'], C[C]) self.assertEqual(copy(C[int]), deepcopy(C[int])) def test_parameterized_slots_dict(self): T = TypeVar('T') class D(Generic[T]): __slots__ = {'banana': 42} d = D() d_int = D[int]() d.banana = 'yes' d_int.banana = 'yes' with self.assertRaises(AttributeError): d.foobar = 'no' with self.assertRaises(AttributeError): d_int.foobar = 'no' def test_errors(self): with self.assertRaises(TypeError): B = SimpleMapping[XK, Any] class C(Generic[B]): pass def test_repr_2(self): class C(Generic[T]): pass self.assertEqual(C.__module__, __name__) self.assertEqual(C.__qualname__, 'GenericTests.test_repr_2.<locals>.C') X = C[int] self.assertEqual(X.__module__, __name__) self.assertEqual(repr(X).split('.')[-1], 'C[int]') class Y(C[int]): pass self.assertEqual(Y.__module__, __name__) self.assertEqual(Y.__qualname__, 'GenericTests.test_repr_2.<locals>.Y') def test_eq_1(self): self.assertEqual(Generic, Generic) self.assertEqual(Generic[T], Generic[T]) self.assertNotEqual(Generic[KT], Generic[VT]) def test_eq_2(self): class A(Generic[T]): pass class B(Generic[T]): pass self.assertEqual(A, A) self.assertNotEqual(A, B) self.assertEqual(A[T], A[T]) self.assertNotEqual(A[T], B[T]) def test_multiple_inheritance(self): class A(Generic[T, VT]): pass class B(Generic[KT, T]): pass class C(A[T, VT], Generic[VT, T, KT], B[KT, T]): pass self.assertEqual(C.__parameters__, (VT, T, KT)) def test_multiple_inheritance_special(self): S = TypeVar('S') class B(Generic[S]): ... class C(List[int], B): ... self.assertEqual(C.__mro__, (C, list, B, Generic, object)) def test_init_subclass_super_called(self): class FinalException(Exception): pass class Final: def __init_subclass__(cls, **kwargs) -> None: for base in cls.__bases__: if base is not Final and issubclass(base, Final): raise FinalException(base) super().__init_subclass__(**kwargs) class Test(Generic[T], Final): pass with self.assertRaises(FinalException): class Subclass(Test): pass with self.assertRaises(FinalException): class Subclass(Test[int]): pass def test_nested(self): G = Generic class Visitor(G[T]): a = None def set(self, a: T): self.a = a def get(self): return self.a def visit(self) -> T: return self.a V = Visitor[typing.List[int]] class IntListVisitor(V): def append(self, x: int): self.a.append(x) a = IntListVisitor() a.set([]) a.append(1) a.append(42) self.assertEqual(a.get(), [1, 42]) def test_type_erasure(self): T = TypeVar('T') class Node(Generic[T]): def __init__(self, label: T, left: 'Node[T]' = None, right: 'Node[T]' = None): self.label = label # type: T self.left = left # type: Optional[Node[T]] self.right = right # type: Optional[Node[T]] def foo(x: T): a = Node(x) b = Node[T](x) c = Node[Any](x) self.assertIs(type(a), Node) self.assertIs(type(b), Node) self.assertIs(type(c), Node) self.assertEqual(a.label, x) self.assertEqual(b.label, x) self.assertEqual(c.label, x) foo(42) def test_implicit_any(self): T = TypeVar('T') class C(Generic[T]): pass class D(C): pass self.assertEqual(D.__parameters__, ()) with self.assertRaises(Exception): D[int] with self.assertRaises(Exception): D[Any] with self.assertRaises(Exception): D[T] def test_new_with_args(self): class A(Generic[T]): pass class B: def __new__(cls, arg): # call object obj = super().__new__(cls) obj.arg = arg return obj # mro: C, A, Generic, B, object class C(A, B): pass c = C('foo') self.assertEqual(c.arg, 'foo') def test_new_with_args2(self): class A: def __init__(self, arg): self.from_a = arg # call object super().__init__() # mro: C, Generic, A, object class C(Generic[T], A): def __init__(self, arg): self.from_c = arg # call Generic super().__init__(arg) c = C('foo') self.assertEqual(c.from_a, 'foo') self.assertEqual(c.from_c, 'foo') def test_new_no_args(self): class A(Generic[T]): pass with self.assertRaises(TypeError): A('foo') class B: def __new__(cls): # call object obj = super().__new__(cls) obj.from_b = 'b' return obj # mro: C, A, Generic, B, object class C(A, B): def __init__(self, arg): self.arg = arg def __new__(cls, arg): # call A obj = super().__new__(cls) obj.from_c = 'c' return obj c = C('foo') self.assertEqual(c.arg, 'foo') self.assertEqual(c.from_b, 'b') self.assertEqual(c.from_c, 'c') def test_subclass_special_form(self): for obj in ( ClassVar[int], Final[int], Union[int, float], Optional[int], Literal[1, 2], Concatenate[int, ParamSpec("P")], TypeGuard[int], ): with self.subTest(msg=obj): with self.assertRaisesRegex( TypeError, f'^{re.escape(f'Cannot subclass {obj!r}')}$' ): class Foo(obj): pass class ClassVarTests(BaseTestCase): def test_basics(self): with self.assertRaises(TypeError): ClassVar[1] with self.assertRaises(TypeError): ClassVar[int, str] with self.assertRaises(TypeError): ClassVar[int][str] def test_repr(self): self.assertEqual(repr(ClassVar), 'typing.ClassVar') cv = ClassVar[int] self.assertEqual(repr(cv), 'typing.ClassVar[int]') cv = ClassVar[Employee] self.assertEqual(repr(cv), 'typing.ClassVar[%s.Employee]' % __name__) def test_cannot_subclass(self): with self.assertRaises(TypeError): class C(type(ClassVar)): pass with self.assertRaises(TypeError): class C(type(ClassVar[int])): pass def test_cannot_init(self): with self.assertRaises(TypeError): ClassVar() with self.assertRaises(TypeError): type(ClassVar)() with self.assertRaises(TypeError): type(ClassVar[Optional[int]])() def test_no_isinstance(self): with self.assertRaises(TypeError): isinstance(1, ClassVar[int]) with self.assertRaises(TypeError): issubclass(int, ClassVar) class FinalTests(BaseTestCase): def test_basics(self): Final[int] # OK with self.assertRaises(TypeError): Final[1] with self.assertRaises(TypeError): Final[int, str] with self.assertRaises(TypeError): Final[int][str] with self.assertRaises(TypeError): Optional[Final[int]] def test_repr(self): self.assertEqual(repr(Final), 'typing.Final') cv = Final[int] self.assertEqual(repr(cv), 'typing.Final[int]') cv = Final[Employee] self.assertEqual(repr(cv), 'typing.Final[%s.Employee]' % __name__) cv = Final[tuple[int]] self.assertEqual(repr(cv), 'typing.Final[tuple[int]]') def test_cannot_subclass(self): with self.assertRaises(TypeError): class C(type(Final)): pass with self.assertRaises(TypeError): class C(type(Final[int])): pass def test_cannot_init(self): with self.assertRaises(TypeError): Final() with self.assertRaises(TypeError): type(Final)() with self.assertRaises(TypeError): type(Final[Optional[int]])() def test_no_isinstance(self): with self.assertRaises(TypeError): isinstance(1, Final[int]) with self.assertRaises(TypeError): issubclass(int, Final) def test_final_unmodified(self): def func(x): ... self.assertIs(func, final(func)) class CastTests(BaseTestCase): def test_basics(self): self.assertEqual(cast(int, 42), 42) self.assertEqual(cast(float, 42), 42) self.assertIs(type(cast(float, 42)), int) self.assertEqual(cast(Any, 42), 42) self.assertEqual(cast(list, 42), 42) self.assertEqual(cast(Union[str, float], 42), 42) self.assertEqual(cast(AnyStr, 42), 42) self.assertEqual(cast(None, 42), 42) def test_errors(self): # Bogus calls are not expected to fail. cast(42, 42) cast('hello', 42) class ForwardRefTests(BaseTestCase): def test_basics(self): class Node(Generic[T]): def __init__(self, label: T): self.label = label self.left = self.right = None def add_both(self, left: 'Optional[Node[T]]', right: 'Node[T]' = None, stuff: int = None, blah=None): self.left = left self.right = right def add_left(self, node: Optional['Node[T]']): self.add_both(node, None) def add_right(self, node: 'Node[T]' = None): self.add_both(None, node) t = Node[int] both_hints = get_type_hints(t.add_both, globals(), locals()) self.assertEqual(both_hints['left'], Optional[Node[T]]) self.assertEqual(both_hints['right'], Optional[Node[T]]) self.assertEqual(both_hints['left'], both_hints['right']) self.assertEqual(both_hints['stuff'], Optional[int]) self.assertNotIn('blah', both_hints) left_hints = get_type_hints(t.add_left, globals(), locals()) self.assertEqual(left_hints['node'], Optional[Node[T]]) right_hints = get_type_hints(t.add_right, globals(), locals()) self.assertEqual(right_hints['node'], Optional[Node[T]]) def test_forwardref_instance_type_error(self): fr = typing.ForwardRef('int') with self.assertRaises(TypeError): isinstance(42, fr) def test_forwardref_subclass_type_error(self): fr = typing.ForwardRef('int') with self.assertRaises(TypeError): issubclass(int, fr) def test_forward_equality(self): fr = typing.ForwardRef('int') self.assertEqual(fr, typing.ForwardRef('int')) self.assertNotEqual(List['int'], List[int]) def test_forward_equality_gth(self): c1 = typing.ForwardRef('C') c1_gth = typing.ForwardRef('C') c2 = typing.ForwardRef('C') c2_gth = typing.ForwardRef('C') class C: pass def foo(a: c1_gth, b: c2_gth): pass self.assertEqual(get_type_hints(foo, globals(), locals()), {'a': C, 'b': C}) self.assertEqual(c1, c2) self.assertEqual(c1, c1_gth) self.assertEqual(c1_gth, c2_gth) self.assertEqual(List[c1], List[c1_gth]) self.assertNotEqual(List[c1], List[C]) self.assertNotEqual(List[c1_gth], List[C]) self.assertEqual(Union[c1, c1_gth], Union[c1]) self.assertEqual(Union[c1, c1_gth, int], Union[c1, int]) def test_forward_equality_hash(self): c1 = typing.ForwardRef('int') c1_gth = typing.ForwardRef('int') c2 = typing.ForwardRef('int') c2_gth = typing.ForwardRef('int') def foo(a: c1_gth, b: c2_gth): pass get_type_hints(foo, globals(), locals()) self.assertEqual(hash(c1), hash(c2)) self.assertEqual(hash(c1_gth), hash(c2_gth)) self.assertEqual(hash(c1), hash(c1_gth)) def test_forward_equality_namespace(self): class A: pass def namespace1(): a = typing.ForwardRef('A') def fun(x: a): pass get_type_hints(fun, globals(), locals()) return a def namespace2(): a = typing.ForwardRef('A') class A: pass def fun(x: a): pass get_type_hints(fun, globals(), locals()) return a self.assertEqual(namespace1(), namespace1()) self.assertNotEqual(namespace1(), namespace2()) def test_forward_repr(self): self.assertEqual(repr(List['int']), "typing.List[ForwardRef('int')]") def test_union_forward(self): def foo(a: Union['T']): pass self.assertEqual(get_type_hints(foo, globals(), locals()), {'a': Union[T]}) def foo(a: tuple[ForwardRef('T')] | int): pass self.assertEqual(get_type_hints(foo, globals(), locals()), {'a': tuple[T] | int}) def test_tuple_forward(self): def foo(a: Tuple['T']): pass self.assertEqual(get_type_hints(foo, globals(), locals()), {'a': Tuple[T]}) def foo(a: tuple[ForwardRef('T')]): pass self.assertEqual(get_type_hints(foo, globals(), locals()), {'a': tuple[T]}) def test_double_forward(self): def foo(a: 'List[\'int\']'): pass self.assertEqual(get_type_hints(foo, globals(), locals()), {'a': List[int]}) def test_forward_recursion_actually(self): def namespace1(): a = typing.ForwardRef('A') A = a def fun(x: a): pass ret = get_type_hints(fun, globals(), locals()) return a def namespace2(): a = typing.ForwardRef('A') A = a def fun(x: a): pass ret = get_type_hints(fun, globals(), locals()) return a def cmp(o1, o2): return o1 == o2 r1 = namespace1() r2 = namespace2() self.assertIsNot(r1, r2) self.assertRaises(RecursionError, cmp, r1, r2) def test_union_forward_recursion(self): ValueList = List['Value'] Value = Union[str, ValueList] class C: foo: List[Value] class D: foo: Union[Value, ValueList] class E: foo: Union[List[Value], ValueList] class F: foo: Union[Value, List[Value], ValueList] self.assertEqual(get_type_hints(C, globals(), locals()), get_type_hints(C, globals(), locals())) self.assertEqual(get_type_hints(C, globals(), locals()), {'foo': List[Union[str, List[Union[str, List['Value']]]]]}) self.assertEqual(get_type_hints(D, globals(), locals()), {'foo': Union[str, List[Union[str, List['Value']]]]}) self.assertEqual(get_type_hints(E, globals(), locals()), {'foo': Union[ List[Union[str, List[Union[str, List['Value']]]]], List[Union[str, List['Value']]] ] }) self.assertEqual(get_type_hints(F, globals(), locals()), {'foo': Union[ str, List[Union[str, List['Value']]], List[Union[str, List[Union[str, List['Value']]]]] ] }) def test_callable_forward(self): def foo(a: Callable[['T'], 'T']): pass self.assertEqual(get_type_hints(foo, globals(), locals()), {'a': Callable[[T], T]}) def test_callable_with_ellipsis_forward(self): def foo(a: 'Callable[..., T]'): pass self.assertEqual(get_type_hints(foo, globals(), locals()), {'a': Callable[..., T]}) def test_syntax_error(self): with self.assertRaises(SyntaxError): Generic['/T'] def test_delayed_syntax_error(self): def foo(a: 'Node[T'): pass with self.assertRaises(SyntaxError): get_type_hints(foo) def test_type_error(self): def foo(a: Tuple['42']): pass with self.assertRaises(TypeError): get_type_hints(foo) def test_name_error(self): def foo(a: 'Noode[T]'): pass with self.assertRaises(NameError): get_type_hints(foo, locals()) def test_no_type_check(self): @no_type_check def foo(a: 'whatevers') -> {}: pass th = get_type_hints(foo) self.assertEqual(th, {}) def test_no_type_check_class(self): @no_type_check class C: def foo(a: 'whatevers') -> {}: pass cth = get_type_hints(C.foo) self.assertEqual(cth, {}) ith = get_type_hints(C().foo) self.assertEqual(ith, {}) def test_no_type_check_no_bases(self): class C: def meth(self, x: int): ... @no_type_check class D(C): c = C # verify that @no_type_check never affects bases self.assertEqual(get_type_hints(C.meth), {'x': int}) def test_no_type_check_forward_ref_as_string(self): class C: foo: typing.ClassVar[int] = 7 class D: foo: ClassVar[int] = 7 class E: foo: 'typing.ClassVar[int]' = 7 class F: foo: 'ClassVar[int]' = 7 expected_result = {'foo': typing.ClassVar[int]} for clazz in [C, D, E, F]: self.assertEqual(get_type_hints(clazz), expected_result) def test_nested_classvar_fails_forward_ref_check(self): class E: foo: 'typing.ClassVar[typing.ClassVar[int]]' = 7 class F: foo: ClassVar['ClassVar[int]'] = 7 for clazz in [E, F]: with self.assertRaises(TypeError): get_type_hints(clazz) def test_meta_no_type_check(self): @no_type_check_decorator def magic_decorator(func): return func self.assertEqual(magic_decorator.__name__, 'magic_decorator') @magic_decorator def foo(a: 'whatevers') -> {}: pass @magic_decorator class C: def foo(a: 'whatevers') -> {}: pass self.assertEqual(foo.__name__, 'foo') th = get_type_hints(foo) self.assertEqual(th, {}) cth = get_type_hints(C.foo) self.assertEqual(cth, {}) ith = get_type_hints(C().foo) self.assertEqual(ith, {}) def test_default_globals(self): code = ("class C:\n" " def foo(self, a: 'C') -> 'D': pass\n" "class D:\n" " def bar(self, b: 'D') -> C: pass\n" ) ns = {} exec(code, ns) hints = get_type_hints(ns['C'].foo) self.assertEqual(hints, {'a': ns['C'], 'return': ns['D']}) def test_final_forward_ref(self): self.assertEqual(gth(Loop, globals())['attr'], Final[Loop]) self.assertNotEqual(gth(Loop, globals())['attr'], Final[int]) self.assertNotEqual(gth(Loop, globals())['attr'], Final) def test_or(self): X = ForwardRef('X') # __or__/__ror__ itself self.assertEqual(X | "x", Union[X, "x"]) self.assertEqual("x" | X, Union["x", X]) class OverloadTests(BaseTestCase): def test_overload_fails(self): from typing import overload with self.assertRaises(RuntimeError): @overload def blah(): pass blah() def test_overload_succeeds(self): from typing import overload @overload def blah(): pass def blah(): pass blah() ASYNCIO_TESTS = """ import asyncio T_a = TypeVar('T_a') class AwaitableWrapper(typing.Awaitable[T_a]): def __init__(self, value): self.value = value def __await__(self) -> typing.Iterator[T_a]: yield return self.value class AsyncIteratorWrapper(typing.AsyncIterator[T_a]): def __init__(self, value: typing.Iterable[T_a]): self.value = value def __aiter__(self) -> typing.AsyncIterator[T_a]: return self async def __anext__(self) -> T_a: data = await self.value if data: return data else: raise StopAsyncIteration class ACM: async def __aenter__(self) -> int: return 42 async def __aexit__(self, etype, eval, tb): return None """ try: exec(ASYNCIO_TESTS) except ImportError: ASYNCIO = False # multithreading is not enabled else: ASYNCIO = True # Definitions needed for features introduced in Python 3.6 from test import ann_module, ann_module2, ann_module3, ann_module5, ann_module6 from typing import AsyncContextManager class A: y: float class B(A): x: ClassVar[Optional['B']] = None y: int b: int class CSub(B): z: ClassVar['CSub'] = B() class G(Generic[T]): lst: ClassVar[List[T]] = [] class Loop: attr: Final['Loop'] class NoneAndForward: parent: 'NoneAndForward' meaning: None class CoolEmployee(NamedTuple): name: str cool: int class CoolEmployeeWithDefault(NamedTuple): name: str cool: int = 0 class XMeth(NamedTuple): x: int def double(self): return 2 * self.x class XRepr(NamedTuple): x: int y: int = 1 def __str__(self): return f'{self.x} -> {self.y}' def __add__(self, other): return 0 Label = TypedDict('Label', [('label', str)]) class Point2D(TypedDict): x: int y: int class Bar(_typed_dict_helper.Foo, total=False): b: int class LabelPoint2D(Point2D, Label): ... class Options(TypedDict, total=False): log_level: int log_path: str class HasForeignBaseClass(mod_generics_cache.A): some_xrepr: 'XRepr' other_a: 'mod_generics_cache.A' async def g_with(am: AsyncContextManager[int]): x: int async with am as x: return x try: g_with(ACM()).send(None) except StopIteration as e: assert e.args[0] == 42 gth = get_type_hints class ForRefExample: @ann_module.dec def func(self: 'ForRefExample'): pass @ann_module.dec @ann_module.dec def nested(self: 'ForRefExample'): pass class GetTypeHintTests(BaseTestCase): def test_get_type_hints_from_various_objects(self): # For invalid objects should fail with TypeError (not AttributeError etc). with self.assertRaises(TypeError): gth(123) with self.assertRaises(TypeError): gth('abc') with self.assertRaises(TypeError): gth(None) def test_get_type_hints_modules(self): ann_module_type_hints = {1: 2, 'f': Tuple[int, int], 'x': int, 'y': str, 'u': int | float} self.assertEqual(gth(ann_module), ann_module_type_hints) self.assertEqual(gth(ann_module2), {}) self.assertEqual(gth(ann_module3), {}) @skip("known bug") def test_get_type_hints_modules_forwardref(self): # FIXME: This currently exposes a bug in typing. Cached forward references # don't account for the case where there are multiple types of the same # name coming from different modules in the same program. mgc_hints = {'default_a': Optional[mod_generics_cache.A], 'default_b': Optional[mod_generics_cache.B]} self.assertEqual(gth(mod_generics_cache), mgc_hints) def test_get_type_hints_classes(self): self.assertEqual(gth(ann_module.C), # gth will find the right globalns {'y': Optional[ann_module.C]}) self.assertIsInstance(gth(ann_module.j_class), dict) self.assertEqual(gth(ann_module.M), {'123': 123, 'o': type}) self.assertEqual(gth(ann_module.D), {'j': str, 'k': str, 'y': Optional[ann_module.C]}) self.assertEqual(gth(ann_module.Y), {'z': int}) self.assertEqual(gth(ann_module.h_class), {'y': Optional[ann_module.C]}) self.assertEqual(gth(ann_module.S), {'x': str, 'y': str}) self.assertEqual(gth(ann_module.foo), {'x': int}) self.assertEqual(gth(NoneAndForward), {'parent': NoneAndForward, 'meaning': type(None)}) self.assertEqual(gth(HasForeignBaseClass), {'some_xrepr': XRepr, 'other_a': mod_generics_cache.A, 'some_b': mod_generics_cache.B}) self.assertEqual(gth(XRepr.__new__), {'x': int, 'y': int}) self.assertEqual(gth(mod_generics_cache.B), {'my_inner_a1': mod_generics_cache.B.A, 'my_inner_a2': mod_generics_cache.B.A, 'my_outer_a': mod_generics_cache.A}) def test_respect_no_type_check(self): @no_type_check class NoTpCheck: class Inn: def __init__(self, x: 'not a type'): ... self.assertTrue(NoTpCheck.__no_type_check__) self.assertTrue(NoTpCheck.Inn.__init__.__no_type_check__) self.assertEqual(gth(ann_module2.NTC.meth), {}) class ABase(Generic[T]): def meth(x: int): ... @no_type_check class Der(ABase): ... self.assertEqual(gth(ABase.meth), {'x': int}) def test_get_type_hints_for_builtins(self): # Should not fail for built-in classes and functions. self.assertEqual(gth(int), {}) self.assertEqual(gth(type), {}) self.assertEqual(gth(dir), {}) self.assertEqual(gth(len), {}) self.assertEqual(gth(object.__str__), {}) self.assertEqual(gth(object().__str__), {}) self.assertEqual(gth(str.join), {}) def test_previous_behavior(self): def testf(x, y): ... testf.__annotations__['x'] = 'int' self.assertEqual(gth(testf), {'x': int}) def testg(x: None): ... self.assertEqual(gth(testg), {'x': type(None)}) def test_get_type_hints_for_object_with_annotations(self): class A: ... class B: ... b = B() b.__annotations__ = {'x': 'A'} self.assertEqual(gth(b, locals()), {'x': A}) def test_get_type_hints_ClassVar(self): self.assertEqual(gth(ann_module2.CV, ann_module2.__dict__), {'var': typing.ClassVar[ann_module2.CV]}) self.assertEqual(gth(B, globals()), {'y': int, 'x': ClassVar[Optional[B]], 'b': int}) self.assertEqual(gth(CSub, globals()), {'z': ClassVar[CSub], 'y': int, 'b': int, 'x': ClassVar[Optional[B]]}) self.assertEqual(gth(G), {'lst': ClassVar[List[T]]}) def test_get_type_hints_wrapped_decoratored_func(self): expects = {'self': ForRefExample} self.assertEqual(gth(ForRefExample.func), expects) self.assertEqual(gth(ForRefExample.nested), expects) def test_get_type_hints_annotated(self): def foobar(x: List['X']): ... X = Annotated[int, (1, 10)] self.assertEqual( get_type_hints(foobar, globals(), locals()), {'x': List[int]} ) self.assertEqual( get_type_hints(foobar, globals(), locals(), include_extras=True), {'x': List[Annotated[int, (1, 10)]]} ) def foobar(x: list[ForwardRef('X')]): ... X = Annotated[int, (1, 10)] self.assertEqual( get_type_hints(foobar, globals(), locals()), {'x': list[int]} ) self.assertEqual( get_type_hints(foobar, globals(), locals(), include_extras=True), {'x': list[Annotated[int, (1, 10)]]} ) BA = Tuple[Annotated[T, (1, 0)], ...] def barfoo(x: BA): ... self.assertEqual(get_type_hints(barfoo, globals(), locals())['x'], Tuple[T, ...]) self.assertIs( get_type_hints(barfoo, globals(), locals(), include_extras=True)['x'], BA ) BA = tuple[Annotated[T, (1, 0)], ...] def barfoo(x: BA): ... self.assertEqual(get_type_hints(barfoo, globals(), locals())['x'], tuple[T, ...]) self.assertIs( get_type_hints(barfoo, globals(), locals(), include_extras=True)['x'], BA ) def barfoo2(x: typing.Callable[..., Annotated[List[T], "const"]], y: typing.Union[int, Annotated[T, "mutable"]]): ... self.assertEqual( get_type_hints(barfoo2, globals(), locals()), {'x': typing.Callable[..., List[T]], 'y': typing.Union[int, T]} ) BA2 = typing.Callable[..., List[T]] def barfoo3(x: BA2): ... self.assertIs( get_type_hints(barfoo3, globals(), locals(), include_extras=True)["x"], BA2 ) BA3 = typing.Annotated[int | float, "const"] def barfoo4(x: BA3): ... self.assertEqual( get_type_hints(barfoo4, globals(), locals()), {"x": int | float} ) self.assertEqual( get_type_hints(barfoo4, globals(), locals(), include_extras=True), {"x": typing.Annotated[int | float, "const"]} ) def test_get_type_hints_annotated_refs(self): Const = Annotated[T, "Const"] class MySet(Generic[T]): def __ior__(self, other: "Const[MySet[T]]") -> "MySet[T]": ... def __iand__(self, other: Const["MySet[T]"]) -> "MySet[T]": ... self.assertEqual( get_type_hints(MySet.__iand__, globals(), locals()), {'other': MySet[T], 'return': MySet[T]} ) self.assertEqual( get_type_hints(MySet.__iand__, globals(), locals(), include_extras=True), {'other': Const[MySet[T]], 'return': MySet[T]} ) self.assertEqual( get_type_hints(MySet.__ior__, globals(), locals()), {'other': MySet[T], 'return': MySet[T]} ) def test_get_type_hints_classes_str_annotations(self): class Foo: y = str x: 'y' # This previously raised an error under PEP 563. self.assertEqual(get_type_hints(Foo), {'x': str}) def test_get_type_hints_bad_module(self): # bpo-41515 class BadModule: pass BadModule.__module__ = 'bad' # Something not in sys.modules self.assertNotIn('bad', sys.modules) self.assertEqual(get_type_hints(BadModule), {}) def test_get_type_hints_annotated_bad_module(self): # See https://bugs.python.org/issue44468 class BadBase: foo: tuple class BadType(BadBase): bar: list BadType.__module__ = BadBase.__module__ = 'bad' self.assertNotIn('bad', sys.modules) self.assertEqual(get_type_hints(BadType), {'foo': tuple, 'bar': list}) class GetUtilitiesTestCase(TestCase): def test_get_origin(self): T = TypeVar('T') P = ParamSpec('P') class C(Generic[T]): pass self.assertIs(get_origin(C[int]), C) self.assertIs(get_origin(C[T]), C) self.assertIs(get_origin(int), None) self.assertIs(get_origin(ClassVar[int]), ClassVar) self.assertIs(get_origin(Union[int, str]), Union) self.assertIs(get_origin(Literal[42, 43]), Literal) self.assertIs(get_origin(Final[List[int]]), Final) self.assertIs(get_origin(Generic), Generic) self.assertIs(get_origin(Generic[T]), Generic) self.assertIs(get_origin(List[Tuple[T, T]][int]), list) self.assertIs(get_origin(Annotated[T, 'thing']), Annotated) self.assertIs(get_origin(List), list) self.assertIs(get_origin(Tuple), tuple) self.assertIs(get_origin(Callable), collections.abc.Callable) self.assertIs(get_origin(list[int]), list) self.assertIs(get_origin(list), None) self.assertIs(get_origin(list | str), types.UnionType) self.assertIs(get_origin(P.args), P) self.assertIs(get_origin(P.kwargs), P) def test_get_args(self): T = TypeVar('T') class C(Generic[T]): pass self.assertEqual(get_args(C[int]), (int,)) self.assertEqual(get_args(C[T]), (T,)) self.assertEqual(get_args(int), ()) self.assertEqual(get_args(ClassVar[int]), (int,)) self.assertEqual(get_args(Union[int, str]), (int, str)) self.assertEqual(get_args(Literal[42, 43]), (42, 43)) self.assertEqual(get_args(Final[List[int]]), (List[int],)) self.assertEqual(get_args(Union[int, Tuple[T, int]][str]), (int, Tuple[str, int])) self.assertEqual(get_args(typing.Dict[int, Tuple[T, T]][Optional[int]]), (int, Tuple[Optional[int], Optional[int]])) self.assertEqual(get_args(Callable[[], T][int]), ([], int)) self.assertEqual(get_args(Callable[..., int]), (..., int)) self.assertEqual(get_args(Union[int, Callable[[Tuple[T, ...]], str]]), (int, Callable[[Tuple[T, ...]], str])) self.assertEqual(get_args(Tuple[int, ...]), (int, ...)) self.assertEqual(get_args(Tuple[()]), ((),)) self.assertEqual(get_args(Annotated[T, 'one', 2, ['three']]), (T, 'one', 2, ['three'])) self.assertEqual(get_args(List), ()) self.assertEqual(get_args(Tuple), ()) self.assertEqual(get_args(Callable), ()) self.assertEqual(get_args(list[int]), (int,)) self.assertEqual(get_args(list), ()) self.assertEqual(get_args(collections.abc.Callable[[int], str]), ([int], str)) self.assertEqual(get_args(collections.abc.Callable[..., str]), (..., str)) self.assertEqual(get_args(collections.abc.Callable[[], str]), ([], str)) self.assertEqual(get_args(collections.abc.Callable[[int], str]), get_args(Callable[[int], str])) P = ParamSpec('P') self.assertEqual(get_args(Callable[P, int]), (P, int)) self.assertEqual(get_args(Callable[Concatenate[int, P], int]), (Concatenate[int, P], int)) self.assertEqual(get_args(list | str), (list, str)) def test_forward_ref_and_final(self): # https://bugs.python.org/issue45166 hints = get_type_hints(ann_module5) self.assertEqual(hints, {'name': Final[str]}) hints = get_type_hints(ann_module5.MyClass) self.assertEqual(hints, {'value': Final}) def test_top_level_class_var(self): # https://bugs.python.org/issue45166 with self.assertRaisesRegex( TypeError, r'typing.ClassVar\[int\] is not valid as type argument', ): get_type_hints(ann_module6) class CollectionsAbcTests(BaseTestCase): def test_hashable(self): self.assertIsInstance(42, typing.Hashable) self.assertNotIsInstance([], typing.Hashable) def test_iterable(self): self.assertIsInstance([], typing.Iterable) # Due to ABC caching, the second time takes a separate code # path and could fail. So call this a few times. self.assertIsInstance([], typing.Iterable) self.assertIsInstance([], typing.Iterable) self.assertNotIsInstance(42, typing.Iterable) # Just in case, also test issubclass() a few times. self.assertIsSubclass(list, typing.Iterable) self.assertIsSubclass(list, typing.Iterable) def test_iterator(self): it = iter([]) self.assertIsInstance(it, typing.Iterator) self.assertNotIsInstance(42, typing.Iterator) @skipUnless(ASYNCIO, 'Python 3.5 and multithreading required') def test_awaitable(self): ns = {} exec( "async def foo() -> typing.Awaitable[int]:\n" " return await AwaitableWrapper(42)\n", globals(), ns) foo = ns['foo'] g = foo() self.assertIsInstance(g, typing.Awaitable) self.assertNotIsInstance(foo, typing.Awaitable) g.send(None) # Run foo() till completion, to avoid warning. @skipUnless(ASYNCIO, 'Python 3.5 and multithreading required') def test_coroutine(self): ns = {} exec( "async def foo():\n" " return\n", globals(), ns) foo = ns['foo'] g = foo() self.assertIsInstance(g, typing.Coroutine) with self.assertRaises(TypeError): isinstance(g, typing.Coroutine[int]) self.assertNotIsInstance(foo, typing.Coroutine) try: g.send(None) except StopIteration: pass @skipUnless(ASYNCIO, 'Python 3.5 and multithreading required') def test_async_iterable(self): base_it = range(10) # type: Iterator[int] it = AsyncIteratorWrapper(base_it) self.assertIsInstance(it, typing.AsyncIterable) self.assertIsInstance(it, typing.AsyncIterable) self.assertNotIsInstance(42, typing.AsyncIterable) @skipUnless(ASYNCIO, 'Python 3.5 and multithreading required') def test_async_iterator(self): base_it = range(10) # type: Iterator[int] it = AsyncIteratorWrapper(base_it) self.assertIsInstance(it, typing.AsyncIterator) self.assertNotIsInstance(42, typing.AsyncIterator) def test_sized(self): self.assertIsInstance([], typing.Sized) self.assertNotIsInstance(42, typing.Sized) def test_container(self): self.assertIsInstance([], typing.Container) self.assertNotIsInstance(42, typing.Container) def test_collection(self): if hasattr(typing, 'Collection'): self.assertIsInstance(tuple(), typing.Collection) self.assertIsInstance(frozenset(), typing.Collection) self.assertIsSubclass(dict, typing.Collection) self.assertNotIsInstance(42, typing.Collection) def test_abstractset(self): self.assertIsInstance(set(), typing.AbstractSet) self.assertNotIsInstance(42, typing.AbstractSet) def test_mutableset(self): self.assertIsInstance(set(), typing.MutableSet) self.assertNotIsInstance(frozenset(), typing.MutableSet) def test_mapping(self): self.assertIsInstance({}, typing.Mapping) self.assertNotIsInstance(42, typing.Mapping) def test_mutablemapping(self): self.assertIsInstance({}, typing.MutableMapping) self.assertNotIsInstance(42, typing.MutableMapping) def test_sequence(self): self.assertIsInstance([], typing.Sequence) self.assertNotIsInstance(42, typing.Sequence) def test_mutablesequence(self): self.assertIsInstance([], typing.MutableSequence) self.assertNotIsInstance((), typing.MutableSequence) def test_bytestring(self): self.assertIsInstance(b'', typing.ByteString) self.assertIsInstance(bytearray(b''), typing.ByteString) def test_list(self): self.assertIsSubclass(list, typing.List) def test_deque(self): self.assertIsSubclass(collections.deque, typing.Deque) class MyDeque(typing.Deque[int]): ... self.assertIsInstance(MyDeque(), collections.deque) def test_counter(self): self.assertIsSubclass(collections.Counter, typing.Counter) def test_set(self): self.assertIsSubclass(set, typing.Set) self.assertNotIsSubclass(frozenset, typing.Set) def test_frozenset(self): self.assertIsSubclass(frozenset, typing.FrozenSet) self.assertNotIsSubclass(set, typing.FrozenSet) def test_dict(self): self.assertIsSubclass(dict, typing.Dict) def test_dict_subscribe(self): K = TypeVar('K') V = TypeVar('V') self.assertEqual(Dict[K, V][str, int], Dict[str, int]) self.assertEqual(Dict[K, int][str], Dict[str, int]) self.assertEqual(Dict[str, V][int], Dict[str, int]) self.assertEqual(Dict[K, List[V]][str, int], Dict[str, List[int]]) self.assertEqual(Dict[K, List[int]][str], Dict[str, List[int]]) self.assertEqual(Dict[K, list[V]][str, int], Dict[str, list[int]]) self.assertEqual(Dict[K, list[int]][str], Dict[str, list[int]]) def test_no_list_instantiation(self): with self.assertRaises(TypeError): typing.List() with self.assertRaises(TypeError): typing.List[T]() with self.assertRaises(TypeError): typing.List[int]() def test_list_subclass(self): class MyList(typing.List[int]): pass a = MyList() self.assertIsInstance(a, MyList) self.assertIsInstance(a, typing.Sequence) self.assertIsSubclass(MyList, list) self.assertNotIsSubclass(list, MyList) def test_no_dict_instantiation(self): with self.assertRaises(TypeError): typing.Dict() with self.assertRaises(TypeError): typing.Dict[KT, VT]() with self.assertRaises(TypeError): typing.Dict[str, int]() def test_dict_subclass(self): class MyDict(typing.Dict[str, int]): pass d = MyDict() self.assertIsInstance(d, MyDict) self.assertIsInstance(d, typing.MutableMapping) self.assertIsSubclass(MyDict, dict) self.assertNotIsSubclass(dict, MyDict) def test_defaultdict_instantiation(self): self.assertIs(type(typing.DefaultDict()), collections.defaultdict) self.assertIs(type(typing.DefaultDict[KT, VT]()), collections.defaultdict) self.assertIs(type(typing.DefaultDict[str, int]()), collections.defaultdict) def test_defaultdict_subclass(self): class MyDefDict(typing.DefaultDict[str, int]): pass dd = MyDefDict() self.assertIsInstance(dd, MyDefDict) self.assertIsSubclass(MyDefDict, collections.defaultdict) self.assertNotIsSubclass(collections.defaultdict, MyDefDict) def test_ordereddict_instantiation(self): self.assertIs(type(typing.OrderedDict()), collections.OrderedDict) self.assertIs(type(typing.OrderedDict[KT, VT]()), collections.OrderedDict) self.assertIs(type(typing.OrderedDict[str, int]()), collections.OrderedDict) def test_ordereddict_subclass(self): class MyOrdDict(typing.OrderedDict[str, int]): pass od = MyOrdDict() self.assertIsInstance(od, MyOrdDict) self.assertIsSubclass(MyOrdDict, collections.OrderedDict) self.assertNotIsSubclass(collections.OrderedDict, MyOrdDict) @skipUnless(sys.version_info >= (3, 3), 'ChainMap was added in 3.3') def test_chainmap_instantiation(self): self.assertIs(type(typing.ChainMap()), collections.ChainMap) self.assertIs(type(typing.ChainMap[KT, VT]()), collections.ChainMap) self.assertIs(type(typing.ChainMap[str, int]()), collections.ChainMap) class CM(typing.ChainMap[KT, VT]): ... self.assertIs(type(CM[int, str]()), CM) @skipUnless(sys.version_info >= (3, 3), 'ChainMap was added in 3.3') def test_chainmap_subclass(self): class MyChainMap(typing.ChainMap[str, int]): pass cm = MyChainMap() self.assertIsInstance(cm, MyChainMap) self.assertIsSubclass(MyChainMap, collections.ChainMap) self.assertNotIsSubclass(collections.ChainMap, MyChainMap) def test_deque_instantiation(self): self.assertIs(type(typing.Deque()), collections.deque) self.assertIs(type(typing.Deque[T]()), collections.deque) self.assertIs(type(typing.Deque[int]()), collections.deque) class D(typing.Deque[T]): ... self.assertIs(type(D[int]()), D) def test_counter_instantiation(self): self.assertIs(type(typing.Counter()), collections.Counter) self.assertIs(type(typing.Counter[T]()), collections.Counter) self.assertIs(type(typing.Counter[int]()), collections.Counter) class C(typing.Counter[T]): ... self.assertIs(type(C[int]()), C) def test_counter_subclass_instantiation(self): class MyCounter(typing.Counter[int]): pass d = MyCounter() self.assertIsInstance(d, MyCounter) self.assertIsInstance(d, typing.Counter) self.assertIsInstance(d, collections.Counter) def test_no_set_instantiation(self): with self.assertRaises(TypeError): typing.Set() with self.assertRaises(TypeError): typing.Set[T]() with self.assertRaises(TypeError): typing.Set[int]() def test_set_subclass_instantiation(self): class MySet(typing.Set[int]): pass d = MySet() self.assertIsInstance(d, MySet) def test_no_frozenset_instantiation(self): with self.assertRaises(TypeError): typing.FrozenSet() with self.assertRaises(TypeError): typing.FrozenSet[T]() with self.assertRaises(TypeError): typing.FrozenSet[int]() def test_frozenset_subclass_instantiation(self): class MyFrozenSet(typing.FrozenSet[int]): pass d = MyFrozenSet() self.assertIsInstance(d, MyFrozenSet) def test_no_tuple_instantiation(self): with self.assertRaises(TypeError): Tuple() with self.assertRaises(TypeError): Tuple[T]() with self.assertRaises(TypeError): Tuple[int]() def test_generator(self): def foo(): yield 42 g = foo() self.assertIsSubclass(type(g), typing.Generator) def test_no_generator_instantiation(self): with self.assertRaises(TypeError): typing.Generator() with self.assertRaises(TypeError): typing.Generator[T, T, T]() with self.assertRaises(TypeError): typing.Generator[int, int, int]() def test_async_generator(self): ns = {} exec("async def f():\n" " yield 42\n", globals(), ns) g = ns['f']() self.assertIsSubclass(type(g), typing.AsyncGenerator) def test_no_async_generator_instantiation(self): with self.assertRaises(TypeError): typing.AsyncGenerator() with self.assertRaises(TypeError): typing.AsyncGenerator[T, T]() with self.assertRaises(TypeError): typing.AsyncGenerator[int, int]() def test_subclassing(self): class MMA(typing.MutableMapping): pass with self.assertRaises(TypeError): # It's abstract MMA() class MMC(MMA): def __getitem__(self, k): return None def __setitem__(self, k, v): pass def __delitem__(self, k): pass def __iter__(self): return iter(()) def __len__(self): return 0 self.assertEqual(len(MMC()), 0) assert callable(MMC.update) self.assertIsInstance(MMC(), typing.Mapping) class MMB(typing.MutableMapping[KT, VT]): def __getitem__(self, k): return None def __setitem__(self, k, v): pass def __delitem__(self, k): pass def __iter__(self): return iter(()) def __len__(self): return 0 self.assertEqual(len(MMB()), 0) self.assertEqual(len(MMB[str, str]()), 0) self.assertEqual(len(MMB[KT, VT]()), 0) self.assertNotIsSubclass(dict, MMA) self.assertNotIsSubclass(dict, MMB) self.assertIsSubclass(MMA, typing.Mapping) self.assertIsSubclass(MMB, typing.Mapping) self.assertIsSubclass(MMC, typing.Mapping) self.assertIsInstance(MMB[KT, VT](), typing.Mapping) self.assertIsInstance(MMB[KT, VT](), collections.abc.Mapping) self.assertIsSubclass(MMA, collections.abc.Mapping) self.assertIsSubclass(MMB, collections.abc.Mapping) self.assertIsSubclass(MMC, collections.abc.Mapping) with self.assertRaises(TypeError): issubclass(MMB[str, str], typing.Mapping) self.assertIsSubclass(MMC, MMA) class I(typing.Iterable): ... self.assertNotIsSubclass(list, I) class G(typing.Generator[int, int, int]): ... def g(): yield 0 self.assertIsSubclass(G, typing.Generator) self.assertIsSubclass(G, typing.Iterable) self.assertIsSubclass(G, collections.abc.Generator) self.assertIsSubclass(G, collections.abc.Iterable) self.assertNotIsSubclass(type(g), G) def test_subclassing_async_generator(self): class G(typing.AsyncGenerator[int, int]): def asend(self, value): pass def athrow(self, typ, val=None, tb=None): pass ns = {} exec('async def g(): yield 0', globals(), ns) g = ns['g'] self.assertIsSubclass(G, typing.AsyncGenerator) self.assertIsSubclass(G, typing.AsyncIterable) self.assertIsSubclass(G, collections.abc.AsyncGenerator) self.assertIsSubclass(G, collections.abc.AsyncIterable) self.assertNotIsSubclass(type(g), G) instance = G() self.assertIsInstance(instance, typing.AsyncGenerator) self.assertIsInstance(instance, typing.AsyncIterable) self.assertIsInstance(instance, collections.abc.AsyncGenerator) self.assertIsInstance(instance, collections.abc.AsyncIterable) self.assertNotIsInstance(type(g), G) self.assertNotIsInstance(g, G) def test_subclassing_subclasshook(self): class Base(typing.Iterable): @classmethod def __subclasshook__(cls, other): if other.__name__ == 'Foo': return True else: return False class C(Base): ... class Foo: ... class Bar: ... self.assertIsSubclass(Foo, Base) self.assertIsSubclass(Foo, C) self.assertNotIsSubclass(Bar, C) def test_subclassing_register(self): class A(typing.Container): ... class B(A): ... class C: ... A.register(C) self.assertIsSubclass(C, A) self.assertNotIsSubclass(C, B) class D: ... B.register(D) self.assertIsSubclass(D, A) self.assertIsSubclass(D, B) class M(): ... collections.abc.MutableMapping.register(M) self.assertIsSubclass(M, typing.Mapping) def test_collections_as_base(self): class M(collections.abc.Mapping): ... self.assertIsSubclass(M, typing.Mapping) self.assertIsSubclass(M, typing.Iterable) class S(collections.abc.MutableSequence): ... self.assertIsSubclass(S, typing.MutableSequence) self.assertIsSubclass(S, typing.Iterable) class I(collections.abc.Iterable): ... self.assertIsSubclass(I, typing.Iterable) class A(collections.abc.Mapping, metaclass=abc.ABCMeta): ... class B: ... A.register(B) self.assertIsSubclass(B, typing.Mapping) class OtherABCTests(BaseTestCase): def test_contextmanager(self): @contextlib.contextmanager def manager(): yield 42 cm = manager() self.assertIsInstance(cm, typing.ContextManager) self.assertNotIsInstance(42, typing.ContextManager) @skipUnless(ASYNCIO, 'Python 3.5 required') def test_async_contextmanager(self): class NotACM: pass self.assertIsInstance(ACM(), typing.AsyncContextManager) self.assertNotIsInstance(NotACM(), typing.AsyncContextManager) @contextlib.contextmanager def manager(): yield 42 cm = manager() self.assertNotIsInstance(cm, typing.AsyncContextManager) self.assertEqual(typing.AsyncContextManager[int].__args__, (int,)) with self.assertRaises(TypeError): isinstance(42, typing.AsyncContextManager[int]) with self.assertRaises(TypeError): typing.AsyncContextManager[int, str] class TypeTests(BaseTestCase): def test_type_basic(self): class User: pass class BasicUser(User): pass class ProUser(User): pass def new_user(user_class: Type[User]) -> User: return user_class() new_user(BasicUser) def test_type_typevar(self): class User: pass class BasicUser(User): pass class ProUser(User): pass U = TypeVar('U', bound=User) def new_user(user_class: Type[U]) -> U: return user_class() new_user(BasicUser) def test_type_optional(self): A = Optional[Type[BaseException]] def foo(a: A) -> Optional[BaseException]: if a is None: return None else: return a() assert isinstance(foo(KeyboardInterrupt), KeyboardInterrupt) assert foo(None) is None class TestModules(TestCase): func_names = ['_idfunc'] def test_py_functions(self): for fname in self.func_names: self.assertEqual(getattr(py_typing, fname).__module__, 'typing') @skipUnless(c_typing, 'requires _typing') def test_c_functions(self): for fname in self.func_names: self.assertEqual(getattr(c_typing, fname).__module__, '_typing') class NewTypeTests: def cleanup(self): for f in self.module._cleanups: f() @classmethod def setUpClass(cls): sys.modules['typing'] = cls.module global UserId UserId = cls.module.NewType('UserId', int) cls.UserName = cls.module.NewType(cls.__qualname__ + '.UserName', str) @classmethod def tearDownClass(cls): global UserId del UserId del cls.UserName sys.modules['typing'] = typing def tearDown(self): self.cleanup() def test_basic(self): self.assertIsInstance(UserId(5), int) self.assertIsInstance(self.UserName('Joe'), str) self.assertEqual(UserId(5) + 1, 6) def test_errors(self): with self.assertRaises(TypeError): issubclass(UserId, int) with self.assertRaises(TypeError): class D(UserId): pass def test_or(self): for cls in (int, self.UserName): with self.subTest(cls=cls): self.assertEqual(UserId | cls, self.module.Union[UserId, cls]) self.assertEqual(cls | UserId, self.module.Union[cls, UserId]) self.assertEqual(self.module.get_args(UserId | cls), (UserId, cls)) self.assertEqual(self.module.get_args(cls | UserId), (cls, UserId)) def test_special_attrs(self): self.assertEqual(UserId.__name__, 'UserId') self.assertEqual(UserId.__qualname__, 'UserId') self.assertEqual(UserId.__module__, __name__) self.assertEqual(UserId.__supertype__, int) UserName = self.UserName self.assertEqual(UserName.__name__, 'UserName') self.assertEqual(UserName.__qualname__, self.__class__.__qualname__ + '.UserName') self.assertEqual(UserName.__module__, __name__) self.assertEqual(UserName.__supertype__, str) def test_repr(self): self.assertEqual(repr(UserId), f'{__name__}.UserId') self.assertEqual(repr(self.UserName), f'{__name__}.{self.__class__.__qualname__}.UserName') def test_pickle(self): UserAge = self.module.NewType('UserAge', float) for proto in range(pickle.HIGHEST_PROTOCOL + 1): with self.subTest(proto=proto): pickled = pickle.dumps(UserId, proto) loaded = pickle.loads(pickled) self.assertIs(loaded, UserId) pickled = pickle.dumps(self.UserName, proto) loaded = pickle.loads(pickled) self.assertIs(loaded, self.UserName) with self.assertRaises(pickle.PicklingError): pickle.dumps(UserAge, proto) def test_missing__name__(self): code = ("import typing\n" "NT = typing.NewType('NT', int)\n" ) exec(code, {}) class NewTypePythonTests(NewTypeTests, BaseTestCase): module = py_typing @skipUnless(c_typing, 'requires _typing') class NewTypeCTests(NewTypeTests, BaseTestCase): module = c_typing class NamedTupleTests(BaseTestCase): class NestedEmployee(NamedTuple): name: str cool: int def test_basics(self): Emp = NamedTuple('Emp', [('name', str), ('id', int)]) self.assertIsSubclass(Emp, tuple) joe = Emp('Joe', 42) jim = Emp(name='Jim', id=1) self.assertIsInstance(joe, Emp) self.assertIsInstance(joe, tuple) self.assertEqual(joe.name, 'Joe') self.assertEqual(joe.id, 42) self.assertEqual(jim.name, 'Jim') self.assertEqual(jim.id, 1) self.assertEqual(Emp.__name__, 'Emp') self.assertEqual(Emp._fields, ('name', 'id')) self.assertEqual(Emp.__annotations__, collections.OrderedDict([('name', str), ('id', int)])) def test_namedtuple_pyversion(self): if sys.version_info[:2] < (3, 6): with self.assertRaises(TypeError): NamedTuple('Name', one=int, other=str) with self.assertRaises(TypeError): class NotYet(NamedTuple): whatever = 0 def test_annotation_usage(self): tim = CoolEmployee('Tim', 9000) self.assertIsInstance(tim, CoolEmployee) self.assertIsInstance(tim, tuple) self.assertEqual(tim.name, 'Tim') self.assertEqual(tim.cool, 9000) self.assertEqual(CoolEmployee.__name__, 'CoolEmployee') self.assertEqual(CoolEmployee._fields, ('name', 'cool')) self.assertEqual(CoolEmployee.__annotations__, collections.OrderedDict(name=str, cool=int)) def test_annotation_usage_with_default(self): jelle = CoolEmployeeWithDefault('Jelle') self.assertIsInstance(jelle, CoolEmployeeWithDefault) self.assertIsInstance(jelle, tuple) self.assertEqual(jelle.name, 'Jelle') self.assertEqual(jelle.cool, 0) cooler_employee = CoolEmployeeWithDefault('Sjoerd', 1) self.assertEqual(cooler_employee.cool, 1) self.assertEqual(CoolEmployeeWithDefault.__name__, 'CoolEmployeeWithDefault') self.assertEqual(CoolEmployeeWithDefault._fields, ('name', 'cool')) self.assertEqual(CoolEmployeeWithDefault.__annotations__, dict(name=str, cool=int)) self.assertEqual(CoolEmployeeWithDefault._field_defaults, dict(cool=0)) with self.assertRaises(TypeError): class NonDefaultAfterDefault(NamedTuple): x: int = 3 y: int def test_annotation_usage_with_methods(self): self.assertEqual(XMeth(1).double(), 2) self.assertEqual(XMeth(42).x, XMeth(42)[0]) self.assertEqual(str(XRepr(42)), '42 -> 1') self.assertEqual(XRepr(1, 2) + XRepr(3), 0) with self.assertRaises(AttributeError): class XMethBad(NamedTuple): x: int def _fields(self): return 'no chance for this' with self.assertRaises(AttributeError): class XMethBad2(NamedTuple): x: int def _source(self): return 'no chance for this as well' def test_multiple_inheritance(self): class A: pass with self.assertRaises(TypeError): class X(NamedTuple, A): x: int def test_namedtuple_keyword_usage(self): LocalEmployee = NamedTuple("LocalEmployee", name=str, age=int) nick = LocalEmployee('Nick', 25) self.assertIsInstance(nick, tuple) self.assertEqual(nick.name, 'Nick') self.assertEqual(LocalEmployee.__name__, 'LocalEmployee') self.assertEqual(LocalEmployee._fields, ('name', 'age')) self.assertEqual(LocalEmployee.__annotations__, dict(name=str, age=int)) with self.assertRaises(TypeError): NamedTuple('Name', [('x', int)], y=str) with self.assertRaises(TypeError): NamedTuple('Name', x=1, y='a') def test_namedtuple_special_keyword_names(self): NT = NamedTuple("NT", cls=type, self=object, typename=str, fields=list) self.assertEqual(NT.__name__, 'NT') self.assertEqual(NT._fields, ('cls', 'self', 'typename', 'fields')) a = NT(cls=str, self=42, typename='foo', fields=[('bar', tuple)]) self.assertEqual(a.cls, str) self.assertEqual(a.self, 42) self.assertEqual(a.typename, 'foo') self.assertEqual(a.fields, [('bar', tuple)]) def test_empty_namedtuple(self): NT = NamedTuple('NT') class CNT(NamedTuple): pass # empty body for struct in [NT, CNT]: with self.subTest(struct=struct): self.assertEqual(struct._fields, ()) self.assertEqual(struct._field_defaults, {}) self.assertEqual(struct.__annotations__, {}) self.assertIsInstance(struct(), struct) def test_namedtuple_errors(self): with self.assertRaises(TypeError): NamedTuple.__new__() with self.assertRaises(TypeError): NamedTuple() with self.assertRaises(TypeError): NamedTuple('Emp', [('name', str)], None) with self.assertRaises(ValueError): NamedTuple('Emp', [('_name', str)]) with self.assertRaises(TypeError): NamedTuple(typename='Emp', name=str, id=int) with self.assertRaises(TypeError): NamedTuple('Emp', fields=[('name', str), ('id', int)]) def test_copy_and_pickle(self): global Emp # pickle wants to reference the class by name Emp = NamedTuple('Emp', [('name', str), ('cool', int)]) for cls in Emp, CoolEmployee, self.NestedEmployee: with self.subTest(cls=cls): jane = cls('jane', 37) for proto in range(pickle.HIGHEST_PROTOCOL + 1): z = pickle.dumps(jane, proto) jane2 = pickle.loads(z) self.assertEqual(jane2, jane) self.assertIsInstance(jane2, cls) jane2 = copy(jane) self.assertEqual(jane2, jane) self.assertIsInstance(jane2, cls) jane2 = deepcopy(jane) self.assertEqual(jane2, jane) self.assertIsInstance(jane2, cls) class TypedDictTests(BaseTestCase): def test_basics_functional_syntax(self): Emp = TypedDict('Emp', {'name': str, 'id': int}) self.assertIsSubclass(Emp, dict) self.assertIsSubclass(Emp, typing.MutableMapping) self.assertNotIsSubclass(Emp, collections.abc.Sequence) jim = Emp(name='Jim', id=1) self.assertIs(type(jim), dict) self.assertEqual(jim['name'], 'Jim') self.assertEqual(jim['id'], 1) self.assertEqual(Emp.__name__, 'Emp') self.assertEqual(Emp.__module__, __name__) self.assertEqual(Emp.__bases__, (dict,)) self.assertEqual(Emp.__annotations__, {'name': str, 'id': int}) self.assertEqual(Emp.__total__, True) def test_basics_keywords_syntax(self): Emp = TypedDict('Emp', name=str, id=int) self.assertIsSubclass(Emp, dict) self.assertIsSubclass(Emp, typing.MutableMapping) self.assertNotIsSubclass(Emp, collections.abc.Sequence) jim = Emp(name='Jim', id=1) self.assertIs(type(jim), dict) self.assertEqual(jim['name'], 'Jim') self.assertEqual(jim['id'], 1) self.assertEqual(Emp.__name__, 'Emp') self.assertEqual(Emp.__module__, __name__) self.assertEqual(Emp.__bases__, (dict,)) self.assertEqual(Emp.__annotations__, {'name': str, 'id': int}) self.assertEqual(Emp.__total__, True) def test_typeddict_special_keyword_names(self): TD = TypedDict("TD", cls=type, self=object, typename=str, _typename=int, fields=list, _fields=dict) self.assertEqual(TD.__name__, 'TD') self.assertEqual(TD.__annotations__, {'cls': type, 'self': object, 'typename': str, '_typename': int, 'fields': list, '_fields': dict}) a = TD(cls=str, self=42, typename='foo', _typename=53, fields=[('bar', tuple)], _fields={'baz', set}) self.assertEqual(a['cls'], str) self.assertEqual(a['self'], 42) self.assertEqual(a['typename'], 'foo') self.assertEqual(a['_typename'], 53) self.assertEqual(a['fields'], [('bar', tuple)]) self.assertEqual(a['_fields'], {'baz', set}) def test_typeddict_create_errors(self): with self.assertRaises(TypeError): TypedDict.__new__() with self.assertRaises(TypeError): TypedDict() with self.assertRaises(TypeError): TypedDict('Emp', [('name', str)], None) with self.assertRaises(TypeError): TypedDict(_typename='Emp', name=str, id=int) with self.assertRaises(TypeError): TypedDict('Emp', _fields={'name': str, 'id': int}) def test_typeddict_errors(self): Emp = TypedDict('Emp', {'name': str, 'id': int}) self.assertEqual(TypedDict.__module__, 'typing') jim = Emp(name='Jim', id=1) with self.assertRaises(TypeError): isinstance({}, Emp) with self.assertRaises(TypeError): isinstance(jim, Emp) with self.assertRaises(TypeError): issubclass(dict, Emp) with self.assertRaises(TypeError): TypedDict('Hi', x=1) with self.assertRaises(TypeError): TypedDict('Hi', [('x', int), ('y', 1)]) with self.assertRaises(TypeError): TypedDict('Hi', [('x', int)], y=int) def test_py36_class_syntax_usage(self): self.assertEqual(LabelPoint2D.__name__, 'LabelPoint2D') self.assertEqual(LabelPoint2D.__module__, __name__) self.assertEqual(LabelPoint2D.__annotations__, {'x': int, 'y': int, 'label': str}) self.assertEqual(LabelPoint2D.__bases__, (dict,)) self.assertEqual(LabelPoint2D.__total__, True) self.assertNotIsSubclass(LabelPoint2D, typing.Sequence) not_origin = Point2D(x=0, y=1) self.assertEqual(not_origin['x'], 0) self.assertEqual(not_origin['y'], 1) other = LabelPoint2D(x=0, y=1, label='hi') self.assertEqual(other['label'], 'hi') def test_pickle(self): global EmpD # pickle wants to reference the class by name EmpD = TypedDict('EmpD', name=str, id=int) jane = EmpD({'name': 'jane', 'id': 37}) for proto in range(pickle.HIGHEST_PROTOCOL + 1): z = pickle.dumps(jane, proto) jane2 = pickle.loads(z) self.assertEqual(jane2, jane) self.assertEqual(jane2, {'name': 'jane', 'id': 37}) ZZ = pickle.dumps(EmpD, proto) EmpDnew = pickle.loads(ZZ) self.assertEqual(EmpDnew({'name': 'jane', 'id': 37}), jane) def test_optional(self): EmpD = TypedDict('EmpD', name=str, id=int) self.assertEqual(typing.Optional[EmpD], typing.Union[None, EmpD]) self.assertNotEqual(typing.List[EmpD], typing.Tuple[EmpD]) def test_total(self): D = TypedDict('D', {'x': int}, total=False) self.assertEqual(D(), {}) self.assertEqual(D(x=1), {'x': 1}) self.assertEqual(D.__total__, False) self.assertEqual(D.__required_keys__, frozenset()) self.assertEqual(D.__optional_keys__, {'x'}) self.assertEqual(Options(), {}) self.assertEqual(Options(log_level=2), {'log_level': 2}) self.assertEqual(Options.__total__, False) self.assertEqual(Options.__required_keys__, frozenset()) self.assertEqual(Options.__optional_keys__, {'log_level', 'log_path'}) def test_optional_keys(self): class Point2Dor3D(Point2D, total=False): z: int assert Point2Dor3D.__required_keys__ == frozenset(['x', 'y']) assert Point2Dor3D.__optional_keys__ == frozenset(['z']) def test_keys_inheritance(self): class BaseAnimal(TypedDict): name: str class Animal(BaseAnimal, total=False): voice: str tail: bool class Cat(Animal): fur_color: str assert BaseAnimal.__required_keys__ == frozenset(['name']) assert BaseAnimal.__optional_keys__ == frozenset([]) assert BaseAnimal.__annotations__ == {'name': str} assert Animal.__required_keys__ == frozenset(['name']) assert Animal.__optional_keys__ == frozenset(['tail', 'voice']) assert Animal.__annotations__ == { 'name': str, 'tail': bool, 'voice': str, } assert Cat.__required_keys__ == frozenset(['name', 'fur_color']) assert Cat.__optional_keys__ == frozenset(['tail', 'voice']) assert Cat.__annotations__ == { 'fur_color': str, 'name': str, 'tail': bool, 'voice': str, } def test_is_typeddict(self): assert is_typeddict(Point2D) is True assert is_typeddict(Union[str, int]) is False # classes, not instances assert is_typeddict(Point2D()) is False def test_get_type_hints(self): self.assertEqual( get_type_hints(Bar), {'a': typing.Optional[int], 'b': int} ) class IOTests(BaseTestCase): def test_io(self): def stuff(a: IO) -> AnyStr: return a.readline() a = stuff.__annotations__['a'] self.assertEqual(a.__parameters__, (AnyStr,)) def test_textio(self): def stuff(a: TextIO) -> str: return a.readline() a = stuff.__annotations__['a'] self.assertEqual(a.__parameters__, ()) def test_binaryio(self): def stuff(a: BinaryIO) -> bytes: return a.readline() a = stuff.__annotations__['a'] self.assertEqual(a.__parameters__, ()) def test_io_submodule(self): with warnings.catch_warnings(record=True) as w: warnings.filterwarnings("default", category=DeprecationWarning) from typing.io import IO, TextIO, BinaryIO, __all__, __name__ self.assertIs(IO, typing.IO) self.assertIs(TextIO, typing.TextIO) self.assertIs(BinaryIO, typing.BinaryIO) self.assertEqual(set(__all__), set(['IO', 'TextIO', 'BinaryIO'])) self.assertEqual(__name__, 'typing.io') self.assertEqual(len(w), 1) class RETests(BaseTestCase): # Much of this is really testing _TypeAlias. def test_basics(self): pat = re.compile('[a-z]+', re.I) self.assertIsSubclass(pat.__class__, Pattern) self.assertIsSubclass(type(pat), Pattern) self.assertIsInstance(pat, Pattern) mat = pat.search('12345abcde.....') self.assertIsSubclass(mat.__class__, Match) self.assertIsSubclass(type(mat), Match) self.assertIsInstance(mat, Match) # these should just work Pattern[Union[str, bytes]] Match[Union[bytes, str]] def test_alias_equality(self): self.assertEqual(Pattern[str], Pattern[str]) self.assertNotEqual(Pattern[str], Pattern[bytes]) self.assertNotEqual(Pattern[str], Match[str]) self.assertNotEqual(Pattern[str], str) def test_errors(self): m = Match[Union[str, bytes]] with self.assertRaises(TypeError): m[str] with self.assertRaises(TypeError): # We don't support isinstance(). isinstance(42, Pattern[str]) with self.assertRaises(TypeError): # We don't support issubclass(). issubclass(Pattern[bytes], Pattern[str]) def test_repr(self): self.assertEqual(repr(Pattern), 'typing.Pattern') self.assertEqual(repr(Pattern[str]), 'typing.Pattern[str]') self.assertEqual(repr(Pattern[bytes]), 'typing.Pattern[bytes]') self.assertEqual(repr(Match), 'typing.Match') self.assertEqual(repr(Match[str]), 'typing.Match[str]') self.assertEqual(repr(Match[bytes]), 'typing.Match[bytes]') def test_re_submodule(self): with warnings.catch_warnings(record=True) as w: warnings.filterwarnings("default", category=DeprecationWarning) from typing.re import Match, Pattern, __all__, __name__ self.assertIs(Match, typing.Match) self.assertIs(Pattern, typing.Pattern) self.assertEqual(set(__all__), set(['Match', 'Pattern'])) self.assertEqual(__name__, 'typing.re') self.assertEqual(len(w), 1) def test_cannot_subclass(self): with self.assertRaises(TypeError) as ex: class A(typing.Match): pass self.assertEqual(str(ex.exception), "type 're.Match' is not an acceptable base type") class AnnotatedTests(BaseTestCase): def test_repr(self): self.assertEqual( repr(Annotated[int, 4, 5]), "typing.Annotated[int, 4, 5]" ) self.assertEqual( repr(Annotated[List[int], 4, 5]), "typing.Annotated[typing.List[int], 4, 5]" ) def test_flatten(self): A = Annotated[Annotated[int, 4], 5] self.assertEqual(A, Annotated[int, 4, 5]) self.assertEqual(A.__metadata__, (4, 5)) self.assertEqual(A.__origin__, int) def test_specialize(self): L = Annotated[List[T], "my decoration"] LI = Annotated[List[int], "my decoration"] self.assertEqual(L[int], Annotated[List[int], "my decoration"]) self.assertEqual(L[int].__metadata__, ("my decoration",)) self.assertEqual(L[int].__origin__, List[int]) with self.assertRaises(TypeError): LI[int] with self.assertRaises(TypeError): L[int, float] def test_hash_eq(self): self.assertEqual(len({Annotated[int, 4, 5], Annotated[int, 4, 5]}), 1) self.assertNotEqual(Annotated[int, 4, 5], Annotated[int, 5, 4]) self.assertNotEqual(Annotated[int, 4, 5], Annotated[str, 4, 5]) self.assertNotEqual(Annotated[int, 4], Annotated[int, 4, 4]) self.assertEqual( {Annotated[int, 4, 5], Annotated[int, 4, 5], Annotated[T, 4, 5]}, {Annotated[int, 4, 5], Annotated[T, 4, 5]} ) def test_instantiate(self): class C: classvar = 4 def __init__(self, x): self.x = x def __eq__(self, other): if not isinstance(other, C): return NotImplemented return other.x == self.x A = Annotated[C, "a decoration"] a = A(5) c = C(5) self.assertEqual(a, c) self.assertEqual(a.x, c.x) self.assertEqual(a.classvar, c.classvar) def test_instantiate_generic(self): MyCount = Annotated[typing.Counter[T], "my decoration"] self.assertEqual(MyCount([4, 4, 5]), {4: 2, 5: 1}) self.assertEqual(MyCount[int]([4, 4, 5]), {4: 2, 5: 1}) def test_cannot_instantiate_forward(self): A = Annotated["int", (5, 6)] with self.assertRaises(TypeError): A(5) def test_cannot_instantiate_type_var(self): A = Annotated[T, (5, 6)] with self.assertRaises(TypeError): A(5) def test_cannot_getattr_typevar(self): with self.assertRaises(AttributeError): Annotated[T, (5, 7)].x def test_attr_passthrough(self): class C: classvar = 4 A = Annotated[C, "a decoration"] self.assertEqual(A.classvar, 4) A.x = 5 self.assertEqual(C.x, 5) def test_hash_eq(self): self.assertEqual(len({Annotated[int, 4, 5], Annotated[int, 4, 5]}), 1) self.assertNotEqual(Annotated[int, 4, 5], Annotated[int, 5, 4]) self.assertNotEqual(Annotated[int, 4, 5], Annotated[str, 4, 5]) self.assertNotEqual(Annotated[int, 4], Annotated[int, 4, 4]) self.assertEqual( {Annotated[int, 4, 5], Annotated[int, 4, 5], Annotated[T, 4, 5]}, {Annotated[int, 4, 5], Annotated[T, 4, 5]} ) def test_cannot_subclass(self): with self.assertRaisesRegex(TypeError, "Cannot subclass .*Annotated"): class C(Annotated): pass def test_cannot_check_instance(self): with self.assertRaises(TypeError): isinstance(5, Annotated[int, "positive"]) def test_cannot_check_subclass(self): with self.assertRaises(TypeError): issubclass(int, Annotated[int, "positive"]) def test_pickle(self): samples = [typing.Any, typing.Union[int, str], typing.Optional[str], Tuple[int, ...], typing.Callable[[str], bytes]] for t in samples: x = Annotated[t, "a"] for prot in range(pickle.HIGHEST_PROTOCOL + 1): with self.subTest(protocol=prot, type=t): pickled = pickle.dumps(x, prot) restored = pickle.loads(pickled) self.assertEqual(x, restored) global _Annotated_test_G class _Annotated_test_G(Generic[T]): x = 1 G = Annotated[_Annotated_test_G[int], "A decoration"] G.foo = 42 G.bar = 'abc' for proto in range(pickle.HIGHEST_PROTOCOL + 1): z = pickle.dumps(G, proto) x = pickle.loads(z) self.assertEqual(x.foo, 42) self.assertEqual(x.bar, 'abc') self.assertEqual(x.x, 1) def test_subst(self): dec = "a decoration" dec2 = "another decoration" S = Annotated[T, dec2] self.assertEqual(S[int], Annotated[int, dec2]) self.assertEqual(S[Annotated[int, dec]], Annotated[int, dec, dec2]) L = Annotated[List[T], dec] self.assertEqual(L[int], Annotated[List[int], dec]) with self.assertRaises(TypeError): L[int, int] self.assertEqual(S[L[int]], Annotated[List[int], dec, dec2]) D = Annotated[typing.Dict[KT, VT], dec] self.assertEqual(D[str, int], Annotated[typing.Dict[str, int], dec]) with self.assertRaises(TypeError): D[int] It = Annotated[int, dec] with self.assertRaises(TypeError): It[None] LI = L[int] with self.assertRaises(TypeError): LI[None] def test_annotated_in_other_types(self): X = List[Annotated[T, 5]] self.assertEqual(X[int], List[Annotated[int, 5]]) def test_annotated_mro(self): class X(Annotated[int, (1, 10)]): ... self.assertEqual(X.__mro__, (X, int, object), "Annotated should be transparent.") class TypeAliasTests(BaseTestCase): def test_canonical_usage_with_variable_annotation(self): Alias: TypeAlias = Employee def test_canonical_usage_with_type_comment(self): Alias = Employee # type: TypeAlias def test_cannot_instantiate(self): with self.assertRaises(TypeError): TypeAlias() def test_no_isinstance(self): with self.assertRaises(TypeError): isinstance(42, TypeAlias) def test_no_issubclass(self): with self.assertRaises(TypeError): issubclass(Employee, TypeAlias) with self.assertRaises(TypeError): issubclass(TypeAlias, Employee) def test_cannot_subclass(self): with self.assertRaises(TypeError): class C(TypeAlias): pass with self.assertRaises(TypeError): class C(type(TypeAlias)): pass def test_repr(self): self.assertEqual(repr(TypeAlias), 'typing.TypeAlias') def test_cannot_subscript(self): with self.assertRaises(TypeError): TypeAlias[int] class ParamSpecTests(BaseTestCase): def test_basic_plain(self): P = ParamSpec('P') self.assertEqual(P, P) self.assertIsInstance(P, ParamSpec) def test_valid_uses(self): P = ParamSpec('P') T = TypeVar('T') C1 = Callable[P, int] self.assertEqual(C1.__args__, (P, int)) self.assertEqual(C1.__parameters__, (P,)) C2 = Callable[P, T] self.assertEqual(C2.__args__, (P, T)) self.assertEqual(C2.__parameters__, (P, T)) # Test collections.abc.Callable too. C3 = collections.abc.Callable[P, int] self.assertEqual(C3.__args__, (P, int)) self.assertEqual(C3.__parameters__, (P,)) C4 = collections.abc.Callable[P, T] self.assertEqual(C4.__args__, (P, T)) self.assertEqual(C4.__parameters__, (P, T)) def test_args_kwargs(self): P = ParamSpec('P') self.assertIn('args', dir(P)) self.assertIn('kwargs', dir(P)) self.assertIsInstance(P.args, ParamSpecArgs) self.assertIsInstance(P.kwargs, ParamSpecKwargs) self.assertIs(P.args.__origin__, P) self.assertIs(P.kwargs.__origin__, P) self.assertEqual(repr(P.args), "P.args") self.assertEqual(repr(P.kwargs), "P.kwargs") def test_user_generics(self): T = TypeVar("T") P = ParamSpec("P") P_2 = ParamSpec("P_2") class X(Generic[T, P]): f: Callable[P, int] x: T G1 = X[int, P_2] self.assertEqual(G1.__args__, (int, P_2)) self.assertEqual(G1.__parameters__, (P_2,)) with self.assertRaisesRegex(TypeError, "few arguments for"): X[int] with self.assertRaisesRegex(TypeError, "many arguments for"): X[int, P_2, str] G2 = X[int, Concatenate[int, P_2]] self.assertEqual(G2.__args__, (int, Concatenate[int, P_2])) self.assertEqual(G2.__parameters__, (P_2,)) G3 = X[int, [int, bool]] self.assertEqual(G3.__args__, (int, (int, bool))) self.assertEqual(G3.__parameters__, ()) G4 = X[int, ...] self.assertEqual(G4.__args__, (int, Ellipsis)) self.assertEqual(G4.__parameters__, ()) class Z(Generic[P]): f: Callable[P, int] G5 = Z[[int, str, bool]] self.assertEqual(G5.__args__, ((int, str, bool),)) self.assertEqual(G5.__parameters__, ()) G6 = Z[int, str, bool] self.assertEqual(G6.__args__, ((int, str, bool),)) self.assertEqual(G6.__parameters__, ()) # G5 and G6 should be equivalent according to the PEP self.assertEqual(G5.__args__, G6.__args__) self.assertEqual(G5.__origin__, G6.__origin__) self.assertEqual(G5.__parameters__, G6.__parameters__) self.assertEqual(G5, G6) G7 = Z[int] self.assertEqual(G7.__args__, ((int,),)) self.assertEqual(G7.__parameters__, ()) with self.assertRaisesRegex(TypeError, "many arguments for"): Z[[int, str], bool] with self.assertRaisesRegex(TypeError, "many arguments for"): Z[P_2, bool] def test_multiple_paramspecs_in_user_generics(self): P = ParamSpec("P") P2 = ParamSpec("P2") class X(Generic[P, P2]): f: Callable[P, int] g: Callable[P2, str] G1 = X[[int, str], [bytes]] G2 = X[[int], [str, bytes]] self.assertNotEqual(G1, G2) self.assertEqual(G1.__args__, ((int, str), (bytes,))) self.assertEqual(G2.__args__, ((int,), (str, bytes))) def test_no_paramspec_in__parameters__(self): # ParamSpec should not be found in __parameters__ # of generics. Usages outside Callable, Concatenate # and Generic are invalid. T = TypeVar("T") P = ParamSpec("P") self.assertNotIn(P, List[P].__parameters__) self.assertIn(T, Tuple[T, P].__parameters__) # Test for consistency with builtin generics. self.assertNotIn(P, list[P].__parameters__) self.assertIn(T, tuple[T, P].__parameters__) self.assertNotIn(P, (list[P] | int).__parameters__) self.assertIn(T, (tuple[T, P] | int).__parameters__) def test_paramspec_in_nested_generics(self): # Although ParamSpec should not be found in __parameters__ of most # generics, they probably should be found when nested in # a valid location. T = TypeVar("T") P = ParamSpec("P") C1 = Callable[P, T] G1 = List[C1] G2 = list[C1] G3 = list[C1] | int self.assertEqual(G1.__parameters__, (P, T)) self.assertEqual(G2.__parameters__, (P, T)) self.assertEqual(G3.__parameters__, (P, T)) class ConcatenateTests(BaseTestCase): def test_basics(self): P = ParamSpec('P') class MyClass: ... c = Concatenate[MyClass, P] self.assertNotEqual(c, Concatenate) def test_valid_uses(self): P = ParamSpec('P') T = TypeVar('T') C1 = Callable[Concatenate[int, P], int] self.assertEqual(C1.__args__, (Concatenate[int, P], int)) self.assertEqual(C1.__parameters__, (P,)) C2 = Callable[Concatenate[int, T, P], T] self.assertEqual(C2.__args__, (Concatenate[int, T, P], T)) self.assertEqual(C2.__parameters__, (T, P)) # Test collections.abc.Callable too. C3 = collections.abc.Callable[Concatenate[int, P], int] self.assertEqual(C3.__args__, (Concatenate[int, P], int)) self.assertEqual(C3.__parameters__, (P,)) C4 = collections.abc.Callable[Concatenate[int, T, P], T] self.assertEqual(C4.__args__, (Concatenate[int, T, P], T)) self.assertEqual(C4.__parameters__, (T, P)) class TypeGuardTests(BaseTestCase): def test_basics(self): TypeGuard[int] # OK def foo(arg) -> TypeGuard[int]: ... self.assertEqual(gth(foo), {'return': TypeGuard[int]}) def test_repr(self): self.assertEqual(repr(TypeGuard), 'typing.TypeGuard') cv = TypeGuard[int] self.assertEqual(repr(cv), 'typing.TypeGuard[int]') cv = TypeGuard[Employee] self.assertEqual(repr(cv), 'typing.TypeGuard[%s.Employee]' % __name__) cv = TypeGuard[tuple[int]] self.assertEqual(repr(cv), 'typing.TypeGuard[tuple[int]]') def test_cannot_subclass(self): with self.assertRaises(TypeError): class C(type(TypeGuard)): pass with self.assertRaises(TypeError): class C(type(TypeGuard[int])): pass def test_cannot_init(self): with self.assertRaises(TypeError): TypeGuard() with self.assertRaises(TypeError): type(TypeGuard)() with self.assertRaises(TypeError): type(TypeGuard[Optional[int]])() def test_no_isinstance(self): with self.assertRaises(TypeError): isinstance(1, TypeGuard[int]) with self.assertRaises(TypeError): issubclass(int, TypeGuard) SpecialAttrsP = typing.ParamSpec('SpecialAttrsP') SpecialAttrsT = typing.TypeVar('SpecialAttrsT', int, float, complex) class SpecialAttrsTests(BaseTestCase): def test_special_attrs(self): cls_to_check = { # ABC classes typing.AbstractSet: 'AbstractSet', typing.AsyncContextManager: 'AsyncContextManager', typing.AsyncGenerator: 'AsyncGenerator', typing.AsyncIterable: 'AsyncIterable', typing.AsyncIterator: 'AsyncIterator', typing.Awaitable: 'Awaitable', typing.ByteString: 'ByteString', typing.Callable: 'Callable', typing.ChainMap: 'ChainMap', typing.Collection: 'Collection', typing.Container: 'Container', typing.ContextManager: 'ContextManager', typing.Coroutine: 'Coroutine', typing.Counter: 'Counter', typing.DefaultDict: 'DefaultDict', typing.Deque: 'Deque', typing.Dict: 'Dict', typing.FrozenSet: 'FrozenSet', typing.Generator: 'Generator', typing.Hashable: 'Hashable', typing.ItemsView: 'ItemsView', typing.Iterable: 'Iterable', typing.Iterator: 'Iterator', typing.KeysView: 'KeysView', typing.List: 'List', typing.Mapping: 'Mapping', typing.MappingView: 'MappingView', typing.MutableMapping: 'MutableMapping', typing.MutableSequence: 'MutableSequence', typing.MutableSet: 'MutableSet', typing.OrderedDict: 'OrderedDict', typing.Reversible: 'Reversible', typing.Sequence: 'Sequence', typing.Set: 'Set', typing.Sized: 'Sized', typing.Tuple: 'Tuple', typing.Type: 'Type', typing.ValuesView: 'ValuesView', # Subscribed ABC classes typing.AbstractSet[Any]: 'AbstractSet', typing.AsyncContextManager[Any]: 'AsyncContextManager', typing.AsyncGenerator[Any, Any]: 'AsyncGenerator', typing.AsyncIterable[Any]: 'AsyncIterable', typing.AsyncIterator[Any]: 'AsyncIterator', typing.Awaitable[Any]: 'Awaitable', typing.Callable[[], Any]: 'Callable', typing.Callable[..., Any]: 'Callable', typing.ChainMap[Any, Any]: 'ChainMap', typing.Collection[Any]: 'Collection', typing.Container[Any]: 'Container', typing.ContextManager[Any]: 'ContextManager', typing.Coroutine[Any, Any, Any]: 'Coroutine', typing.Counter[Any]: 'Counter', typing.DefaultDict[Any, Any]: 'DefaultDict', typing.Deque[Any]: 'Deque', typing.Dict[Any, Any]: 'Dict', typing.FrozenSet[Any]: 'FrozenSet', typing.Generator[Any, Any, Any]: 'Generator', typing.ItemsView[Any, Any]: 'ItemsView', typing.Iterable[Any]: 'Iterable', typing.Iterator[Any]: 'Iterator', typing.KeysView[Any]: 'KeysView', typing.List[Any]: 'List', typing.Mapping[Any, Any]: 'Mapping', typing.MappingView[Any]: 'MappingView', typing.MutableMapping[Any, Any]: 'MutableMapping', typing.MutableSequence[Any]: 'MutableSequence', typing.MutableSet[Any]: 'MutableSet', typing.OrderedDict[Any, Any]: 'OrderedDict', typing.Reversible[Any]: 'Reversible', typing.Sequence[Any]: 'Sequence', typing.Set[Any]: 'Set', typing.Tuple[Any]: 'Tuple', typing.Tuple[Any, ...]: 'Tuple', typing.Type[Any]: 'Type', typing.ValuesView[Any]: 'ValuesView', # Special Forms typing.Annotated: 'Annotated', typing.Any: 'Any', typing.ClassVar: 'ClassVar', typing.Concatenate: 'Concatenate', typing.Final: 'Final', typing.ForwardRef: 'ForwardRef', typing.Literal: 'Literal', typing.NewType: 'NewType', typing.NoReturn: 'NoReturn', typing.Optional: 'Optional', typing.TypeAlias: 'TypeAlias', typing.TypeGuard: 'TypeGuard', typing.TypeVar: 'TypeVar', typing.Union: 'Union', # Subscribed special forms typing.Annotated[Any, "Annotation"]: 'Annotated', typing.ClassVar[Any]: 'ClassVar', typing.Concatenate[Any, SpecialAttrsP]: 'Concatenate', typing.Final[Any]: 'Final', typing.Literal[Any]: 'Literal', typing.Optional[Any]: 'Optional', typing.TypeGuard[Any]: 'TypeGuard', typing.Union[Any]: 'Any', typing.Union[int, float]: 'Union', # Incompatible special forms (tested in test_special_attrs2) # - typing.ForwardRef('set[Any]') # - typing.NewType('TypeName', Any) # - typing.ParamSpec('SpecialAttrsP') # - typing.TypeVar('T') } for cls, name in cls_to_check.items(): with self.subTest(cls=cls): self.assertEqual(cls.__name__, name, str(cls)) self.assertEqual(cls.__qualname__, name, str(cls)) self.assertEqual(cls.__module__, 'typing', str(cls)) for proto in range(pickle.HIGHEST_PROTOCOL + 1): s = pickle.dumps(cls, proto) loaded = pickle.loads(s) self.assertIs(cls, loaded) TypeName = typing.NewType('SpecialAttrsTests.TypeName', Any) def test_special_attrs2(self): # Forward refs provide a different introspection API. __name__ and # __qualname__ make little sense for forward refs as they can store # complex typing expressions. fr = typing.ForwardRef('set[Any]') self.assertFalse(hasattr(fr, '__name__')) self.assertFalse(hasattr(fr, '__qualname__')) self.assertEqual(fr.__module__, 'typing') # Forward refs are currently unpicklable. for proto in range(pickle.HIGHEST_PROTOCOL + 1): with self.assertRaises(TypeError) as exc: pickle.dumps(fr, proto) self.assertEqual(SpecialAttrsTests.TypeName.__name__, 'TypeName') self.assertEqual( SpecialAttrsTests.TypeName.__qualname__, 'SpecialAttrsTests.TypeName', ) self.assertEqual( SpecialAttrsTests.TypeName.__module__, 'test.test_typing', ) # NewTypes are picklable assuming correct qualname information. for proto in range(pickle.HIGHEST_PROTOCOL + 1): s = pickle.dumps(SpecialAttrsTests.TypeName, proto) loaded = pickle.loads(s) self.assertIs(SpecialAttrsTests.TypeName, loaded) # Type variables don't support non-global instantiation per PEP 484 # restriction that "The argument to TypeVar() must be a string equal # to the variable name to which it is assigned". Thus, providing # __qualname__ is unnecessary. self.assertEqual(SpecialAttrsT.__name__, 'SpecialAttrsT') self.assertFalse(hasattr(SpecialAttrsT, '__qualname__')) self.assertEqual(SpecialAttrsT.__module__, 'test.test_typing') # Module-level type variables are picklable. for proto in range(pickle.HIGHEST_PROTOCOL + 1): s = pickle.dumps(SpecialAttrsT, proto) loaded = pickle.loads(s) self.assertIs(SpecialAttrsT, loaded) self.assertEqual(SpecialAttrsP.__name__, 'SpecialAttrsP') self.assertFalse(hasattr(SpecialAttrsP, '__qualname__')) self.assertEqual(SpecialAttrsP.__module__, 'test.test_typing') # Module-level ParamSpecs are picklable. for proto in range(pickle.HIGHEST_PROTOCOL + 1): s = pickle.dumps(SpecialAttrsP, proto) loaded = pickle.loads(s) self.assertIs(SpecialAttrsP, loaded) class AllTests(BaseTestCase): """Tests for __all__.""" def test_all(self): from typing import __all__ as a # Just spot-check the first and last of every category. self.assertIn('AbstractSet', a) self.assertIn('ValuesView', a) self.assertIn('cast', a) self.assertIn('overload', a) if hasattr(contextlib, 'AbstractContextManager'): self.assertIn('ContextManager', a) # Check that io and re are not exported. self.assertNotIn('io', a) self.assertNotIn('re', a) # Spot-check that stdlib modules aren't exported. self.assertNotIn('os', a) self.assertNotIn('sys', a) # Check that Text is defined. self.assertIn('Text', a) # Check previously missing classes. self.assertIn('SupportsBytes', a) self.assertIn('SupportsComplex', a) def test_all_exported_names(self): import typing actual_all = set(typing.__all__) computed_all = { k for k, v in vars(typing).items() # explicitly exported, not a thing with __module__ if k in actual_all or ( # avoid private names not k.startswith('_') and k not in {'io', 're'} and # there's a few types and metaclasses that aren't exported not k.endswith(('Meta', '_contra', '_co')) and not k.upper() == k and # but export all things that have __module__ == 'typing' getattr(v, '__module__', None) == typing.__name__ ) } self.assertSetEqual(computed_all, actual_all) if __name__ == '__main__': main()
import contextlib import collections import pickle import re import sys import warnings from unittest import TestCase, main, skipUnless, skip from copy import copy, deepcopy from typing import Any, NoReturn from typing import TypeVar, AnyStr from typing import T, KT, VT # Not in __all__. from typing import Union, Optional, Literal from typing import Tuple, List, Dict, MutableMapping from typing import Callable from typing import Generic, ClassVar, Final, final, Protocol from typing import cast, runtime_checkable from typing import get_type_hints from typing import get_origin, get_args from typing import is_typeddict from typing import no_type_check, no_type_check_decorator from typing import Type from typing import NewType from typing import NamedTuple, TypedDict from typing import IO, TextIO, BinaryIO from typing import Pattern, Match from typing import Annotated, ForwardRef from typing import TypeAlias from typing import ParamSpec, Concatenate, ParamSpecArgs, ParamSpecKwargs from typing import TypeGuard import abc import typing import weakref import types from test.support import import_helper from test import mod_generics_cache from test import _typed_dict_helper py_typing = import_helper.import_fresh_module('typing', blocked=['_typing']) c_typing = import_helper.import_fresh_module('typing', fresh=['_typing']) class BaseTestCase(TestCase): def assertIsSubclass(self, cls, class_or_tuple, msg=None): if not issubclass(cls, class_or_tuple): message = '%r is not a subclass of %r' % (cls, class_or_tuple) if msg is not None: message += ' : %s' % msg raise self.failureException(message) def assertNotIsSubclass(self, cls, class_or_tuple, msg=None): if issubclass(cls, class_or_tuple): message = '%r is a subclass of %r' % (cls, class_or_tuple) if msg is not None: message += ' : %s' % msg raise self.failureException(message) def clear_caches(self): for f in typing._cleanups: f() class Employee: pass class Manager(Employee): pass class Founder(Employee): pass class ManagingFounder(Manager, Founder): pass class AnyTests(BaseTestCase): def test_any_instance_type_error(self): with self.assertRaises(TypeError): isinstance(42, Any) def test_any_subclass_type_error(self): with self.assertRaises(TypeError): issubclass(Employee, Any) with self.assertRaises(TypeError): issubclass(Any, Employee) def test_repr(self): self.assertEqual(repr(Any), 'typing.Any') def test_errors(self): with self.assertRaises(TypeError): issubclass(42, Any) with self.assertRaises(TypeError): Any[int] # Any is not a generic type. def test_cannot_subclass(self): with self.assertRaises(TypeError): class A(Any): pass with self.assertRaises(TypeError): class A(type(Any)): pass def test_cannot_instantiate(self): with self.assertRaises(TypeError): Any() with self.assertRaises(TypeError): type(Any)() def test_any_works_with_alias(self): # These expressions must simply not fail. typing.Match[Any] typing.Pattern[Any] typing.IO[Any] class NoReturnTests(BaseTestCase): def test_noreturn_instance_type_error(self): with self.assertRaises(TypeError): isinstance(42, NoReturn) def test_noreturn_subclass_type_error(self): with self.assertRaises(TypeError): issubclass(Employee, NoReturn) with self.assertRaises(TypeError): issubclass(NoReturn, Employee) def test_repr(self): self.assertEqual(repr(NoReturn), 'typing.NoReturn') def test_not_generic(self): with self.assertRaises(TypeError): NoReturn[int] def test_cannot_subclass(self): with self.assertRaises(TypeError): class A(NoReturn): pass with self.assertRaises(TypeError): class A(type(NoReturn)): pass def test_cannot_instantiate(self): with self.assertRaises(TypeError): NoReturn() with self.assertRaises(TypeError): type(NoReturn)() class TypeVarTests(BaseTestCase): def test_basic_plain(self): T = TypeVar('T') # T equals itself. self.assertEqual(T, T) # T is an instance of TypeVar self.assertIsInstance(T, TypeVar) def test_typevar_instance_type_error(self): T = TypeVar('T') with self.assertRaises(TypeError): isinstance(42, T) def test_typevar_subclass_type_error(self): T = TypeVar('T') with self.assertRaises(TypeError): issubclass(int, T) with self.assertRaises(TypeError): issubclass(T, int) def test_constrained_error(self): with self.assertRaises(TypeError): X = TypeVar('X', int) X def test_union_unique(self): X = TypeVar('X') Y = TypeVar('Y') self.assertNotEqual(X, Y) self.assertEqual(Union[X], X) self.assertNotEqual(Union[X], Union[X, Y]) self.assertEqual(Union[X, X], X) self.assertNotEqual(Union[X, int], Union[X]) self.assertNotEqual(Union[X, int], Union[int]) self.assertEqual(Union[X, int].__args__, (X, int)) self.assertEqual(Union[X, int].__parameters__, (X,)) self.assertIs(Union[X, int].__origin__, Union) def test_or(self): X = TypeVar('X') # use a string because str doesn't implement # __or__/__ror__ itself self.assertEqual(X | "x", Union[X, "x"]) self.assertEqual("x" | X, Union["x", X]) # make sure the order is correct self.assertEqual(get_args(X | "x"), (X, ForwardRef("x"))) self.assertEqual(get_args("x" | X), (ForwardRef("x"), X)) def test_union_constrained(self): A = TypeVar('A', str, bytes) self.assertNotEqual(Union[A, str], Union[A]) def test_repr(self): self.assertEqual(repr(T), '~T') self.assertEqual(repr(KT), '~KT') self.assertEqual(repr(VT), '~VT') self.assertEqual(repr(AnyStr), '~AnyStr') T_co = TypeVar('T_co', covariant=True) self.assertEqual(repr(T_co), '+T_co') T_contra = TypeVar('T_contra', contravariant=True) self.assertEqual(repr(T_contra), '-T_contra') def test_no_redefinition(self): self.assertNotEqual(TypeVar('T'), TypeVar('T')) self.assertNotEqual(TypeVar('T', int, str), TypeVar('T', int, str)) def test_cannot_subclass_vars(self): with self.assertRaises(TypeError): class V(TypeVar('T')): pass def test_cannot_subclass_var_itself(self): with self.assertRaises(TypeError): class V(TypeVar): pass def test_cannot_instantiate_vars(self): with self.assertRaises(TypeError): TypeVar('A')() def test_bound_errors(self): with self.assertRaises(TypeError): TypeVar('X', bound=42) with self.assertRaises(TypeError): TypeVar('X', str, float, bound=Employee) def test_missing__name__(self): # See bpo-39942 code = ("import typing\n" "T = typing.TypeVar('T')\n" ) exec(code, {}) def test_no_bivariant(self): with self.assertRaises(ValueError): TypeVar('T', covariant=True, contravariant=True) class UnionTests(BaseTestCase): def test_basics(self): u = Union[int, float] self.assertNotEqual(u, Union) def test_subclass_error(self): with self.assertRaises(TypeError): issubclass(int, Union) with self.assertRaises(TypeError): issubclass(Union, int) with self.assertRaises(TypeError): issubclass(Union[int, str], int) def test_union_any(self): u = Union[Any] self.assertEqual(u, Any) u1 = Union[int, Any] u2 = Union[Any, int] u3 = Union[Any, object] self.assertEqual(u1, u2) self.assertNotEqual(u1, Any) self.assertNotEqual(u2, Any) self.assertNotEqual(u3, Any) def test_union_object(self): u = Union[object] self.assertEqual(u, object) u1 = Union[int, object] u2 = Union[object, int] self.assertEqual(u1, u2) self.assertNotEqual(u1, object) self.assertNotEqual(u2, object) def test_unordered(self): u1 = Union[int, float] u2 = Union[float, int] self.assertEqual(u1, u2) def test_single_class_disappears(self): t = Union[Employee] self.assertIs(t, Employee) def test_base_class_kept(self): u = Union[Employee, Manager] self.assertNotEqual(u, Employee) self.assertIn(Employee, u.__args__) self.assertIn(Manager, u.__args__) def test_union_union(self): u = Union[int, float] v = Union[u, Employee] self.assertEqual(v, Union[int, float, Employee]) def test_repr(self): self.assertEqual(repr(Union), 'typing.Union') u = Union[Employee, int] self.assertEqual(repr(u), 'typing.Union[%s.Employee, int]' % __name__) u = Union[int, Employee] self.assertEqual(repr(u), 'typing.Union[int, %s.Employee]' % __name__) T = TypeVar('T') u = Union[T, int][int] self.assertEqual(repr(u), repr(int)) u = Union[List[int], int] self.assertEqual(repr(u), 'typing.Union[typing.List[int], int]') u = Union[list[int], dict[str, float]] self.assertEqual(repr(u), 'typing.Union[list[int], dict[str, float]]') u = Union[int | float] self.assertEqual(repr(u), 'typing.Union[int, float]') def test_cannot_subclass(self): with self.assertRaises(TypeError): class C(Union): pass with self.assertRaises(TypeError): class C(type(Union)): pass with self.assertRaises(TypeError): class C(Union[int, str]): pass def test_cannot_instantiate(self): with self.assertRaises(TypeError): Union() with self.assertRaises(TypeError): type(Union)() u = Union[int, float] with self.assertRaises(TypeError): u() with self.assertRaises(TypeError): type(u)() def test_union_generalization(self): self.assertFalse(Union[str, typing.Iterable[int]] == str) self.assertFalse(Union[str, typing.Iterable[int]] == typing.Iterable[int]) self.assertIn(str, Union[str, typing.Iterable[int]].__args__) self.assertIn(typing.Iterable[int], Union[str, typing.Iterable[int]].__args__) def test_union_compare_other(self): self.assertNotEqual(Union, object) self.assertNotEqual(Union, Any) self.assertNotEqual(ClassVar, Union) self.assertNotEqual(Optional, Union) self.assertNotEqual([None], Optional) self.assertNotEqual(Optional, typing.Mapping) self.assertNotEqual(Optional[typing.MutableMapping], Union) def test_optional(self): o = Optional[int] u = Union[int, None] self.assertEqual(o, u) def test_empty(self): with self.assertRaises(TypeError): Union[()] def test_no_eval_union(self): u = Union[int, str] def f(x: u): ... self.assertIs(get_type_hints(f)['x'], u) def test_function_repr_union(self): def fun() -> int: ... self.assertEqual(repr(Union[fun, int]), 'typing.Union[fun, int]') def test_union_str_pattern(self): # Shouldn't crash; see http://bugs.python.org/issue25390 A = Union[str, Pattern] A def test_etree(self): # See https://github.com/python/typing/issues/229 # (Only relevant for Python 2.) from xml.etree.ElementTree import Element Union[Element, str] # Shouldn't crash def Elem(*args): return Element(*args) Union[Elem, str] # Nor should this class TupleTests(BaseTestCase): def test_basics(self): with self.assertRaises(TypeError): issubclass(Tuple, Tuple[int, str]) with self.assertRaises(TypeError): issubclass(tuple, Tuple[int, str]) class TP(tuple): ... self.assertIsSubclass(tuple, Tuple) self.assertIsSubclass(TP, Tuple) def test_equality(self): self.assertEqual(Tuple[int], Tuple[int]) self.assertEqual(Tuple[int, ...], Tuple[int, ...]) self.assertNotEqual(Tuple[int], Tuple[int, int]) self.assertNotEqual(Tuple[int], Tuple[int, ...]) def test_tuple_subclass(self): class MyTuple(tuple): pass self.assertIsSubclass(MyTuple, Tuple) def test_tuple_instance_type_error(self): with self.assertRaises(TypeError): isinstance((0, 0), Tuple[int, int]) self.assertIsInstance((0, 0), Tuple) def test_repr(self): self.assertEqual(repr(Tuple), 'typing.Tuple') self.assertEqual(repr(Tuple[()]), 'typing.Tuple[()]') self.assertEqual(repr(Tuple[int, float]), 'typing.Tuple[int, float]') self.assertEqual(repr(Tuple[int, ...]), 'typing.Tuple[int, ...]') self.assertEqual(repr(Tuple[list[int]]), 'typing.Tuple[list[int]]') def test_errors(self): with self.assertRaises(TypeError): issubclass(42, Tuple) with self.assertRaises(TypeError): issubclass(42, Tuple[int]) class BaseCallableTests: def test_self_subclass(self): Callable = self.Callable with self.assertRaises(TypeError): issubclass(types.FunctionType, Callable[[int], int]) self.assertIsSubclass(types.FunctionType, Callable) def test_eq_hash(self): Callable = self.Callable C = Callable[[int], int] self.assertEqual(C, Callable[[int], int]) self.assertEqual(len({C, Callable[[int], int]}), 1) self.assertNotEqual(C, Callable[[int], str]) self.assertNotEqual(C, Callable[[str], int]) self.assertNotEqual(C, Callable[[int, int], int]) self.assertNotEqual(C, Callable[[], int]) self.assertNotEqual(C, Callable[..., int]) self.assertNotEqual(C, Callable) def test_cannot_instantiate(self): Callable = self.Callable with self.assertRaises(TypeError): Callable() with self.assertRaises(TypeError): type(Callable)() c = Callable[[int], str] with self.assertRaises(TypeError): c() with self.assertRaises(TypeError): type(c)() def test_callable_wrong_forms(self): Callable = self.Callable with self.assertRaises(TypeError): Callable[int] def test_callable_instance_works(self): Callable = self.Callable def f(): pass self.assertIsInstance(f, Callable) self.assertNotIsInstance(None, Callable) def test_callable_instance_type_error(self): Callable = self.Callable def f(): pass with self.assertRaises(TypeError): self.assertIsInstance(f, Callable[[], None]) with self.assertRaises(TypeError): self.assertIsInstance(f, Callable[[], Any]) with self.assertRaises(TypeError): self.assertNotIsInstance(None, Callable[[], None]) with self.assertRaises(TypeError): self.assertNotIsInstance(None, Callable[[], Any]) def test_repr(self): Callable = self.Callable fullname = f'{Callable.__module__}.Callable' ct0 = Callable[[], bool] self.assertEqual(repr(ct0), f'{fullname}[[], bool]') ct2 = Callable[[str, float], int] self.assertEqual(repr(ct2), f'{fullname}[[str, float], int]') ctv = Callable[..., str] self.assertEqual(repr(ctv), f'{fullname}[..., str]') ct3 = Callable[[str, float], list[int]] self.assertEqual(repr(ct3), f'{fullname}[[str, float], list[int]]') def test_callable_with_ellipsis(self): Callable = self.Callable def foo(a: Callable[..., T]): pass self.assertEqual(get_type_hints(foo, globals(), locals()), {'a': Callable[..., T]}) def test_ellipsis_in_generic(self): Callable = self.Callable # Shouldn't crash; see https://github.com/python/typing/issues/259 typing.List[Callable[..., str]] def test_basic(self): Callable = self.Callable alias = Callable[[int, str], float] if Callable is collections.abc.Callable: self.assertIsInstance(alias, types.GenericAlias) self.assertIs(alias.__origin__, collections.abc.Callable) self.assertEqual(alias.__args__, (int, str, float)) self.assertEqual(alias.__parameters__, ()) def test_weakref(self): Callable = self.Callable alias = Callable[[int, str], float] self.assertEqual(weakref.ref(alias)(), alias) def test_pickle(self): Callable = self.Callable alias = Callable[[int, str], float] for proto in range(pickle.HIGHEST_PROTOCOL + 1): s = pickle.dumps(alias, proto) loaded = pickle.loads(s) self.assertEqual(alias.__origin__, loaded.__origin__) self.assertEqual(alias.__args__, loaded.__args__) self.assertEqual(alias.__parameters__, loaded.__parameters__) def test_var_substitution(self): Callable = self.Callable fullname = f"{Callable.__module__}.Callable" C1 = Callable[[int, T], T] C2 = Callable[[KT, T], VT] C3 = Callable[..., T] self.assertEqual(C1[str], Callable[[int, str], str]) self.assertEqual(C2[int, float, str], Callable[[int, float], str]) self.assertEqual(C3[int], Callable[..., int]) # multi chaining C4 = C2[int, VT, str] self.assertEqual(repr(C4), f"{fullname}[[int, ~VT], str]") self.assertEqual(repr(C4[dict]), f"{fullname}[[int, dict], str]") self.assertEqual(C4[dict], Callable[[int, dict], str]) # substitute a nested GenericAlias (both typing and the builtin # version) C5 = Callable[[typing.List[T], tuple[KT, T], VT], int] self.assertEqual(C5[int, str, float], Callable[[typing.List[int], tuple[str, int], float], int]) def test_type_erasure(self): Callable = self.Callable class C1(Callable): def __call__(self): return None a = C1[[int], T] self.assertIs(a().__class__, C1) self.assertEqual(a().__orig_class__, C1[[int], T]) def test_paramspec(self): Callable = self.Callable fullname = f"{Callable.__module__}.Callable" P = ParamSpec('P') P2 = ParamSpec('P2') C1 = Callable[P, T] # substitution self.assertEqual(C1[[int], str], Callable[[int], str]) self.assertEqual(C1[[int, str], str], Callable[[int, str], str]) self.assertEqual(C1[[], str], Callable[[], str]) self.assertEqual(C1[..., str], Callable[..., str]) self.assertEqual(C1[P2, str], Callable[P2, str]) self.assertEqual(C1[Concatenate[int, P2], str], Callable[Concatenate[int, P2], str]) self.assertEqual(repr(C1), f"{fullname}[~P, ~T]") self.assertEqual(repr(C1[[int, str], str]), f"{fullname}[[int, str], str]") with self.assertRaises(TypeError): C1[int, str] C2 = Callable[P, int] self.assertEqual(C2[[int]], Callable[[int], int]) self.assertEqual(C2[[int, str]], Callable[[int, str], int]) self.assertEqual(C2[[]], Callable[[], int]) self.assertEqual(C2[...], Callable[..., int]) self.assertEqual(C2[P2], Callable[P2, int]) self.assertEqual(C2[Concatenate[int, P2]], Callable[Concatenate[int, P2], int]) # special case in PEP 612 where # X[int, str, float] == X[[int, str, float]] self.assertEqual(C2[int], Callable[[int], int]) self.assertEqual(C2[int, str], Callable[[int, str], int]) self.assertEqual(repr(C2), f"{fullname}[~P, int]") self.assertEqual(repr(C2[int, str]), f"{fullname}[[int, str], int]") def test_concatenate(self): Callable = self.Callable fullname = f"{Callable.__module__}.Callable" P = ParamSpec('P') C1 = Callable[typing.Concatenate[int, P], int] self.assertEqual(repr(C1), f"{fullname}[typing.Concatenate[int, ~P], int]") def test_errors(self): Callable = self.Callable alias = Callable[[int, str], float] with self.assertRaisesRegex(TypeError, "is not a generic class"): alias[int] P = ParamSpec('P') C1 = Callable[P, T] with self.assertRaisesRegex(TypeError, "many arguments for"): C1[int, str, str] with self.assertRaisesRegex(TypeError, "few arguments for"): C1[int] class TypingCallableTests(BaseCallableTests, BaseTestCase): Callable = typing.Callable def test_consistency(self): # bpo-42195 # Testing collections.abc.Callable's consistency with typing.Callable c1 = typing.Callable[[int, str], dict] c2 = collections.abc.Callable[[int, str], dict] self.assertEqual(c1.__args__, c2.__args__) self.assertEqual(hash(c1.__args__), hash(c2.__args__)) class CollectionsCallableTests(BaseCallableTests, BaseTestCase): Callable = collections.abc.Callable class LiteralTests(BaseTestCase): def test_basics(self): # All of these are allowed. Literal[1] Literal[1, 2, 3] Literal["x", "y", "z"] Literal[None] Literal[True] Literal[1, "2", False] Literal[Literal[1, 2], Literal[4, 5]] Literal[b"foo", u"bar"] def test_illegal_parameters_do_not_raise_runtime_errors(self): # Type checkers should reject these types, but we do not # raise errors at runtime to maintain maximum flexibility. Literal[int] Literal[3j + 2, ..., ()] Literal[{"foo": 3, "bar": 4}] Literal[T] def test_literals_inside_other_types(self): List[Literal[1, 2, 3]] List[Literal[("foo", "bar", "baz")]] def test_repr(self): self.assertEqual(repr(Literal[1]), "typing.Literal[1]") self.assertEqual(repr(Literal[1, True, "foo"]), "typing.Literal[1, True, 'foo']") self.assertEqual(repr(Literal[int]), "typing.Literal[int]") self.assertEqual(repr(Literal), "typing.Literal") self.assertEqual(repr(Literal[None]), "typing.Literal[None]") self.assertEqual(repr(Literal[1, 2, 3, 3]), "typing.Literal[1, 2, 3]") def test_cannot_init(self): with self.assertRaises(TypeError): Literal() with self.assertRaises(TypeError): Literal[1]() with self.assertRaises(TypeError): type(Literal)() with self.assertRaises(TypeError): type(Literal[1])() def test_no_isinstance_or_issubclass(self): with self.assertRaises(TypeError): isinstance(1, Literal[1]) with self.assertRaises(TypeError): isinstance(int, Literal[1]) with self.assertRaises(TypeError): issubclass(1, Literal[1]) with self.assertRaises(TypeError): issubclass(int, Literal[1]) def test_no_subclassing(self): with self.assertRaises(TypeError): class Foo(Literal[1]): pass with self.assertRaises(TypeError): class Bar(Literal): pass def test_no_multiple_subscripts(self): with self.assertRaises(TypeError): Literal[1][1] def test_equal(self): self.assertNotEqual(Literal[0], Literal[False]) self.assertNotEqual(Literal[True], Literal[1]) self.assertNotEqual(Literal[1], Literal[2]) self.assertNotEqual(Literal[1, True], Literal[1]) self.assertEqual(Literal[1], Literal[1]) self.assertEqual(Literal[1, 2], Literal[2, 1]) self.assertEqual(Literal[1, 2, 3], Literal[1, 2, 3, 3]) def test_hash(self): self.assertEqual(hash(Literal[1]), hash(Literal[1])) self.assertEqual(hash(Literal[1, 2]), hash(Literal[2, 1])) self.assertEqual(hash(Literal[1, 2, 3]), hash(Literal[1, 2, 3, 3])) def test_args(self): self.assertEqual(Literal[1, 2, 3].__args__, (1, 2, 3)) self.assertEqual(Literal[1, 2, 3, 3].__args__, (1, 2, 3)) self.assertEqual(Literal[1, Literal[2], Literal[3, 4]].__args__, (1, 2, 3, 4)) # Mutable arguments will not be deduplicated self.assertEqual(Literal[[], []].__args__, ([], [])) def test_flatten(self): l1 = Literal[Literal[1], Literal[2], Literal[3]] l2 = Literal[Literal[1, 2], 3] l3 = Literal[Literal[1, 2, 3]] for l in l1, l2, l3: self.assertEqual(l, Literal[1, 2, 3]) self.assertEqual(l.__args__, (1, 2, 3)) XK = TypeVar('XK', str, bytes) XV = TypeVar('XV') class SimpleMapping(Generic[XK, XV]): def __getitem__(self, key: XK) -> XV: ... def __setitem__(self, key: XK, value: XV): ... def get(self, key: XK, default: XV = None) -> XV: ... class MySimpleMapping(SimpleMapping[XK, XV]): def __init__(self): self.store = {} def __getitem__(self, key: str): return self.store[key] def __setitem__(self, key: str, value): self.store[key] = value def get(self, key: str, default=None): try: return self.store[key] except KeyError: return default class Coordinate(Protocol): x: int y: int @runtime_checkable class Point(Coordinate, Protocol): label: str class MyPoint: x: int y: int label: str class XAxis(Protocol): x: int class YAxis(Protocol): y: int @runtime_checkable class Position(XAxis, YAxis, Protocol): pass @runtime_checkable class Proto(Protocol): attr: int def meth(self, arg: str) -> int: ... class Concrete(Proto): pass class Other: attr: int = 1 def meth(self, arg: str) -> int: if arg == 'this': return 1 return 0 class NT(NamedTuple): x: int y: int @runtime_checkable class HasCallProtocol(Protocol): __call__: typing.Callable class ProtocolTests(BaseTestCase): def test_basic_protocol(self): @runtime_checkable class P(Protocol): def meth(self): pass class C: pass class D: def meth(self): pass def f(): pass self.assertIsSubclass(D, P) self.assertIsInstance(D(), P) self.assertNotIsSubclass(C, P) self.assertNotIsInstance(C(), P) self.assertNotIsSubclass(types.FunctionType, P) self.assertNotIsInstance(f, P) def test_everything_implements_empty_protocol(self): @runtime_checkable class Empty(Protocol): pass class C: pass def f(): pass for thing in (object, type, tuple, C, types.FunctionType): self.assertIsSubclass(thing, Empty) for thing in (object(), 1, (), typing, f): self.assertIsInstance(thing, Empty) def test_function_implements_protocol(self): def f(): pass self.assertIsInstance(f, HasCallProtocol) def test_no_inheritance_from_nominal(self): class C: pass class BP(Protocol): pass with self.assertRaises(TypeError): class P(C, Protocol): pass with self.assertRaises(TypeError): class P(Protocol, C): pass with self.assertRaises(TypeError): class P(BP, C, Protocol): pass class D(BP, C): pass class E(C, BP): pass self.assertNotIsInstance(D(), E) self.assertNotIsInstance(E(), D) def test_no_instantiation(self): class P(Protocol): pass with self.assertRaises(TypeError): P() class C(P): pass self.assertIsInstance(C(), C) with self.assertRaises(TypeError): C(42) T = TypeVar('T') class PG(Protocol[T]): pass with self.assertRaises(TypeError): PG() with self.assertRaises(TypeError): PG[int]() with self.assertRaises(TypeError): PG[T]() class CG(PG[T]): pass self.assertIsInstance(CG[int](), CG) with self.assertRaises(TypeError): CG[int](42) def test_cannot_instantiate_abstract(self): @runtime_checkable class P(Protocol): @abc.abstractmethod def ameth(self) -> int: raise NotImplementedError class B(P): pass class C(B): def ameth(self) -> int: return 26 with self.assertRaises(TypeError): B() self.assertIsInstance(C(), P) def test_subprotocols_extending(self): class P1(Protocol): def meth1(self): pass @runtime_checkable class P2(P1, Protocol): def meth2(self): pass class C: def meth1(self): pass def meth2(self): pass class C1: def meth1(self): pass class C2: def meth2(self): pass self.assertNotIsInstance(C1(), P2) self.assertNotIsInstance(C2(), P2) self.assertNotIsSubclass(C1, P2) self.assertNotIsSubclass(C2, P2) self.assertIsInstance(C(), P2) self.assertIsSubclass(C, P2) def test_subprotocols_merging(self): class P1(Protocol): def meth1(self): pass class P2(Protocol): def meth2(self): pass @runtime_checkable class P(P1, P2, Protocol): pass class C: def meth1(self): pass def meth2(self): pass class C1: def meth1(self): pass class C2: def meth2(self): pass self.assertNotIsInstance(C1(), P) self.assertNotIsInstance(C2(), P) self.assertNotIsSubclass(C1, P) self.assertNotIsSubclass(C2, P) self.assertIsInstance(C(), P) self.assertIsSubclass(C, P) def test_protocols_issubclass(self): T = TypeVar('T') @runtime_checkable class P(Protocol): def x(self): ... @runtime_checkable class PG(Protocol[T]): def x(self): ... class BadP(Protocol): def x(self): ... class BadPG(Protocol[T]): def x(self): ... class C: def x(self): ... self.assertIsSubclass(C, P) self.assertIsSubclass(C, PG) self.assertIsSubclass(BadP, PG) with self.assertRaises(TypeError): issubclass(C, PG[T]) with self.assertRaises(TypeError): issubclass(C, PG[C]) with self.assertRaises(TypeError): issubclass(C, BadP) with self.assertRaises(TypeError): issubclass(C, BadPG) with self.assertRaises(TypeError): issubclass(P, PG[T]) with self.assertRaises(TypeError): issubclass(PG, PG[int]) def test_protocols_issubclass_non_callable(self): class C: x = 1 @runtime_checkable class PNonCall(Protocol): x = 1 with self.assertRaises(TypeError): issubclass(C, PNonCall) self.assertIsInstance(C(), PNonCall) PNonCall.register(C) with self.assertRaises(TypeError): issubclass(C, PNonCall) self.assertIsInstance(C(), PNonCall) # check that non-protocol subclasses are not affected class D(PNonCall): ... self.assertNotIsSubclass(C, D) self.assertNotIsInstance(C(), D) D.register(C) self.assertIsSubclass(C, D) self.assertIsInstance(C(), D) with self.assertRaises(TypeError): issubclass(D, PNonCall) def test_protocols_isinstance(self): T = TypeVar('T') @runtime_checkable class P(Protocol): def meth(x): ... @runtime_checkable class PG(Protocol[T]): def meth(x): ... class BadP(Protocol): def meth(x): ... class BadPG(Protocol[T]): def meth(x): ... class C: def meth(x): ... self.assertIsInstance(C(), P) self.assertIsInstance(C(), PG) with self.assertRaises(TypeError): isinstance(C(), PG[T]) with self.assertRaises(TypeError): isinstance(C(), PG[C]) with self.assertRaises(TypeError): isinstance(C(), BadP) with self.assertRaises(TypeError): isinstance(C(), BadPG) def test_protocols_isinstance_py36(self): class APoint: def __init__(self, x, y, label): self.x = x self.y = y self.label = label class BPoint: label = 'B' def __init__(self, x, y): self.x = x self.y = y class C: def __init__(self, attr): self.attr = attr def meth(self, arg): return 0 class Bad: pass self.assertIsInstance(APoint(1, 2, 'A'), Point) self.assertIsInstance(BPoint(1, 2), Point) self.assertNotIsInstance(MyPoint(), Point) self.assertIsInstance(BPoint(1, 2), Position) self.assertIsInstance(Other(), Proto) self.assertIsInstance(Concrete(), Proto) self.assertIsInstance(C(42), Proto) self.assertNotIsInstance(Bad(), Proto) self.assertNotIsInstance(Bad(), Point) self.assertNotIsInstance(Bad(), Position) self.assertNotIsInstance(Bad(), Concrete) self.assertNotIsInstance(Other(), Concrete) self.assertIsInstance(NT(1, 2), Position) def test_protocols_isinstance_init(self): T = TypeVar('T') @runtime_checkable class P(Protocol): x = 1 @runtime_checkable class PG(Protocol[T]): x = 1 class C: def __init__(self, x): self.x = x self.assertIsInstance(C(1), P) self.assertIsInstance(C(1), PG) def test_protocol_checks_after_subscript(self): class P(Protocol[T]): pass class C(P[T]): pass class Other1: pass class Other2: pass CA = C[Any] self.assertNotIsInstance(Other1(), C) self.assertNotIsSubclass(Other2, C) class D1(C[Any]): pass class D2(C[Any]): pass CI = C[int] self.assertIsInstance(D1(), C) self.assertIsSubclass(D2, C) def test_protocols_support_register(self): @runtime_checkable class P(Protocol): x = 1 class PM(Protocol): def meth(self): pass class D(PM): pass class C: pass D.register(C) P.register(C) self.assertIsInstance(C(), P) self.assertIsInstance(C(), D) def test_none_on_non_callable_doesnt_block_implementation(self): @runtime_checkable class P(Protocol): x = 1 class A: x = 1 class B(A): x = None class C: def __init__(self): self.x = None self.assertIsInstance(B(), P) self.assertIsInstance(C(), P) def test_none_on_callable_blocks_implementation(self): @runtime_checkable class P(Protocol): def x(self): ... class A: def x(self): ... class B(A): x = None class C: def __init__(self): self.x = None self.assertNotIsInstance(B(), P) self.assertNotIsInstance(C(), P) def test_non_protocol_subclasses(self): class P(Protocol): x = 1 @runtime_checkable class PR(Protocol): def meth(self): pass class NonP(P): x = 1 class NonPR(PR): pass class C: x = 1 class D: def meth(self): pass self.assertNotIsInstance(C(), NonP) self.assertNotIsInstance(D(), NonPR) self.assertNotIsSubclass(C, NonP) self.assertNotIsSubclass(D, NonPR) self.assertIsInstance(NonPR(), PR) self.assertIsSubclass(NonPR, PR) def test_custom_subclasshook(self): class P(Protocol): x = 1 class OKClass: pass class BadClass: x = 1 class C(P): @classmethod def __subclasshook__(cls, other): return other.__name__.startswith("OK") self.assertIsInstance(OKClass(), C) self.assertNotIsInstance(BadClass(), C) self.assertIsSubclass(OKClass, C) self.assertNotIsSubclass(BadClass, C) def test_issubclass_fails_correctly(self): @runtime_checkable class P(Protocol): x = 1 class C: pass with self.assertRaises(TypeError): issubclass(C(), P) def test_defining_generic_protocols(self): T = TypeVar('T') S = TypeVar('S') @runtime_checkable class PR(Protocol[T, S]): def meth(self): pass class P(PR[int, T], Protocol[T]): y = 1 with self.assertRaises(TypeError): PR[int] with self.assertRaises(TypeError): P[int, str] class C(PR[int, T]): pass self.assertIsInstance(C[str](), C) def test_defining_generic_protocols_old_style(self): T = TypeVar('T') S = TypeVar('S') @runtime_checkable class PR(Protocol, Generic[T, S]): def meth(self): pass class P(PR[int, str], Protocol): y = 1 with self.assertRaises(TypeError): issubclass(PR[int, str], PR) self.assertIsSubclass(P, PR) with self.assertRaises(TypeError): PR[int] class P1(Protocol, Generic[T]): def bar(self, x: T) -> str: ... class P2(Generic[T], Protocol): def bar(self, x: T) -> str: ... @runtime_checkable class PSub(P1[str], Protocol): x = 1 class Test: x = 1 def bar(self, x: str) -> str: return x self.assertIsInstance(Test(), PSub) def test_init_called(self): T = TypeVar('T') class P(Protocol[T]): pass class C(P[T]): def __init__(self): self.test = 'OK' self.assertEqual(C[int]().test, 'OK') class B: def __init__(self): self.test = 'OK' class D1(B, P[T]): pass self.assertEqual(D1[int]().test, 'OK') class D2(P[T], B): pass self.assertEqual(D2[int]().test, 'OK') def test_new_called(self): T = TypeVar('T') class P(Protocol[T]): pass class C(P[T]): def __new__(cls, *args): self = super().__new__(cls, *args) self.test = 'OK' return self self.assertEqual(C[int]().test, 'OK') with self.assertRaises(TypeError): C[int](42) with self.assertRaises(TypeError): C[int](a=42) def test_protocols_bad_subscripts(self): T = TypeVar('T') S = TypeVar('S') with self.assertRaises(TypeError): class P(Protocol[T, T]): pass with self.assertRaises(TypeError): class P(Protocol[int]): pass with self.assertRaises(TypeError): class P(Protocol[T], Protocol[S]): pass with self.assertRaises(TypeError): class P(typing.Mapping[T, S], Protocol[T]): pass def test_generic_protocols_repr(self): T = TypeVar('T') S = TypeVar('S') class P(Protocol[T, S]): pass self.assertTrue(repr(P[T, S]).endswith('P[~T, ~S]')) self.assertTrue(repr(P[int, str]).endswith('P[int, str]')) def test_generic_protocols_eq(self): T = TypeVar('T') S = TypeVar('S') class P(Protocol[T, S]): pass self.assertEqual(P, P) self.assertEqual(P[int, T], P[int, T]) self.assertEqual(P[T, T][Tuple[T, S]][int, str], P[Tuple[int, str], Tuple[int, str]]) def test_generic_protocols_special_from_generic(self): T = TypeVar('T') class P(Protocol[T]): pass self.assertEqual(P.__parameters__, (T,)) self.assertEqual(P[int].__parameters__, ()) self.assertEqual(P[int].__args__, (int,)) self.assertIs(P[int].__origin__, P) def test_generic_protocols_special_from_protocol(self): @runtime_checkable class PR(Protocol): x = 1 class P(Protocol): def meth(self): pass T = TypeVar('T') class PG(Protocol[T]): x = 1 def meth(self): pass self.assertTrue(P._is_protocol) self.assertTrue(PR._is_protocol) self.assertTrue(PG._is_protocol) self.assertFalse(P._is_runtime_protocol) self.assertTrue(PR._is_runtime_protocol) self.assertTrue(PG[int]._is_protocol) self.assertEqual(typing._get_protocol_attrs(P), {'meth'}) self.assertEqual(typing._get_protocol_attrs(PR), {'x'}) self.assertEqual(frozenset(typing._get_protocol_attrs(PG)), frozenset({'x', 'meth'})) def test_no_runtime_deco_on_nominal(self): with self.assertRaises(TypeError): @runtime_checkable class C: pass class Proto(Protocol): x = 1 with self.assertRaises(TypeError): @runtime_checkable class Concrete(Proto): pass def test_none_treated_correctly(self): @runtime_checkable class P(Protocol): x = None # type: int class B(object): pass self.assertNotIsInstance(B(), P) class C: x = 1 class D: x = None self.assertIsInstance(C(), P) self.assertIsInstance(D(), P) class CI: def __init__(self): self.x = 1 class DI: def __init__(self): self.x = None self.assertIsInstance(C(), P) self.assertIsInstance(D(), P) def test_protocols_in_unions(self): class P(Protocol): x = None # type: int Alias = typing.Union[typing.Iterable, P] Alias2 = typing.Union[P, typing.Iterable] self.assertEqual(Alias, Alias2) def test_protocols_pickleable(self): global P, CP # pickle wants to reference the class by name T = TypeVar('T') @runtime_checkable class P(Protocol[T]): x = 1 class CP(P[int]): pass c = CP() c.foo = 42 c.bar = 'abc' for proto in range(pickle.HIGHEST_PROTOCOL + 1): z = pickle.dumps(c, proto) x = pickle.loads(z) self.assertEqual(x.foo, 42) self.assertEqual(x.bar, 'abc') self.assertEqual(x.x, 1) self.assertEqual(x.__dict__, {'foo': 42, 'bar': 'abc'}) s = pickle.dumps(P) D = pickle.loads(s) class E: x = 1 self.assertIsInstance(E(), D) def test_supports_int(self): self.assertIsSubclass(int, typing.SupportsInt) self.assertNotIsSubclass(str, typing.SupportsInt) def test_supports_float(self): self.assertIsSubclass(float, typing.SupportsFloat) self.assertNotIsSubclass(str, typing.SupportsFloat) def test_supports_complex(self): class C: def __complex__(self): return 0j self.assertIsSubclass(complex, typing.SupportsComplex) self.assertIsSubclass(C, typing.SupportsComplex) self.assertNotIsSubclass(str, typing.SupportsComplex) def test_supports_bytes(self): class B: def __bytes__(self): return b'' self.assertIsSubclass(bytes, typing.SupportsBytes) self.assertIsSubclass(B, typing.SupportsBytes) self.assertNotIsSubclass(str, typing.SupportsBytes) def test_supports_abs(self): self.assertIsSubclass(float, typing.SupportsAbs) self.assertIsSubclass(int, typing.SupportsAbs) self.assertNotIsSubclass(str, typing.SupportsAbs) def test_supports_round(self): issubclass(float, typing.SupportsRound) self.assertIsSubclass(float, typing.SupportsRound) self.assertIsSubclass(int, typing.SupportsRound) self.assertNotIsSubclass(str, typing.SupportsRound) def test_reversible(self): self.assertIsSubclass(list, typing.Reversible) self.assertNotIsSubclass(int, typing.Reversible) def test_supports_index(self): self.assertIsSubclass(int, typing.SupportsIndex) self.assertNotIsSubclass(str, typing.SupportsIndex) def test_bundled_protocol_instance_works(self): self.assertIsInstance(0, typing.SupportsAbs) class C1(typing.SupportsInt): def __int__(self) -> int: return 42 class C2(C1): pass c = C2() self.assertIsInstance(c, C1) def test_collections_protocols_allowed(self): @runtime_checkable class Custom(collections.abc.Iterable, Protocol): def close(self): ... class A: pass class B: def __iter__(self): return [] def close(self): return 0 self.assertIsSubclass(B, Custom) self.assertNotIsSubclass(A, Custom) def test_builtin_protocol_allowlist(self): with self.assertRaises(TypeError): class CustomProtocol(TestCase, Protocol): pass class CustomContextManager(typing.ContextManager, Protocol): pass def test_non_runtime_protocol_isinstance_check(self): class P(Protocol): x: int with self.assertRaisesRegex(TypeError, "@runtime_checkable"): isinstance(1, P) def test_super_call_init(self): class P(Protocol): x: int class Foo(P): def __init__(self): super().__init__() Foo() # Previously triggered RecursionError class GenericTests(BaseTestCase): def test_basics(self): X = SimpleMapping[str, Any] self.assertEqual(X.__parameters__, ()) with self.assertRaises(TypeError): X[str] with self.assertRaises(TypeError): X[str, str] Y = SimpleMapping[XK, str] self.assertEqual(Y.__parameters__, (XK,)) Y[str] with self.assertRaises(TypeError): Y[str, str] SM1 = SimpleMapping[str, int] with self.assertRaises(TypeError): issubclass(SM1, SimpleMapping) self.assertIsInstance(SM1(), SimpleMapping) T = TypeVar("T") self.assertEqual(List[list[T] | float].__parameters__, (T,)) def test_generic_errors(self): T = TypeVar('T') S = TypeVar('S') with self.assertRaises(TypeError): Generic[T][T] with self.assertRaises(TypeError): Generic[T][S] with self.assertRaises(TypeError): class C(Generic[T], Generic[T]): ... with self.assertRaises(TypeError): isinstance([], List[int]) with self.assertRaises(TypeError): issubclass(list, List[int]) with self.assertRaises(TypeError): class NewGeneric(Generic): ... with self.assertRaises(TypeError): class MyGeneric(Generic[T], Generic[S]): ... with self.assertRaises(TypeError): class MyGeneric(List[T], Generic[S]): ... def test_init(self): T = TypeVar('T') S = TypeVar('S') with self.assertRaises(TypeError): Generic[T, T] with self.assertRaises(TypeError): Generic[T, S, T] def test_init_subclass(self): class X(typing.Generic[T]): def __init_subclass__(cls, **kwargs): super().__init_subclass__(**kwargs) cls.attr = 42 class Y(X): pass self.assertEqual(Y.attr, 42) with self.assertRaises(AttributeError): X.attr X.attr = 1 Y.attr = 2 class Z(Y): pass class W(X[int]): pass self.assertEqual(Y.attr, 2) self.assertEqual(Z.attr, 42) self.assertEqual(W.attr, 42) def test_repr(self): self.assertEqual(repr(SimpleMapping), f"<class '{__name__}.SimpleMapping'>") self.assertEqual(repr(MySimpleMapping), f"<class '{__name__}.MySimpleMapping'>") def test_chain_repr(self): T = TypeVar('T') S = TypeVar('S') class C(Generic[T]): pass X = C[Tuple[S, T]] self.assertEqual(X, C[Tuple[S, T]]) self.assertNotEqual(X, C[Tuple[T, S]]) Y = X[T, int] self.assertEqual(Y, X[T, int]) self.assertNotEqual(Y, X[S, int]) self.assertNotEqual(Y, X[T, str]) Z = Y[str] self.assertEqual(Z, Y[str]) self.assertNotEqual(Z, Y[int]) self.assertNotEqual(Z, Y[T]) self.assertTrue(str(Z).endswith( '.C[typing.Tuple[str, int]]')) def test_new_repr(self): T = TypeVar('T') U = TypeVar('U', covariant=True) S = TypeVar('S') self.assertEqual(repr(List), 'typing.List') self.assertEqual(repr(List[T]), 'typing.List[~T]') self.assertEqual(repr(List[U]), 'typing.List[+U]') self.assertEqual(repr(List[S][T][int]), 'typing.List[int]') self.assertEqual(repr(List[int]), 'typing.List[int]') def test_new_repr_complex(self): T = TypeVar('T') TS = TypeVar('TS') self.assertEqual(repr(typing.Mapping[T, TS][TS, T]), 'typing.Mapping[~TS, ~T]') self.assertEqual(repr(List[Tuple[T, TS]][int, T]), 'typing.List[typing.Tuple[int, ~T]]') self.assertEqual( repr(List[Tuple[T, T]][List[int]]), 'typing.List[typing.Tuple[typing.List[int], typing.List[int]]]' ) def test_new_repr_bare(self): T = TypeVar('T') self.assertEqual(repr(Generic[T]), 'typing.Generic[~T]') self.assertEqual(repr(typing.Protocol[T]), 'typing.Protocol[~T]') class C(typing.Dict[Any, Any]): ... # this line should just work repr(C.__mro__) def test_dict(self): T = TypeVar('T') class B(Generic[T]): pass b = B() b.foo = 42 self.assertEqual(b.__dict__, {'foo': 42}) class C(B[int]): pass c = C() c.bar = 'abc' self.assertEqual(c.__dict__, {'bar': 'abc'}) def test_subscripted_generics_as_proxies(self): T = TypeVar('T') class C(Generic[T]): x = 'def' self.assertEqual(C[int].x, 'def') self.assertEqual(C[C[int]].x, 'def') C[C[int]].x = 'changed' self.assertEqual(C.x, 'changed') self.assertEqual(C[str].x, 'changed') C[List[str]].z = 'new' self.assertEqual(C.z, 'new') self.assertEqual(C[Tuple[int]].z, 'new') self.assertEqual(C().x, 'changed') self.assertEqual(C[Tuple[str]]().z, 'new') class D(C[T]): pass self.assertEqual(D[int].x, 'changed') self.assertEqual(D.z, 'new') D.z = 'from derived z' D[int].x = 'from derived x' self.assertEqual(C.x, 'changed') self.assertEqual(C[int].z, 'new') self.assertEqual(D.x, 'from derived x') self.assertEqual(D[str].z, 'from derived z') def test_abc_registry_kept(self): T = TypeVar('T') class C(collections.abc.Mapping, Generic[T]): ... C.register(int) self.assertIsInstance(1, C) C[int] self.assertIsInstance(1, C) C._abc_registry_clear() C._abc_caches_clear() # To keep refleak hunting mode clean def test_false_subclasses(self): class MyMapping(MutableMapping[str, str]): pass self.assertNotIsInstance({}, MyMapping) self.assertNotIsSubclass(dict, MyMapping) def test_abc_bases(self): class MM(MutableMapping[str, str]): def __getitem__(self, k): return None def __setitem__(self, k, v): pass def __delitem__(self, k): pass def __iter__(self): return iter(()) def __len__(self): return 0 # this should just work MM().update() self.assertIsInstance(MM(), collections.abc.MutableMapping) self.assertIsInstance(MM(), MutableMapping) self.assertNotIsInstance(MM(), List) self.assertNotIsInstance({}, MM) def test_multiple_bases(self): class MM1(MutableMapping[str, str], collections.abc.MutableMapping): pass class MM2(collections.abc.MutableMapping, MutableMapping[str, str]): pass self.assertEqual(MM2.__bases__, (collections.abc.MutableMapping, Generic)) def test_orig_bases(self): T = TypeVar('T') class C(typing.Dict[str, T]): ... self.assertEqual(C.__orig_bases__, (typing.Dict[str, T],)) def test_naive_runtime_checks(self): def naive_dict_check(obj, tp): # Check if a dictionary conforms to Dict type if len(tp.__parameters__) > 0: raise NotImplementedError if tp.__args__: KT, VT = tp.__args__ return all( isinstance(k, KT) and isinstance(v, VT) for k, v in obj.items() ) self.assertTrue(naive_dict_check({'x': 1}, typing.Dict[str, int])) self.assertFalse(naive_dict_check({1: 'x'}, typing.Dict[str, int])) with self.assertRaises(NotImplementedError): naive_dict_check({1: 'x'}, typing.Dict[str, T]) def naive_generic_check(obj, tp): # Check if an instance conforms to the generic class if not hasattr(obj, '__orig_class__'): raise NotImplementedError return obj.__orig_class__ == tp class Node(Generic[T]): ... self.assertTrue(naive_generic_check(Node[int](), Node[int])) self.assertFalse(naive_generic_check(Node[str](), Node[int])) self.assertFalse(naive_generic_check(Node[str](), List)) with self.assertRaises(NotImplementedError): naive_generic_check([1, 2, 3], Node[int]) def naive_list_base_check(obj, tp): # Check if list conforms to a List subclass return all(isinstance(x, tp.__orig_bases__[0].__args__[0]) for x in obj) class C(List[int]): ... self.assertTrue(naive_list_base_check([1, 2, 3], C)) self.assertFalse(naive_list_base_check(['a', 'b'], C)) def test_multi_subscr_base(self): T = TypeVar('T') U = TypeVar('U') V = TypeVar('V') class C(List[T][U][V]): ... class D(C, List[T][U][V]): ... self.assertEqual(C.__parameters__, (V,)) self.assertEqual(D.__parameters__, (V,)) self.assertEqual(C[int].__parameters__, ()) self.assertEqual(D[int].__parameters__, ()) self.assertEqual(C[int].__args__, (int,)) self.assertEqual(D[int].__args__, (int,)) self.assertEqual(C.__bases__, (list, Generic)) self.assertEqual(D.__bases__, (C, list, Generic)) self.assertEqual(C.__orig_bases__, (List[T][U][V],)) self.assertEqual(D.__orig_bases__, (C, List[T][U][V])) def test_subscript_meta(self): T = TypeVar('T') class Meta(type): ... self.assertEqual(Type[Meta], Type[Meta]) self.assertEqual(Union[T, int][Meta], Union[Meta, int]) self.assertEqual(Callable[..., Meta].__args__, (Ellipsis, Meta)) def test_generic_hashes(self): class A(Generic[T]): ... class B(Generic[T]): class A(Generic[T]): ... self.assertEqual(A, A) self.assertEqual(mod_generics_cache.A[str], mod_generics_cache.A[str]) self.assertEqual(B.A, B.A) self.assertEqual(mod_generics_cache.B.A[B.A[str]], mod_generics_cache.B.A[B.A[str]]) self.assertNotEqual(A, B.A) self.assertNotEqual(A, mod_generics_cache.A) self.assertNotEqual(A, mod_generics_cache.B.A) self.assertNotEqual(B.A, mod_generics_cache.A) self.assertNotEqual(B.A, mod_generics_cache.B.A) self.assertNotEqual(A[str], B.A[str]) self.assertNotEqual(A[List[Any]], B.A[List[Any]]) self.assertNotEqual(A[str], mod_generics_cache.A[str]) self.assertNotEqual(A[str], mod_generics_cache.B.A[str]) self.assertNotEqual(B.A[int], mod_generics_cache.A[int]) self.assertNotEqual(B.A[List[Any]], mod_generics_cache.B.A[List[Any]]) self.assertNotEqual(Tuple[A[str]], Tuple[B.A[str]]) self.assertNotEqual(Tuple[A[List[Any]]], Tuple[B.A[List[Any]]]) self.assertNotEqual(Union[str, A[str]], Union[str, mod_generics_cache.A[str]]) self.assertNotEqual(Union[A[str], A[str]], Union[A[str], mod_generics_cache.A[str]]) self.assertNotEqual(typing.FrozenSet[A[str]], typing.FrozenSet[mod_generics_cache.B.A[str]]) if sys.version_info[:2] > (3, 2): self.assertTrue(repr(Tuple[A[str]]).endswith('<locals>.A[str]]')) self.assertTrue(repr(Tuple[B.A[str]]).endswith('<locals>.B.A[str]]')) self.assertTrue(repr(Tuple[mod_generics_cache.A[str]]) .endswith('mod_generics_cache.A[str]]')) self.assertTrue(repr(Tuple[mod_generics_cache.B.A[str]]) .endswith('mod_generics_cache.B.A[str]]')) def test_extended_generic_rules_eq(self): T = TypeVar('T') U = TypeVar('U') self.assertEqual(Tuple[T, T][int], Tuple[int, int]) self.assertEqual(typing.Iterable[Tuple[T, T]][T], typing.Iterable[Tuple[T, T]]) with self.assertRaises(TypeError): Tuple[T, int][()] self.assertEqual(Union[T, int][int], int) self.assertEqual(Union[T, U][int, Union[int, str]], Union[int, str]) class Base: ... class Derived(Base): ... self.assertEqual(Union[T, Base][Union[Base, Derived]], Union[Base, Derived]) with self.assertRaises(TypeError): Union[T, int][1] self.assertEqual(Callable[[T], T][KT], Callable[[KT], KT]) self.assertEqual(Callable[..., List[T]][int], Callable[..., List[int]]) def test_extended_generic_rules_repr(self): T = TypeVar('T') self.assertEqual(repr(Union[Tuple, Callable]).replace('typing.', ''), 'Union[Tuple, Callable]') self.assertEqual(repr(Union[Tuple, Tuple[int]]).replace('typing.', ''), 'Union[Tuple, Tuple[int]]') self.assertEqual(repr(Callable[..., Optional[T]][int]).replace('typing.', ''), 'Callable[..., Optional[int]]') self.assertEqual(repr(Callable[[], List[T]][int]).replace('typing.', ''), 'Callable[[], List[int]]') def test_generic_forward_ref(self): def foobar(x: List[List['CC']]): ... def foobar2(x: list[list[ForwardRef('CC')]]): ... def foobar3(x: list[ForwardRef('CC | int')] | int): ... class CC: ... self.assertEqual( get_type_hints(foobar, globals(), locals()), {'x': List[List[CC]]} ) self.assertEqual( get_type_hints(foobar2, globals(), locals()), {'x': list[list[CC]]} ) self.assertEqual( get_type_hints(foobar3, globals(), locals()), {'x': list[CC | int] | int} ) T = TypeVar('T') AT = Tuple[T, ...] def barfoo(x: AT): ... self.assertIs(get_type_hints(barfoo, globals(), locals())['x'], AT) CT = Callable[..., List[T]] def barfoo2(x: CT): ... self.assertIs(get_type_hints(barfoo2, globals(), locals())['x'], CT) def test_extended_generic_rules_subclassing(self): class T1(Tuple[T, KT]): ... class T2(Tuple[T, ...]): ... class C1(typing.Container[T]): def __contains__(self, item): return False self.assertEqual(T1.__parameters__, (T, KT)) self.assertEqual(T1[int, str].__args__, (int, str)) self.assertEqual(T1[int, T].__origin__, T1) self.assertEqual(T2.__parameters__, (T,)) # These don't work because of tuple.__class_item__ ## with self.assertRaises(TypeError): ## T1[int] ## with self.assertRaises(TypeError): ## T2[int, str] self.assertEqual(repr(C1[int]).split('.')[-1], 'C1[int]') self.assertEqual(C1.__parameters__, (T,)) self.assertIsInstance(C1(), collections.abc.Container) self.assertIsSubclass(C1, collections.abc.Container) self.assertIsInstance(T1(), tuple) self.assertIsSubclass(T2, tuple) with self.assertRaises(TypeError): issubclass(Tuple[int, ...], typing.Sequence) with self.assertRaises(TypeError): issubclass(Tuple[int, ...], typing.Iterable) def test_fail_with_bare_union(self): with self.assertRaises(TypeError): List[Union] with self.assertRaises(TypeError): Tuple[Optional] with self.assertRaises(TypeError): ClassVar[ClassVar] with self.assertRaises(TypeError): List[ClassVar[int]] def test_fail_with_bare_generic(self): T = TypeVar('T') with self.assertRaises(TypeError): List[Generic] with self.assertRaises(TypeError): Tuple[Generic[T]] with self.assertRaises(TypeError): List[typing.Protocol] def test_type_erasure_special(self): T = TypeVar('T') # this is the only test that checks type caching self.clear_caches() class MyTup(Tuple[T, T]): ... self.assertIs(MyTup[int]().__class__, MyTup) self.assertEqual(MyTup[int]().__orig_class__, MyTup[int]) class MyDict(typing.Dict[T, T]): ... self.assertIs(MyDict[int]().__class__, MyDict) self.assertEqual(MyDict[int]().__orig_class__, MyDict[int]) class MyDef(typing.DefaultDict[str, T]): ... self.assertIs(MyDef[int]().__class__, MyDef) self.assertEqual(MyDef[int]().__orig_class__, MyDef[int]) # ChainMap was added in 3.3 if sys.version_info >= (3, 3): class MyChain(typing.ChainMap[str, T]): ... self.assertIs(MyChain[int]().__class__, MyChain) self.assertEqual(MyChain[int]().__orig_class__, MyChain[int]) def test_all_repr_eq_any(self): objs = (getattr(typing, el) for el in typing.__all__) for obj in objs: self.assertNotEqual(repr(obj), '') self.assertEqual(obj, obj) if getattr(obj, '__parameters__', None) and len(obj.__parameters__) == 1: self.assertEqual(obj[Any].__args__, (Any,)) if isinstance(obj, type): for base in obj.__mro__: self.assertNotEqual(repr(base), '') self.assertEqual(base, base) def test_pickle(self): global C # pickle wants to reference the class by name T = TypeVar('T') class B(Generic[T]): pass class C(B[int]): pass c = C() c.foo = 42 c.bar = 'abc' for proto in range(pickle.HIGHEST_PROTOCOL + 1): z = pickle.dumps(c, proto) x = pickle.loads(z) self.assertEqual(x.foo, 42) self.assertEqual(x.bar, 'abc') self.assertEqual(x.__dict__, {'foo': 42, 'bar': 'abc'}) samples = [Any, Union, Tuple, Callable, ClassVar, Union[int, str], ClassVar[List], Tuple[int, ...], Callable[[str], bytes], typing.DefaultDict, typing.FrozenSet[int]] for s in samples: for proto in range(pickle.HIGHEST_PROTOCOL + 1): z = pickle.dumps(s, proto) x = pickle.loads(z) self.assertEqual(s, x) more_samples = [List, typing.Iterable, typing.Type, List[int], typing.Type[typing.Mapping], typing.AbstractSet[Tuple[int, str]]] for s in more_samples: for proto in range(pickle.HIGHEST_PROTOCOL + 1): z = pickle.dumps(s, proto) x = pickle.loads(z) self.assertEqual(s, x) def test_copy_and_deepcopy(self): T = TypeVar('T') class Node(Generic[T]): ... things = [Union[T, int], Tuple[T, int], Callable[..., T], Callable[[int], int], Tuple[Any, Any], Node[T], Node[int], Node[Any], typing.Iterable[T], typing.Iterable[Any], typing.Iterable[int], typing.Dict[int, str], typing.Dict[T, Any], ClassVar[int], ClassVar[List[T]], Tuple['T', 'T'], Union['T', int], List['T'], typing.Mapping['T', int]] for t in things + [Any]: self.assertEqual(t, copy(t)) self.assertEqual(t, deepcopy(t)) def test_immutability_by_copy_and_pickle(self): # Special forms like Union, Any, etc., generic aliases to containers like List, # Mapping, etc., and type variabcles are considered immutable by copy and pickle. global TP, TPB, TPV # for pickle TP = TypeVar('TP') TPB = TypeVar('TPB', bound=int) TPV = TypeVar('TPV', bytes, str) for X in [TP, TPB, TPV, List, typing.Mapping, ClassVar, typing.Iterable, Union, Any, Tuple, Callable]: self.assertIs(copy(X), X) self.assertIs(deepcopy(X), X) self.assertIs(pickle.loads(pickle.dumps(X)), X) # Check that local type variables are copyable. TL = TypeVar('TL') TLB = TypeVar('TLB', bound=int) TLV = TypeVar('TLV', bytes, str) for X in [TL, TLB, TLV]: self.assertIs(copy(X), X) self.assertIs(deepcopy(X), X) def test_copy_generic_instances(self): T = TypeVar('T') class C(Generic[T]): def __init__(self, attr: T) -> None: self.attr = attr c = C(42) self.assertEqual(copy(c).attr, 42) self.assertEqual(deepcopy(c).attr, 42) self.assertIsNot(copy(c), c) self.assertIsNot(deepcopy(c), c) c.attr = 1 self.assertEqual(copy(c).attr, 1) self.assertEqual(deepcopy(c).attr, 1) ci = C[int](42) self.assertEqual(copy(ci).attr, 42) self.assertEqual(deepcopy(ci).attr, 42) self.assertIsNot(copy(ci), ci) self.assertIsNot(deepcopy(ci), ci) ci.attr = 1 self.assertEqual(copy(ci).attr, 1) self.assertEqual(deepcopy(ci).attr, 1) self.assertEqual(ci.__orig_class__, C[int]) def test_weakref_all(self): T = TypeVar('T') things = [Any, Union[T, int], Callable[..., T], Tuple[Any, Any], Optional[List[int]], typing.Mapping[int, str], typing.Match[bytes], typing.Iterable['whatever']] for t in things: self.assertEqual(weakref.ref(t)(), t) def test_parameterized_slots(self): T = TypeVar('T') class C(Generic[T]): __slots__ = ('potato',) c = C() c_int = C[int]() c.potato = 0 c_int.potato = 0 with self.assertRaises(AttributeError): c.tomato = 0 with self.assertRaises(AttributeError): c_int.tomato = 0 def foo(x: C['C']): ... self.assertEqual(get_type_hints(foo, globals(), locals())['x'], C[C]) self.assertEqual(copy(C[int]), deepcopy(C[int])) def test_parameterized_slots_dict(self): T = TypeVar('T') class D(Generic[T]): __slots__ = {'banana': 42} d = D() d_int = D[int]() d.banana = 'yes' d_int.banana = 'yes' with self.assertRaises(AttributeError): d.foobar = 'no' with self.assertRaises(AttributeError): d_int.foobar = 'no' def test_errors(self): with self.assertRaises(TypeError): B = SimpleMapping[XK, Any] class C(Generic[B]): pass def test_repr_2(self): class C(Generic[T]): pass self.assertEqual(C.__module__, __name__) self.assertEqual(C.__qualname__, 'GenericTests.test_repr_2.<locals>.C') X = C[int] self.assertEqual(X.__module__, __name__) self.assertEqual(repr(X).split('.')[-1], 'C[int]') class Y(C[int]): pass self.assertEqual(Y.__module__, __name__) self.assertEqual(Y.__qualname__, 'GenericTests.test_repr_2.<locals>.Y') def test_eq_1(self): self.assertEqual(Generic, Generic) self.assertEqual(Generic[T], Generic[T]) self.assertNotEqual(Generic[KT], Generic[VT]) def test_eq_2(self): class A(Generic[T]): pass class B(Generic[T]): pass self.assertEqual(A, A) self.assertNotEqual(A, B) self.assertEqual(A[T], A[T]) self.assertNotEqual(A[T], B[T]) def test_multiple_inheritance(self): class A(Generic[T, VT]): pass class B(Generic[KT, T]): pass class C(A[T, VT], Generic[VT, T, KT], B[KT, T]): pass self.assertEqual(C.__parameters__, (VT, T, KT)) def test_multiple_inheritance_special(self): S = TypeVar('S') class B(Generic[S]): ... class C(List[int], B): ... self.assertEqual(C.__mro__, (C, list, B, Generic, object)) def test_init_subclass_super_called(self): class FinalException(Exception): pass class Final: def __init_subclass__(cls, **kwargs) -> None: for base in cls.__bases__: if base is not Final and issubclass(base, Final): raise FinalException(base) super().__init_subclass__(**kwargs) class Test(Generic[T], Final): pass with self.assertRaises(FinalException): class Subclass(Test): pass with self.assertRaises(FinalException): class Subclass(Test[int]): pass def test_nested(self): G = Generic class Visitor(G[T]): a = None def set(self, a: T): self.a = a def get(self): return self.a def visit(self) -> T: return self.a V = Visitor[typing.List[int]] class IntListVisitor(V): def append(self, x: int): self.a.append(x) a = IntListVisitor() a.set([]) a.append(1) a.append(42) self.assertEqual(a.get(), [1, 42]) def test_type_erasure(self): T = TypeVar('T') class Node(Generic[T]): def __init__(self, label: T, left: 'Node[T]' = None, right: 'Node[T]' = None): self.label = label # type: T self.left = left # type: Optional[Node[T]] self.right = right # type: Optional[Node[T]] def foo(x: T): a = Node(x) b = Node[T](x) c = Node[Any](x) self.assertIs(type(a), Node) self.assertIs(type(b), Node) self.assertIs(type(c), Node) self.assertEqual(a.label, x) self.assertEqual(b.label, x) self.assertEqual(c.label, x) foo(42) def test_implicit_any(self): T = TypeVar('T') class C(Generic[T]): pass class D(C): pass self.assertEqual(D.__parameters__, ()) with self.assertRaises(Exception): D[int] with self.assertRaises(Exception): D[Any] with self.assertRaises(Exception): D[T] def test_new_with_args(self): class A(Generic[T]): pass class B: def __new__(cls, arg): # call object obj = super().__new__(cls) obj.arg = arg return obj # mro: C, A, Generic, B, object class C(A, B): pass c = C('foo') self.assertEqual(c.arg, 'foo') def test_new_with_args2(self): class A: def __init__(self, arg): self.from_a = arg # call object super().__init__() # mro: C, Generic, A, object class C(Generic[T], A): def __init__(self, arg): self.from_c = arg # call Generic super().__init__(arg) c = C('foo') self.assertEqual(c.from_a, 'foo') self.assertEqual(c.from_c, 'foo') def test_new_no_args(self): class A(Generic[T]): pass with self.assertRaises(TypeError): A('foo') class B: def __new__(cls): # call object obj = super().__new__(cls) obj.from_b = 'b' return obj # mro: C, A, Generic, B, object class C(A, B): def __init__(self, arg): self.arg = arg def __new__(cls, arg): # call A obj = super().__new__(cls) obj.from_c = 'c' return obj c = C('foo') self.assertEqual(c.arg, 'foo') self.assertEqual(c.from_b, 'b') self.assertEqual(c.from_c, 'c') def test_subclass_special_form(self): for obj in ( ClassVar[int], Final[int], Union[int, float], Optional[int], Literal[1, 2], Concatenate[int, ParamSpec("P")], TypeGuard[int], ): with self.subTest(msg=obj): with self.assertRaisesRegex( TypeError, f'^{re.escape(f"Cannot subclass {obj!r}")}$' ): class Foo(obj): pass class ClassVarTests(BaseTestCase): def test_basics(self): with self.assertRaises(TypeError): ClassVar[1] with self.assertRaises(TypeError): ClassVar[int, str] with self.assertRaises(TypeError): ClassVar[int][str] def test_repr(self): self.assertEqual(repr(ClassVar), 'typing.ClassVar') cv = ClassVar[int] self.assertEqual(repr(cv), 'typing.ClassVar[int]') cv = ClassVar[Employee] self.assertEqual(repr(cv), 'typing.ClassVar[%s.Employee]' % __name__) def test_cannot_subclass(self): with self.assertRaises(TypeError): class C(type(ClassVar)): pass with self.assertRaises(TypeError): class C(type(ClassVar[int])): pass def test_cannot_init(self): with self.assertRaises(TypeError): ClassVar() with self.assertRaises(TypeError): type(ClassVar)() with self.assertRaises(TypeError): type(ClassVar[Optional[int]])() def test_no_isinstance(self): with self.assertRaises(TypeError): isinstance(1, ClassVar[int]) with self.assertRaises(TypeError): issubclass(int, ClassVar) class FinalTests(BaseTestCase): def test_basics(self): Final[int] # OK with self.assertRaises(TypeError): Final[1] with self.assertRaises(TypeError): Final[int, str] with self.assertRaises(TypeError): Final[int][str] with self.assertRaises(TypeError): Optional[Final[int]] def test_repr(self): self.assertEqual(repr(Final), 'typing.Final') cv = Final[int] self.assertEqual(repr(cv), 'typing.Final[int]') cv = Final[Employee] self.assertEqual(repr(cv), 'typing.Final[%s.Employee]' % __name__) cv = Final[tuple[int]] self.assertEqual(repr(cv), 'typing.Final[tuple[int]]') def test_cannot_subclass(self): with self.assertRaises(TypeError): class C(type(Final)): pass with self.assertRaises(TypeError): class C(type(Final[int])): pass def test_cannot_init(self): with self.assertRaises(TypeError): Final() with self.assertRaises(TypeError): type(Final)() with self.assertRaises(TypeError): type(Final[Optional[int]])() def test_no_isinstance(self): with self.assertRaises(TypeError): isinstance(1, Final[int]) with self.assertRaises(TypeError): issubclass(int, Final) def test_final_unmodified(self): def func(x): ... self.assertIs(func, final(func)) class CastTests(BaseTestCase): def test_basics(self): self.assertEqual(cast(int, 42), 42) self.assertEqual(cast(float, 42), 42) self.assertIs(type(cast(float, 42)), int) self.assertEqual(cast(Any, 42), 42) self.assertEqual(cast(list, 42), 42) self.assertEqual(cast(Union[str, float], 42), 42) self.assertEqual(cast(AnyStr, 42), 42) self.assertEqual(cast(None, 42), 42) def test_errors(self): # Bogus calls are not expected to fail. cast(42, 42) cast('hello', 42) class ForwardRefTests(BaseTestCase): def test_basics(self): class Node(Generic[T]): def __init__(self, label: T): self.label = label self.left = self.right = None def add_both(self, left: 'Optional[Node[T]]', right: 'Node[T]' = None, stuff: int = None, blah=None): self.left = left self.right = right def add_left(self, node: Optional['Node[T]']): self.add_both(node, None) def add_right(self, node: 'Node[T]' = None): self.add_both(None, node) t = Node[int] both_hints = get_type_hints(t.add_both, globals(), locals()) self.assertEqual(both_hints['left'], Optional[Node[T]]) self.assertEqual(both_hints['right'], Optional[Node[T]]) self.assertEqual(both_hints['left'], both_hints['right']) self.assertEqual(both_hints['stuff'], Optional[int]) self.assertNotIn('blah', both_hints) left_hints = get_type_hints(t.add_left, globals(), locals()) self.assertEqual(left_hints['node'], Optional[Node[T]]) right_hints = get_type_hints(t.add_right, globals(), locals()) self.assertEqual(right_hints['node'], Optional[Node[T]]) def test_forwardref_instance_type_error(self): fr = typing.ForwardRef('int') with self.assertRaises(TypeError): isinstance(42, fr) def test_forwardref_subclass_type_error(self): fr = typing.ForwardRef('int') with self.assertRaises(TypeError): issubclass(int, fr) def test_forward_equality(self): fr = typing.ForwardRef('int') self.assertEqual(fr, typing.ForwardRef('int')) self.assertNotEqual(List['int'], List[int]) def test_forward_equality_gth(self): c1 = typing.ForwardRef('C') c1_gth = typing.ForwardRef('C') c2 = typing.ForwardRef('C') c2_gth = typing.ForwardRef('C') class C: pass def foo(a: c1_gth, b: c2_gth): pass self.assertEqual(get_type_hints(foo, globals(), locals()), {'a': C, 'b': C}) self.assertEqual(c1, c2) self.assertEqual(c1, c1_gth) self.assertEqual(c1_gth, c2_gth) self.assertEqual(List[c1], List[c1_gth]) self.assertNotEqual(List[c1], List[C]) self.assertNotEqual(List[c1_gth], List[C]) self.assertEqual(Union[c1, c1_gth], Union[c1]) self.assertEqual(Union[c1, c1_gth, int], Union[c1, int]) def test_forward_equality_hash(self): c1 = typing.ForwardRef('int') c1_gth = typing.ForwardRef('int') c2 = typing.ForwardRef('int') c2_gth = typing.ForwardRef('int') def foo(a: c1_gth, b: c2_gth): pass get_type_hints(foo, globals(), locals()) self.assertEqual(hash(c1), hash(c2)) self.assertEqual(hash(c1_gth), hash(c2_gth)) self.assertEqual(hash(c1), hash(c1_gth)) def test_forward_equality_namespace(self): class A: pass def namespace1(): a = typing.ForwardRef('A') def fun(x: a): pass get_type_hints(fun, globals(), locals()) return a def namespace2(): a = typing.ForwardRef('A') class A: pass def fun(x: a): pass get_type_hints(fun, globals(), locals()) return a self.assertEqual(namespace1(), namespace1()) self.assertNotEqual(namespace1(), namespace2()) def test_forward_repr(self): self.assertEqual(repr(List['int']), "typing.List[ForwardRef('int')]") def test_union_forward(self): def foo(a: Union['T']): pass self.assertEqual(get_type_hints(foo, globals(), locals()), {'a': Union[T]}) def foo(a: tuple[ForwardRef('T')] | int): pass self.assertEqual(get_type_hints(foo, globals(), locals()), {'a': tuple[T] | int}) def test_tuple_forward(self): def foo(a: Tuple['T']): pass self.assertEqual(get_type_hints(foo, globals(), locals()), {'a': Tuple[T]}) def foo(a: tuple[ForwardRef('T')]): pass self.assertEqual(get_type_hints(foo, globals(), locals()), {'a': tuple[T]}) def test_double_forward(self): def foo(a: 'List[\'int\']'): pass self.assertEqual(get_type_hints(foo, globals(), locals()), {'a': List[int]}) def test_forward_recursion_actually(self): def namespace1(): a = typing.ForwardRef('A') A = a def fun(x: a): pass ret = get_type_hints(fun, globals(), locals()) return a def namespace2(): a = typing.ForwardRef('A') A = a def fun(x: a): pass ret = get_type_hints(fun, globals(), locals()) return a def cmp(o1, o2): return o1 == o2 r1 = namespace1() r2 = namespace2() self.assertIsNot(r1, r2) self.assertRaises(RecursionError, cmp, r1, r2) def test_union_forward_recursion(self): ValueList = List['Value'] Value = Union[str, ValueList] class C: foo: List[Value] class D: foo: Union[Value, ValueList] class E: foo: Union[List[Value], ValueList] class F: foo: Union[Value, List[Value], ValueList] self.assertEqual(get_type_hints(C, globals(), locals()), get_type_hints(C, globals(), locals())) self.assertEqual(get_type_hints(C, globals(), locals()), {'foo': List[Union[str, List[Union[str, List['Value']]]]]}) self.assertEqual(get_type_hints(D, globals(), locals()), {'foo': Union[str, List[Union[str, List['Value']]]]}) self.assertEqual(get_type_hints(E, globals(), locals()), {'foo': Union[ List[Union[str, List[Union[str, List['Value']]]]], List[Union[str, List['Value']]] ] }) self.assertEqual(get_type_hints(F, globals(), locals()), {'foo': Union[ str, List[Union[str, List['Value']]], List[Union[str, List[Union[str, List['Value']]]]] ] }) def test_callable_forward(self): def foo(a: Callable[['T'], 'T']): pass self.assertEqual(get_type_hints(foo, globals(), locals()), {'a': Callable[[T], T]}) def test_callable_with_ellipsis_forward(self): def foo(a: 'Callable[..., T]'): pass self.assertEqual(get_type_hints(foo, globals(), locals()), {'a': Callable[..., T]}) def test_syntax_error(self): with self.assertRaises(SyntaxError): Generic['/T'] def test_delayed_syntax_error(self): def foo(a: 'Node[T'): pass with self.assertRaises(SyntaxError): get_type_hints(foo) def test_type_error(self): def foo(a: Tuple['42']): pass with self.assertRaises(TypeError): get_type_hints(foo) def test_name_error(self): def foo(a: 'Noode[T]'): pass with self.assertRaises(NameError): get_type_hints(foo, locals()) def test_no_type_check(self): @no_type_check def foo(a: 'whatevers') -> {}: pass th = get_type_hints(foo) self.assertEqual(th, {}) def test_no_type_check_class(self): @no_type_check class C: def foo(a: 'whatevers') -> {}: pass cth = get_type_hints(C.foo) self.assertEqual(cth, {}) ith = get_type_hints(C().foo) self.assertEqual(ith, {}) def test_no_type_check_no_bases(self): class C: def meth(self, x: int): ... @no_type_check class D(C): c = C # verify that @no_type_check never affects bases self.assertEqual(get_type_hints(C.meth), {'x': int}) def test_no_type_check_forward_ref_as_string(self): class C: foo: typing.ClassVar[int] = 7 class D: foo: ClassVar[int] = 7 class E: foo: 'typing.ClassVar[int]' = 7 class F: foo: 'ClassVar[int]' = 7 expected_result = {'foo': typing.ClassVar[int]} for clazz in [C, D, E, F]: self.assertEqual(get_type_hints(clazz), expected_result) def test_nested_classvar_fails_forward_ref_check(self): class E: foo: 'typing.ClassVar[typing.ClassVar[int]]' = 7 class F: foo: ClassVar['ClassVar[int]'] = 7 for clazz in [E, F]: with self.assertRaises(TypeError): get_type_hints(clazz) def test_meta_no_type_check(self): @no_type_check_decorator def magic_decorator(func): return func self.assertEqual(magic_decorator.__name__, 'magic_decorator') @magic_decorator def foo(a: 'whatevers') -> {}: pass @magic_decorator class C: def foo(a: 'whatevers') -> {}: pass self.assertEqual(foo.__name__, 'foo') th = get_type_hints(foo) self.assertEqual(th, {}) cth = get_type_hints(C.foo) self.assertEqual(cth, {}) ith = get_type_hints(C().foo) self.assertEqual(ith, {}) def test_default_globals(self): code = ("class C:\n" " def foo(self, a: 'C') -> 'D': pass\n" "class D:\n" " def bar(self, b: 'D') -> C: pass\n" ) ns = {} exec(code, ns) hints = get_type_hints(ns['C'].foo) self.assertEqual(hints, {'a': ns['C'], 'return': ns['D']}) def test_final_forward_ref(self): self.assertEqual(gth(Loop, globals())['attr'], Final[Loop]) self.assertNotEqual(gth(Loop, globals())['attr'], Final[int]) self.assertNotEqual(gth(Loop, globals())['attr'], Final) def test_or(self): X = ForwardRef('X') # __or__/__ror__ itself self.assertEqual(X | "x", Union[X, "x"]) self.assertEqual("x" | X, Union["x", X]) class OverloadTests(BaseTestCase): def test_overload_fails(self): from typing import overload with self.assertRaises(RuntimeError): @overload def blah(): pass blah() def test_overload_succeeds(self): from typing import overload @overload def blah(): pass def blah(): pass blah() ASYNCIO_TESTS = """ import asyncio T_a = TypeVar('T_a') class AwaitableWrapper(typing.Awaitable[T_a]): def __init__(self, value): self.value = value def __await__(self) -> typing.Iterator[T_a]: yield return self.value class AsyncIteratorWrapper(typing.AsyncIterator[T_a]): def __init__(self, value: typing.Iterable[T_a]): self.value = value def __aiter__(self) -> typing.AsyncIterator[T_a]: return self async def __anext__(self) -> T_a: data = await self.value if data: return data else: raise StopAsyncIteration class ACM: async def __aenter__(self) -> int: return 42 async def __aexit__(self, etype, eval, tb): return None """ try: exec(ASYNCIO_TESTS) except ImportError: ASYNCIO = False # multithreading is not enabled else: ASYNCIO = True # Definitions needed for features introduced in Python 3.6 from test import ann_module, ann_module2, ann_module3, ann_module5, ann_module6 from typing import AsyncContextManager class A: y: float class B(A): x: ClassVar[Optional['B']] = None y: int b: int class CSub(B): z: ClassVar['CSub'] = B() class G(Generic[T]): lst: ClassVar[List[T]] = [] class Loop: attr: Final['Loop'] class NoneAndForward: parent: 'NoneAndForward' meaning: None class CoolEmployee(NamedTuple): name: str cool: int class CoolEmployeeWithDefault(NamedTuple): name: str cool: int = 0 class XMeth(NamedTuple): x: int def double(self): return 2 * self.x class XRepr(NamedTuple): x: int y: int = 1 def __str__(self): return f'{self.x} -> {self.y}' def __add__(self, other): return 0 Label = TypedDict('Label', [('label', str)]) class Point2D(TypedDict): x: int y: int class Bar(_typed_dict_helper.Foo, total=False): b: int class LabelPoint2D(Point2D, Label): ... class Options(TypedDict, total=False): log_level: int log_path: str class HasForeignBaseClass(mod_generics_cache.A): some_xrepr: 'XRepr' other_a: 'mod_generics_cache.A' async def g_with(am: AsyncContextManager[int]): x: int async with am as x: return x try: g_with(ACM()).send(None) except StopIteration as e: assert e.args[0] == 42 gth = get_type_hints class ForRefExample: @ann_module.dec def func(self: 'ForRefExample'): pass @ann_module.dec @ann_module.dec def nested(self: 'ForRefExample'): pass class GetTypeHintTests(BaseTestCase): def test_get_type_hints_from_various_objects(self): # For invalid objects should fail with TypeError (not AttributeError etc). with self.assertRaises(TypeError): gth(123) with self.assertRaises(TypeError): gth('abc') with self.assertRaises(TypeError): gth(None) def test_get_type_hints_modules(self): ann_module_type_hints = {1: 2, 'f': Tuple[int, int], 'x': int, 'y': str, 'u': int | float} self.assertEqual(gth(ann_module), ann_module_type_hints) self.assertEqual(gth(ann_module2), {}) self.assertEqual(gth(ann_module3), {}) @skip("known bug") def test_get_type_hints_modules_forwardref(self): # FIXME: This currently exposes a bug in typing. Cached forward references # don't account for the case where there are multiple types of the same # name coming from different modules in the same program. mgc_hints = {'default_a': Optional[mod_generics_cache.A], 'default_b': Optional[mod_generics_cache.B]} self.assertEqual(gth(mod_generics_cache), mgc_hints) def test_get_type_hints_classes(self): self.assertEqual(gth(ann_module.C), # gth will find the right globalns {'y': Optional[ann_module.C]}) self.assertIsInstance(gth(ann_module.j_class), dict) self.assertEqual(gth(ann_module.M), {'123': 123, 'o': type}) self.assertEqual(gth(ann_module.D), {'j': str, 'k': str, 'y': Optional[ann_module.C]}) self.assertEqual(gth(ann_module.Y), {'z': int}) self.assertEqual(gth(ann_module.h_class), {'y': Optional[ann_module.C]}) self.assertEqual(gth(ann_module.S), {'x': str, 'y': str}) self.assertEqual(gth(ann_module.foo), {'x': int}) self.assertEqual(gth(NoneAndForward), {'parent': NoneAndForward, 'meaning': type(None)}) self.assertEqual(gth(HasForeignBaseClass), {'some_xrepr': XRepr, 'other_a': mod_generics_cache.A, 'some_b': mod_generics_cache.B}) self.assertEqual(gth(XRepr.__new__), {'x': int, 'y': int}) self.assertEqual(gth(mod_generics_cache.B), {'my_inner_a1': mod_generics_cache.B.A, 'my_inner_a2': mod_generics_cache.B.A, 'my_outer_a': mod_generics_cache.A}) def test_respect_no_type_check(self): @no_type_check class NoTpCheck: class Inn: def __init__(self, x: 'not a type'): ... self.assertTrue(NoTpCheck.__no_type_check__) self.assertTrue(NoTpCheck.Inn.__init__.__no_type_check__) self.assertEqual(gth(ann_module2.NTC.meth), {}) class ABase(Generic[T]): def meth(x: int): ... @no_type_check class Der(ABase): ... self.assertEqual(gth(ABase.meth), {'x': int}) def test_get_type_hints_for_builtins(self): # Should not fail for built-in classes and functions. self.assertEqual(gth(int), {}) self.assertEqual(gth(type), {}) self.assertEqual(gth(dir), {}) self.assertEqual(gth(len), {}) self.assertEqual(gth(object.__str__), {}) self.assertEqual(gth(object().__str__), {}) self.assertEqual(gth(str.join), {}) def test_previous_behavior(self): def testf(x, y): ... testf.__annotations__['x'] = 'int' self.assertEqual(gth(testf), {'x': int}) def testg(x: None): ... self.assertEqual(gth(testg), {'x': type(None)}) def test_get_type_hints_for_object_with_annotations(self): class A: ... class B: ... b = B() b.__annotations__ = {'x': 'A'} self.assertEqual(gth(b, locals()), {'x': A}) def test_get_type_hints_ClassVar(self): self.assertEqual(gth(ann_module2.CV, ann_module2.__dict__), {'var': typing.ClassVar[ann_module2.CV]}) self.assertEqual(gth(B, globals()), {'y': int, 'x': ClassVar[Optional[B]], 'b': int}) self.assertEqual(gth(CSub, globals()), {'z': ClassVar[CSub], 'y': int, 'b': int, 'x': ClassVar[Optional[B]]}) self.assertEqual(gth(G), {'lst': ClassVar[List[T]]}) def test_get_type_hints_wrapped_decoratored_func(self): expects = {'self': ForRefExample} self.assertEqual(gth(ForRefExample.func), expects) self.assertEqual(gth(ForRefExample.nested), expects) def test_get_type_hints_annotated(self): def foobar(x: List['X']): ... X = Annotated[int, (1, 10)] self.assertEqual( get_type_hints(foobar, globals(), locals()), {'x': List[int]} ) self.assertEqual( get_type_hints(foobar, globals(), locals(), include_extras=True), {'x': List[Annotated[int, (1, 10)]]} ) def foobar(x: list[ForwardRef('X')]): ... X = Annotated[int, (1, 10)] self.assertEqual( get_type_hints(foobar, globals(), locals()), {'x': list[int]} ) self.assertEqual( get_type_hints(foobar, globals(), locals(), include_extras=True), {'x': list[Annotated[int, (1, 10)]]} ) BA = Tuple[Annotated[T, (1, 0)], ...] def barfoo(x: BA): ... self.assertEqual(get_type_hints(barfoo, globals(), locals())['x'], Tuple[T, ...]) self.assertIs( get_type_hints(barfoo, globals(), locals(), include_extras=True)['x'], BA ) BA = tuple[Annotated[T, (1, 0)], ...] def barfoo(x: BA): ... self.assertEqual(get_type_hints(barfoo, globals(), locals())['x'], tuple[T, ...]) self.assertIs( get_type_hints(barfoo, globals(), locals(), include_extras=True)['x'], BA ) def barfoo2(x: typing.Callable[..., Annotated[List[T], "const"]], y: typing.Union[int, Annotated[T, "mutable"]]): ... self.assertEqual( get_type_hints(barfoo2, globals(), locals()), {'x': typing.Callable[..., List[T]], 'y': typing.Union[int, T]} ) BA2 = typing.Callable[..., List[T]] def barfoo3(x: BA2): ... self.assertIs( get_type_hints(barfoo3, globals(), locals(), include_extras=True)["x"], BA2 ) BA3 = typing.Annotated[int | float, "const"] def barfoo4(x: BA3): ... self.assertEqual( get_type_hints(barfoo4, globals(), locals()), {"x": int | float} ) self.assertEqual( get_type_hints(barfoo4, globals(), locals(), include_extras=True), {"x": typing.Annotated[int | float, "const"]} ) def test_get_type_hints_annotated_refs(self): Const = Annotated[T, "Const"] class MySet(Generic[T]): def __ior__(self, other: "Const[MySet[T]]") -> "MySet[T]": ... def __iand__(self, other: Const["MySet[T]"]) -> "MySet[T]": ... self.assertEqual( get_type_hints(MySet.__iand__, globals(), locals()), {'other': MySet[T], 'return': MySet[T]} ) self.assertEqual( get_type_hints(MySet.__iand__, globals(), locals(), include_extras=True), {'other': Const[MySet[T]], 'return': MySet[T]} ) self.assertEqual( get_type_hints(MySet.__ior__, globals(), locals()), {'other': MySet[T], 'return': MySet[T]} ) def test_get_type_hints_classes_str_annotations(self): class Foo: y = str x: 'y' # This previously raised an error under PEP 563. self.assertEqual(get_type_hints(Foo), {'x': str}) def test_get_type_hints_bad_module(self): # bpo-41515 class BadModule: pass BadModule.__module__ = 'bad' # Something not in sys.modules self.assertNotIn('bad', sys.modules) self.assertEqual(get_type_hints(BadModule), {}) def test_get_type_hints_annotated_bad_module(self): # See https://bugs.python.org/issue44468 class BadBase: foo: tuple class BadType(BadBase): bar: list BadType.__module__ = BadBase.__module__ = 'bad' self.assertNotIn('bad', sys.modules) self.assertEqual(get_type_hints(BadType), {'foo': tuple, 'bar': list}) class GetUtilitiesTestCase(TestCase): def test_get_origin(self): T = TypeVar('T') P = ParamSpec('P') class C(Generic[T]): pass self.assertIs(get_origin(C[int]), C) self.assertIs(get_origin(C[T]), C) self.assertIs(get_origin(int), None) self.assertIs(get_origin(ClassVar[int]), ClassVar) self.assertIs(get_origin(Union[int, str]), Union) self.assertIs(get_origin(Literal[42, 43]), Literal) self.assertIs(get_origin(Final[List[int]]), Final) self.assertIs(get_origin(Generic), Generic) self.assertIs(get_origin(Generic[T]), Generic) self.assertIs(get_origin(List[Tuple[T, T]][int]), list) self.assertIs(get_origin(Annotated[T, 'thing']), Annotated) self.assertIs(get_origin(List), list) self.assertIs(get_origin(Tuple), tuple) self.assertIs(get_origin(Callable), collections.abc.Callable) self.assertIs(get_origin(list[int]), list) self.assertIs(get_origin(list), None) self.assertIs(get_origin(list | str), types.UnionType) self.assertIs(get_origin(P.args), P) self.assertIs(get_origin(P.kwargs), P) def test_get_args(self): T = TypeVar('T') class C(Generic[T]): pass self.assertEqual(get_args(C[int]), (int,)) self.assertEqual(get_args(C[T]), (T,)) self.assertEqual(get_args(int), ()) self.assertEqual(get_args(ClassVar[int]), (int,)) self.assertEqual(get_args(Union[int, str]), (int, str)) self.assertEqual(get_args(Literal[42, 43]), (42, 43)) self.assertEqual(get_args(Final[List[int]]), (List[int],)) self.assertEqual(get_args(Union[int, Tuple[T, int]][str]), (int, Tuple[str, int])) self.assertEqual(get_args(typing.Dict[int, Tuple[T, T]][Optional[int]]), (int, Tuple[Optional[int], Optional[int]])) self.assertEqual(get_args(Callable[[], T][int]), ([], int)) self.assertEqual(get_args(Callable[..., int]), (..., int)) self.assertEqual(get_args(Union[int, Callable[[Tuple[T, ...]], str]]), (int, Callable[[Tuple[T, ...]], str])) self.assertEqual(get_args(Tuple[int, ...]), (int, ...)) self.assertEqual(get_args(Tuple[()]), ((),)) self.assertEqual(get_args(Annotated[T, 'one', 2, ['three']]), (T, 'one', 2, ['three'])) self.assertEqual(get_args(List), ()) self.assertEqual(get_args(Tuple), ()) self.assertEqual(get_args(Callable), ()) self.assertEqual(get_args(list[int]), (int,)) self.assertEqual(get_args(list), ()) self.assertEqual(get_args(collections.abc.Callable[[int], str]), ([int], str)) self.assertEqual(get_args(collections.abc.Callable[..., str]), (..., str)) self.assertEqual(get_args(collections.abc.Callable[[], str]), ([], str)) self.assertEqual(get_args(collections.abc.Callable[[int], str]), get_args(Callable[[int], str])) P = ParamSpec('P') self.assertEqual(get_args(Callable[P, int]), (P, int)) self.assertEqual(get_args(Callable[Concatenate[int, P], int]), (Concatenate[int, P], int)) self.assertEqual(get_args(list | str), (list, str)) def test_forward_ref_and_final(self): # https://bugs.python.org/issue45166 hints = get_type_hints(ann_module5) self.assertEqual(hints, {'name': Final[str]}) hints = get_type_hints(ann_module5.MyClass) self.assertEqual(hints, {'value': Final}) def test_top_level_class_var(self): # https://bugs.python.org/issue45166 with self.assertRaisesRegex( TypeError, r'typing.ClassVar\[int\] is not valid as type argument', ): get_type_hints(ann_module6) class CollectionsAbcTests(BaseTestCase): def test_hashable(self): self.assertIsInstance(42, typing.Hashable) self.assertNotIsInstance([], typing.Hashable) def test_iterable(self): self.assertIsInstance([], typing.Iterable) # Due to ABC caching, the second time takes a separate code # path and could fail. So call this a few times. self.assertIsInstance([], typing.Iterable) self.assertIsInstance([], typing.Iterable) self.assertNotIsInstance(42, typing.Iterable) # Just in case, also test issubclass() a few times. self.assertIsSubclass(list, typing.Iterable) self.assertIsSubclass(list, typing.Iterable) def test_iterator(self): it = iter([]) self.assertIsInstance(it, typing.Iterator) self.assertNotIsInstance(42, typing.Iterator) @skipUnless(ASYNCIO, 'Python 3.5 and multithreading required') def test_awaitable(self): ns = {} exec( "async def foo() -> typing.Awaitable[int]:\n" " return await AwaitableWrapper(42)\n", globals(), ns) foo = ns['foo'] g = foo() self.assertIsInstance(g, typing.Awaitable) self.assertNotIsInstance(foo, typing.Awaitable) g.send(None) # Run foo() till completion, to avoid warning. @skipUnless(ASYNCIO, 'Python 3.5 and multithreading required') def test_coroutine(self): ns = {} exec( "async def foo():\n" " return\n", globals(), ns) foo = ns['foo'] g = foo() self.assertIsInstance(g, typing.Coroutine) with self.assertRaises(TypeError): isinstance(g, typing.Coroutine[int]) self.assertNotIsInstance(foo, typing.Coroutine) try: g.send(None) except StopIteration: pass @skipUnless(ASYNCIO, 'Python 3.5 and multithreading required') def test_async_iterable(self): base_it = range(10) # type: Iterator[int] it = AsyncIteratorWrapper(base_it) self.assertIsInstance(it, typing.AsyncIterable) self.assertIsInstance(it, typing.AsyncIterable) self.assertNotIsInstance(42, typing.AsyncIterable) @skipUnless(ASYNCIO, 'Python 3.5 and multithreading required') def test_async_iterator(self): base_it = range(10) # type: Iterator[int] it = AsyncIteratorWrapper(base_it) self.assertIsInstance(it, typing.AsyncIterator) self.assertNotIsInstance(42, typing.AsyncIterator) def test_sized(self): self.assertIsInstance([], typing.Sized) self.assertNotIsInstance(42, typing.Sized) def test_container(self): self.assertIsInstance([], typing.Container) self.assertNotIsInstance(42, typing.Container) def test_collection(self): if hasattr(typing, 'Collection'): self.assertIsInstance(tuple(), typing.Collection) self.assertIsInstance(frozenset(), typing.Collection) self.assertIsSubclass(dict, typing.Collection) self.assertNotIsInstance(42, typing.Collection) def test_abstractset(self): self.assertIsInstance(set(), typing.AbstractSet) self.assertNotIsInstance(42, typing.AbstractSet) def test_mutableset(self): self.assertIsInstance(set(), typing.MutableSet) self.assertNotIsInstance(frozenset(), typing.MutableSet) def test_mapping(self): self.assertIsInstance({}, typing.Mapping) self.assertNotIsInstance(42, typing.Mapping) def test_mutablemapping(self): self.assertIsInstance({}, typing.MutableMapping) self.assertNotIsInstance(42, typing.MutableMapping) def test_sequence(self): self.assertIsInstance([], typing.Sequence) self.assertNotIsInstance(42, typing.Sequence) def test_mutablesequence(self): self.assertIsInstance([], typing.MutableSequence) self.assertNotIsInstance((), typing.MutableSequence) def test_bytestring(self): self.assertIsInstance(b'', typing.ByteString) self.assertIsInstance(bytearray(b''), typing.ByteString) def test_list(self): self.assertIsSubclass(list, typing.List) def test_deque(self): self.assertIsSubclass(collections.deque, typing.Deque) class MyDeque(typing.Deque[int]): ... self.assertIsInstance(MyDeque(), collections.deque) def test_counter(self): self.assertIsSubclass(collections.Counter, typing.Counter) def test_set(self): self.assertIsSubclass(set, typing.Set) self.assertNotIsSubclass(frozenset, typing.Set) def test_frozenset(self): self.assertIsSubclass(frozenset, typing.FrozenSet) self.assertNotIsSubclass(set, typing.FrozenSet) def test_dict(self): self.assertIsSubclass(dict, typing.Dict) def test_dict_subscribe(self): K = TypeVar('K') V = TypeVar('V') self.assertEqual(Dict[K, V][str, int], Dict[str, int]) self.assertEqual(Dict[K, int][str], Dict[str, int]) self.assertEqual(Dict[str, V][int], Dict[str, int]) self.assertEqual(Dict[K, List[V]][str, int], Dict[str, List[int]]) self.assertEqual(Dict[K, List[int]][str], Dict[str, List[int]]) self.assertEqual(Dict[K, list[V]][str, int], Dict[str, list[int]]) self.assertEqual(Dict[K, list[int]][str], Dict[str, list[int]]) def test_no_list_instantiation(self): with self.assertRaises(TypeError): typing.List() with self.assertRaises(TypeError): typing.List[T]() with self.assertRaises(TypeError): typing.List[int]() def test_list_subclass(self): class MyList(typing.List[int]): pass a = MyList() self.assertIsInstance(a, MyList) self.assertIsInstance(a, typing.Sequence) self.assertIsSubclass(MyList, list) self.assertNotIsSubclass(list, MyList) def test_no_dict_instantiation(self): with self.assertRaises(TypeError): typing.Dict() with self.assertRaises(TypeError): typing.Dict[KT, VT]() with self.assertRaises(TypeError): typing.Dict[str, int]() def test_dict_subclass(self): class MyDict(typing.Dict[str, int]): pass d = MyDict() self.assertIsInstance(d, MyDict) self.assertIsInstance(d, typing.MutableMapping) self.assertIsSubclass(MyDict, dict) self.assertNotIsSubclass(dict, MyDict) def test_defaultdict_instantiation(self): self.assertIs(type(typing.DefaultDict()), collections.defaultdict) self.assertIs(type(typing.DefaultDict[KT, VT]()), collections.defaultdict) self.assertIs(type(typing.DefaultDict[str, int]()), collections.defaultdict) def test_defaultdict_subclass(self): class MyDefDict(typing.DefaultDict[str, int]): pass dd = MyDefDict() self.assertIsInstance(dd, MyDefDict) self.assertIsSubclass(MyDefDict, collections.defaultdict) self.assertNotIsSubclass(collections.defaultdict, MyDefDict) def test_ordereddict_instantiation(self): self.assertIs(type(typing.OrderedDict()), collections.OrderedDict) self.assertIs(type(typing.OrderedDict[KT, VT]()), collections.OrderedDict) self.assertIs(type(typing.OrderedDict[str, int]()), collections.OrderedDict) def test_ordereddict_subclass(self): class MyOrdDict(typing.OrderedDict[str, int]): pass od = MyOrdDict() self.assertIsInstance(od, MyOrdDict) self.assertIsSubclass(MyOrdDict, collections.OrderedDict) self.assertNotIsSubclass(collections.OrderedDict, MyOrdDict) @skipUnless(sys.version_info >= (3, 3), 'ChainMap was added in 3.3') def test_chainmap_instantiation(self): self.assertIs(type(typing.ChainMap()), collections.ChainMap) self.assertIs(type(typing.ChainMap[KT, VT]()), collections.ChainMap) self.assertIs(type(typing.ChainMap[str, int]()), collections.ChainMap) class CM(typing.ChainMap[KT, VT]): ... self.assertIs(type(CM[int, str]()), CM) @skipUnless(sys.version_info >= (3, 3), 'ChainMap was added in 3.3') def test_chainmap_subclass(self): class MyChainMap(typing.ChainMap[str, int]): pass cm = MyChainMap() self.assertIsInstance(cm, MyChainMap) self.assertIsSubclass(MyChainMap, collections.ChainMap) self.assertNotIsSubclass(collections.ChainMap, MyChainMap) def test_deque_instantiation(self): self.assertIs(type(typing.Deque()), collections.deque) self.assertIs(type(typing.Deque[T]()), collections.deque) self.assertIs(type(typing.Deque[int]()), collections.deque) class D(typing.Deque[T]): ... self.assertIs(type(D[int]()), D) def test_counter_instantiation(self): self.assertIs(type(typing.Counter()), collections.Counter) self.assertIs(type(typing.Counter[T]()), collections.Counter) self.assertIs(type(typing.Counter[int]()), collections.Counter) class C(typing.Counter[T]): ... self.assertIs(type(C[int]()), C) def test_counter_subclass_instantiation(self): class MyCounter(typing.Counter[int]): pass d = MyCounter() self.assertIsInstance(d, MyCounter) self.assertIsInstance(d, typing.Counter) self.assertIsInstance(d, collections.Counter) def test_no_set_instantiation(self): with self.assertRaises(TypeError): typing.Set() with self.assertRaises(TypeError): typing.Set[T]() with self.assertRaises(TypeError): typing.Set[int]() def test_set_subclass_instantiation(self): class MySet(typing.Set[int]): pass d = MySet() self.assertIsInstance(d, MySet) def test_no_frozenset_instantiation(self): with self.assertRaises(TypeError): typing.FrozenSet() with self.assertRaises(TypeError): typing.FrozenSet[T]() with self.assertRaises(TypeError): typing.FrozenSet[int]() def test_frozenset_subclass_instantiation(self): class MyFrozenSet(typing.FrozenSet[int]): pass d = MyFrozenSet() self.assertIsInstance(d, MyFrozenSet) def test_no_tuple_instantiation(self): with self.assertRaises(TypeError): Tuple() with self.assertRaises(TypeError): Tuple[T]() with self.assertRaises(TypeError): Tuple[int]() def test_generator(self): def foo(): yield 42 g = foo() self.assertIsSubclass(type(g), typing.Generator) def test_no_generator_instantiation(self): with self.assertRaises(TypeError): typing.Generator() with self.assertRaises(TypeError): typing.Generator[T, T, T]() with self.assertRaises(TypeError): typing.Generator[int, int, int]() def test_async_generator(self): ns = {} exec("async def f():\n" " yield 42\n", globals(), ns) g = ns['f']() self.assertIsSubclass(type(g), typing.AsyncGenerator) def test_no_async_generator_instantiation(self): with self.assertRaises(TypeError): typing.AsyncGenerator() with self.assertRaises(TypeError): typing.AsyncGenerator[T, T]() with self.assertRaises(TypeError): typing.AsyncGenerator[int, int]() def test_subclassing(self): class MMA(typing.MutableMapping): pass with self.assertRaises(TypeError): # It's abstract MMA() class MMC(MMA): def __getitem__(self, k): return None def __setitem__(self, k, v): pass def __delitem__(self, k): pass def __iter__(self): return iter(()) def __len__(self): return 0 self.assertEqual(len(MMC()), 0) assert callable(MMC.update) self.assertIsInstance(MMC(), typing.Mapping) class MMB(typing.MutableMapping[KT, VT]): def __getitem__(self, k): return None def __setitem__(self, k, v): pass def __delitem__(self, k): pass def __iter__(self): return iter(()) def __len__(self): return 0 self.assertEqual(len(MMB()), 0) self.assertEqual(len(MMB[str, str]()), 0) self.assertEqual(len(MMB[KT, VT]()), 0) self.assertNotIsSubclass(dict, MMA) self.assertNotIsSubclass(dict, MMB) self.assertIsSubclass(MMA, typing.Mapping) self.assertIsSubclass(MMB, typing.Mapping) self.assertIsSubclass(MMC, typing.Mapping) self.assertIsInstance(MMB[KT, VT](), typing.Mapping) self.assertIsInstance(MMB[KT, VT](), collections.abc.Mapping) self.assertIsSubclass(MMA, collections.abc.Mapping) self.assertIsSubclass(MMB, collections.abc.Mapping) self.assertIsSubclass(MMC, collections.abc.Mapping) with self.assertRaises(TypeError): issubclass(MMB[str, str], typing.Mapping) self.assertIsSubclass(MMC, MMA) class I(typing.Iterable): ... self.assertNotIsSubclass(list, I) class G(typing.Generator[int, int, int]): ... def g(): yield 0 self.assertIsSubclass(G, typing.Generator) self.assertIsSubclass(G, typing.Iterable) self.assertIsSubclass(G, collections.abc.Generator) self.assertIsSubclass(G, collections.abc.Iterable) self.assertNotIsSubclass(type(g), G) def test_subclassing_async_generator(self): class G(typing.AsyncGenerator[int, int]): def asend(self, value): pass def athrow(self, typ, val=None, tb=None): pass ns = {} exec('async def g(): yield 0', globals(), ns) g = ns['g'] self.assertIsSubclass(G, typing.AsyncGenerator) self.assertIsSubclass(G, typing.AsyncIterable) self.assertIsSubclass(G, collections.abc.AsyncGenerator) self.assertIsSubclass(G, collections.abc.AsyncIterable) self.assertNotIsSubclass(type(g), G) instance = G() self.assertIsInstance(instance, typing.AsyncGenerator) self.assertIsInstance(instance, typing.AsyncIterable) self.assertIsInstance(instance, collections.abc.AsyncGenerator) self.assertIsInstance(instance, collections.abc.AsyncIterable) self.assertNotIsInstance(type(g), G) self.assertNotIsInstance(g, G) def test_subclassing_subclasshook(self): class Base(typing.Iterable): @classmethod def __subclasshook__(cls, other): if other.__name__ == 'Foo': return True else: return False class C(Base): ... class Foo: ... class Bar: ... self.assertIsSubclass(Foo, Base) self.assertIsSubclass(Foo, C) self.assertNotIsSubclass(Bar, C) def test_subclassing_register(self): class A(typing.Container): ... class B(A): ... class C: ... A.register(C) self.assertIsSubclass(C, A) self.assertNotIsSubclass(C, B) class D: ... B.register(D) self.assertIsSubclass(D, A) self.assertIsSubclass(D, B) class M(): ... collections.abc.MutableMapping.register(M) self.assertIsSubclass(M, typing.Mapping) def test_collections_as_base(self): class M(collections.abc.Mapping): ... self.assertIsSubclass(M, typing.Mapping) self.assertIsSubclass(M, typing.Iterable) class S(collections.abc.MutableSequence): ... self.assertIsSubclass(S, typing.MutableSequence) self.assertIsSubclass(S, typing.Iterable) class I(collections.abc.Iterable): ... self.assertIsSubclass(I, typing.Iterable) class A(collections.abc.Mapping, metaclass=abc.ABCMeta): ... class B: ... A.register(B) self.assertIsSubclass(B, typing.Mapping) class OtherABCTests(BaseTestCase): def test_contextmanager(self): @contextlib.contextmanager def manager(): yield 42 cm = manager() self.assertIsInstance(cm, typing.ContextManager) self.assertNotIsInstance(42, typing.ContextManager) @skipUnless(ASYNCIO, 'Python 3.5 required') def test_async_contextmanager(self): class NotACM: pass self.assertIsInstance(ACM(), typing.AsyncContextManager) self.assertNotIsInstance(NotACM(), typing.AsyncContextManager) @contextlib.contextmanager def manager(): yield 42 cm = manager() self.assertNotIsInstance(cm, typing.AsyncContextManager) self.assertEqual(typing.AsyncContextManager[int].__args__, (int,)) with self.assertRaises(TypeError): isinstance(42, typing.AsyncContextManager[int]) with self.assertRaises(TypeError): typing.AsyncContextManager[int, str] class TypeTests(BaseTestCase): def test_type_basic(self): class User: pass class BasicUser(User): pass class ProUser(User): pass def new_user(user_class: Type[User]) -> User: return user_class() new_user(BasicUser) def test_type_typevar(self): class User: pass class BasicUser(User): pass class ProUser(User): pass U = TypeVar('U', bound=User) def new_user(user_class: Type[U]) -> U: return user_class() new_user(BasicUser) def test_type_optional(self): A = Optional[Type[BaseException]] def foo(a: A) -> Optional[BaseException]: if a is None: return None else: return a() assert isinstance(foo(KeyboardInterrupt), KeyboardInterrupt) assert foo(None) is None class TestModules(TestCase): func_names = ['_idfunc'] def test_py_functions(self): for fname in self.func_names: self.assertEqual(getattr(py_typing, fname).__module__, 'typing') @skipUnless(c_typing, 'requires _typing') def test_c_functions(self): for fname in self.func_names: self.assertEqual(getattr(c_typing, fname).__module__, '_typing') class NewTypeTests: def cleanup(self): for f in self.module._cleanups: f() @classmethod def setUpClass(cls): sys.modules['typing'] = cls.module global UserId UserId = cls.module.NewType('UserId', int) cls.UserName = cls.module.NewType(cls.__qualname__ + '.UserName', str) @classmethod def tearDownClass(cls): global UserId del UserId del cls.UserName sys.modules['typing'] = typing def tearDown(self): self.cleanup() def test_basic(self): self.assertIsInstance(UserId(5), int) self.assertIsInstance(self.UserName('Joe'), str) self.assertEqual(UserId(5) + 1, 6) def test_errors(self): with self.assertRaises(TypeError): issubclass(UserId, int) with self.assertRaises(TypeError): class D(UserId): pass def test_or(self): for cls in (int, self.UserName): with self.subTest(cls=cls): self.assertEqual(UserId | cls, self.module.Union[UserId, cls]) self.assertEqual(cls | UserId, self.module.Union[cls, UserId]) self.assertEqual(self.module.get_args(UserId | cls), (UserId, cls)) self.assertEqual(self.module.get_args(cls | UserId), (cls, UserId)) def test_special_attrs(self): self.assertEqual(UserId.__name__, 'UserId') self.assertEqual(UserId.__qualname__, 'UserId') self.assertEqual(UserId.__module__, __name__) self.assertEqual(UserId.__supertype__, int) UserName = self.UserName self.assertEqual(UserName.__name__, 'UserName') self.assertEqual(UserName.__qualname__, self.__class__.__qualname__ + '.UserName') self.assertEqual(UserName.__module__, __name__) self.assertEqual(UserName.__supertype__, str) def test_repr(self): self.assertEqual(repr(UserId), f'{__name__}.UserId') self.assertEqual(repr(self.UserName), f'{__name__}.{self.__class__.__qualname__}.UserName') def test_pickle(self): UserAge = self.module.NewType('UserAge', float) for proto in range(pickle.HIGHEST_PROTOCOL + 1): with self.subTest(proto=proto): pickled = pickle.dumps(UserId, proto) loaded = pickle.loads(pickled) self.assertIs(loaded, UserId) pickled = pickle.dumps(self.UserName, proto) loaded = pickle.loads(pickled) self.assertIs(loaded, self.UserName) with self.assertRaises(pickle.PicklingError): pickle.dumps(UserAge, proto) def test_missing__name__(self): code = ("import typing\n" "NT = typing.NewType('NT', int)\n" ) exec(code, {}) class NewTypePythonTests(NewTypeTests, BaseTestCase): module = py_typing @skipUnless(c_typing, 'requires _typing') class NewTypeCTests(NewTypeTests, BaseTestCase): module = c_typing class NamedTupleTests(BaseTestCase): class NestedEmployee(NamedTuple): name: str cool: int def test_basics(self): Emp = NamedTuple('Emp', [('name', str), ('id', int)]) self.assertIsSubclass(Emp, tuple) joe = Emp('Joe', 42) jim = Emp(name='Jim', id=1) self.assertIsInstance(joe, Emp) self.assertIsInstance(joe, tuple) self.assertEqual(joe.name, 'Joe') self.assertEqual(joe.id, 42) self.assertEqual(jim.name, 'Jim') self.assertEqual(jim.id, 1) self.assertEqual(Emp.__name__, 'Emp') self.assertEqual(Emp._fields, ('name', 'id')) self.assertEqual(Emp.__annotations__, collections.OrderedDict([('name', str), ('id', int)])) def test_namedtuple_pyversion(self): if sys.version_info[:2] < (3, 6): with self.assertRaises(TypeError): NamedTuple('Name', one=int, other=str) with self.assertRaises(TypeError): class NotYet(NamedTuple): whatever = 0 def test_annotation_usage(self): tim = CoolEmployee('Tim', 9000) self.assertIsInstance(tim, CoolEmployee) self.assertIsInstance(tim, tuple) self.assertEqual(tim.name, 'Tim') self.assertEqual(tim.cool, 9000) self.assertEqual(CoolEmployee.__name__, 'CoolEmployee') self.assertEqual(CoolEmployee._fields, ('name', 'cool')) self.assertEqual(CoolEmployee.__annotations__, collections.OrderedDict(name=str, cool=int)) def test_annotation_usage_with_default(self): jelle = CoolEmployeeWithDefault('Jelle') self.assertIsInstance(jelle, CoolEmployeeWithDefault) self.assertIsInstance(jelle, tuple) self.assertEqual(jelle.name, 'Jelle') self.assertEqual(jelle.cool, 0) cooler_employee = CoolEmployeeWithDefault('Sjoerd', 1) self.assertEqual(cooler_employee.cool, 1) self.assertEqual(CoolEmployeeWithDefault.__name__, 'CoolEmployeeWithDefault') self.assertEqual(CoolEmployeeWithDefault._fields, ('name', 'cool')) self.assertEqual(CoolEmployeeWithDefault.__annotations__, dict(name=str, cool=int)) self.assertEqual(CoolEmployeeWithDefault._field_defaults, dict(cool=0)) with self.assertRaises(TypeError): class NonDefaultAfterDefault(NamedTuple): x: int = 3 y: int def test_annotation_usage_with_methods(self): self.assertEqual(XMeth(1).double(), 2) self.assertEqual(XMeth(42).x, XMeth(42)[0]) self.assertEqual(str(XRepr(42)), '42 -> 1') self.assertEqual(XRepr(1, 2) + XRepr(3), 0) with self.assertRaises(AttributeError): class XMethBad(NamedTuple): x: int def _fields(self): return 'no chance for this' with self.assertRaises(AttributeError): class XMethBad2(NamedTuple): x: int def _source(self): return 'no chance for this as well' def test_multiple_inheritance(self): class A: pass with self.assertRaises(TypeError): class X(NamedTuple, A): x: int def test_namedtuple_keyword_usage(self): LocalEmployee = NamedTuple("LocalEmployee", name=str, age=int) nick = LocalEmployee('Nick', 25) self.assertIsInstance(nick, tuple) self.assertEqual(nick.name, 'Nick') self.assertEqual(LocalEmployee.__name__, 'LocalEmployee') self.assertEqual(LocalEmployee._fields, ('name', 'age')) self.assertEqual(LocalEmployee.__annotations__, dict(name=str, age=int)) with self.assertRaises(TypeError): NamedTuple('Name', [('x', int)], y=str) with self.assertRaises(TypeError): NamedTuple('Name', x=1, y='a') def test_namedtuple_special_keyword_names(self): NT = NamedTuple("NT", cls=type, self=object, typename=str, fields=list) self.assertEqual(NT.__name__, 'NT') self.assertEqual(NT._fields, ('cls', 'self', 'typename', 'fields')) a = NT(cls=str, self=42, typename='foo', fields=[('bar', tuple)]) self.assertEqual(a.cls, str) self.assertEqual(a.self, 42) self.assertEqual(a.typename, 'foo') self.assertEqual(a.fields, [('bar', tuple)]) def test_empty_namedtuple(self): NT = NamedTuple('NT') class CNT(NamedTuple): pass # empty body for struct in [NT, CNT]: with self.subTest(struct=struct): self.assertEqual(struct._fields, ()) self.assertEqual(struct._field_defaults, {}) self.assertEqual(struct.__annotations__, {}) self.assertIsInstance(struct(), struct) def test_namedtuple_errors(self): with self.assertRaises(TypeError): NamedTuple.__new__() with self.assertRaises(TypeError): NamedTuple() with self.assertRaises(TypeError): NamedTuple('Emp', [('name', str)], None) with self.assertRaises(ValueError): NamedTuple('Emp', [('_name', str)]) with self.assertRaises(TypeError): NamedTuple(typename='Emp', name=str, id=int) with self.assertRaises(TypeError): NamedTuple('Emp', fields=[('name', str), ('id', int)]) def test_copy_and_pickle(self): global Emp # pickle wants to reference the class by name Emp = NamedTuple('Emp', [('name', str), ('cool', int)]) for cls in Emp, CoolEmployee, self.NestedEmployee: with self.subTest(cls=cls): jane = cls('jane', 37) for proto in range(pickle.HIGHEST_PROTOCOL + 1): z = pickle.dumps(jane, proto) jane2 = pickle.loads(z) self.assertEqual(jane2, jane) self.assertIsInstance(jane2, cls) jane2 = copy(jane) self.assertEqual(jane2, jane) self.assertIsInstance(jane2, cls) jane2 = deepcopy(jane) self.assertEqual(jane2, jane) self.assertIsInstance(jane2, cls) class TypedDictTests(BaseTestCase): def test_basics_functional_syntax(self): Emp = TypedDict('Emp', {'name': str, 'id': int}) self.assertIsSubclass(Emp, dict) self.assertIsSubclass(Emp, typing.MutableMapping) self.assertNotIsSubclass(Emp, collections.abc.Sequence) jim = Emp(name='Jim', id=1) self.assertIs(type(jim), dict) self.assertEqual(jim['name'], 'Jim') self.assertEqual(jim['id'], 1) self.assertEqual(Emp.__name__, 'Emp') self.assertEqual(Emp.__module__, __name__) self.assertEqual(Emp.__bases__, (dict,)) self.assertEqual(Emp.__annotations__, {'name': str, 'id': int}) self.assertEqual(Emp.__total__, True) def test_basics_keywords_syntax(self): Emp = TypedDict('Emp', name=str, id=int) self.assertIsSubclass(Emp, dict) self.assertIsSubclass(Emp, typing.MutableMapping) self.assertNotIsSubclass(Emp, collections.abc.Sequence) jim = Emp(name='Jim', id=1) self.assertIs(type(jim), dict) self.assertEqual(jim['name'], 'Jim') self.assertEqual(jim['id'], 1) self.assertEqual(Emp.__name__, 'Emp') self.assertEqual(Emp.__module__, __name__) self.assertEqual(Emp.__bases__, (dict,)) self.assertEqual(Emp.__annotations__, {'name': str, 'id': int}) self.assertEqual(Emp.__total__, True) def test_typeddict_special_keyword_names(self): TD = TypedDict("TD", cls=type, self=object, typename=str, _typename=int, fields=list, _fields=dict) self.assertEqual(TD.__name__, 'TD') self.assertEqual(TD.__annotations__, {'cls': type, 'self': object, 'typename': str, '_typename': int, 'fields': list, '_fields': dict}) a = TD(cls=str, self=42, typename='foo', _typename=53, fields=[('bar', tuple)], _fields={'baz', set}) self.assertEqual(a['cls'], str) self.assertEqual(a['self'], 42) self.assertEqual(a['typename'], 'foo') self.assertEqual(a['_typename'], 53) self.assertEqual(a['fields'], [('bar', tuple)]) self.assertEqual(a['_fields'], {'baz', set}) def test_typeddict_create_errors(self): with self.assertRaises(TypeError): TypedDict.__new__() with self.assertRaises(TypeError): TypedDict() with self.assertRaises(TypeError): TypedDict('Emp', [('name', str)], None) with self.assertRaises(TypeError): TypedDict(_typename='Emp', name=str, id=int) with self.assertRaises(TypeError): TypedDict('Emp', _fields={'name': str, 'id': int}) def test_typeddict_errors(self): Emp = TypedDict('Emp', {'name': str, 'id': int}) self.assertEqual(TypedDict.__module__, 'typing') jim = Emp(name='Jim', id=1) with self.assertRaises(TypeError): isinstance({}, Emp) with self.assertRaises(TypeError): isinstance(jim, Emp) with self.assertRaises(TypeError): issubclass(dict, Emp) with self.assertRaises(TypeError): TypedDict('Hi', x=1) with self.assertRaises(TypeError): TypedDict('Hi', [('x', int), ('y', 1)]) with self.assertRaises(TypeError): TypedDict('Hi', [('x', int)], y=int) def test_py36_class_syntax_usage(self): self.assertEqual(LabelPoint2D.__name__, 'LabelPoint2D') self.assertEqual(LabelPoint2D.__module__, __name__) self.assertEqual(LabelPoint2D.__annotations__, {'x': int, 'y': int, 'label': str}) self.assertEqual(LabelPoint2D.__bases__, (dict,)) self.assertEqual(LabelPoint2D.__total__, True) self.assertNotIsSubclass(LabelPoint2D, typing.Sequence) not_origin = Point2D(x=0, y=1) self.assertEqual(not_origin['x'], 0) self.assertEqual(not_origin['y'], 1) other = LabelPoint2D(x=0, y=1, label='hi') self.assertEqual(other['label'], 'hi') def test_pickle(self): global EmpD # pickle wants to reference the class by name EmpD = TypedDict('EmpD', name=str, id=int) jane = EmpD({'name': 'jane', 'id': 37}) for proto in range(pickle.HIGHEST_PROTOCOL + 1): z = pickle.dumps(jane, proto) jane2 = pickle.loads(z) self.assertEqual(jane2, jane) self.assertEqual(jane2, {'name': 'jane', 'id': 37}) ZZ = pickle.dumps(EmpD, proto) EmpDnew = pickle.loads(ZZ) self.assertEqual(EmpDnew({'name': 'jane', 'id': 37}), jane) def test_optional(self): EmpD = TypedDict('EmpD', name=str, id=int) self.assertEqual(typing.Optional[EmpD], typing.Union[None, EmpD]) self.assertNotEqual(typing.List[EmpD], typing.Tuple[EmpD]) def test_total(self): D = TypedDict('D', {'x': int}, total=False) self.assertEqual(D(), {}) self.assertEqual(D(x=1), {'x': 1}) self.assertEqual(D.__total__, False) self.assertEqual(D.__required_keys__, frozenset()) self.assertEqual(D.__optional_keys__, {'x'}) self.assertEqual(Options(), {}) self.assertEqual(Options(log_level=2), {'log_level': 2}) self.assertEqual(Options.__total__, False) self.assertEqual(Options.__required_keys__, frozenset()) self.assertEqual(Options.__optional_keys__, {'log_level', 'log_path'}) def test_optional_keys(self): class Point2Dor3D(Point2D, total=False): z: int assert Point2Dor3D.__required_keys__ == frozenset(['x', 'y']) assert Point2Dor3D.__optional_keys__ == frozenset(['z']) def test_keys_inheritance(self): class BaseAnimal(TypedDict): name: str class Animal(BaseAnimal, total=False): voice: str tail: bool class Cat(Animal): fur_color: str assert BaseAnimal.__required_keys__ == frozenset(['name']) assert BaseAnimal.__optional_keys__ == frozenset([]) assert BaseAnimal.__annotations__ == {'name': str} assert Animal.__required_keys__ == frozenset(['name']) assert Animal.__optional_keys__ == frozenset(['tail', 'voice']) assert Animal.__annotations__ == { 'name': str, 'tail': bool, 'voice': str, } assert Cat.__required_keys__ == frozenset(['name', 'fur_color']) assert Cat.__optional_keys__ == frozenset(['tail', 'voice']) assert Cat.__annotations__ == { 'fur_color': str, 'name': str, 'tail': bool, 'voice': str, } def test_is_typeddict(self): assert is_typeddict(Point2D) is True assert is_typeddict(Union[str, int]) is False # classes, not instances assert is_typeddict(Point2D()) is False def test_get_type_hints(self): self.assertEqual( get_type_hints(Bar), {'a': typing.Optional[int], 'b': int} ) class IOTests(BaseTestCase): def test_io(self): def stuff(a: IO) -> AnyStr: return a.readline() a = stuff.__annotations__['a'] self.assertEqual(a.__parameters__, (AnyStr,)) def test_textio(self): def stuff(a: TextIO) -> str: return a.readline() a = stuff.__annotations__['a'] self.assertEqual(a.__parameters__, ()) def test_binaryio(self): def stuff(a: BinaryIO) -> bytes: return a.readline() a = stuff.__annotations__['a'] self.assertEqual(a.__parameters__, ()) def test_io_submodule(self): with warnings.catch_warnings(record=True) as w: warnings.filterwarnings("default", category=DeprecationWarning) from typing.io import IO, TextIO, BinaryIO, __all__, __name__ self.assertIs(IO, typing.IO) self.assertIs(TextIO, typing.TextIO) self.assertIs(BinaryIO, typing.BinaryIO) self.assertEqual(set(__all__), set(['IO', 'TextIO', 'BinaryIO'])) self.assertEqual(__name__, 'typing.io') self.assertEqual(len(w), 1) class RETests(BaseTestCase): # Much of this is really testing _TypeAlias. def test_basics(self): pat = re.compile('[a-z]+', re.I) self.assertIsSubclass(pat.__class__, Pattern) self.assertIsSubclass(type(pat), Pattern) self.assertIsInstance(pat, Pattern) mat = pat.search('12345abcde.....') self.assertIsSubclass(mat.__class__, Match) self.assertIsSubclass(type(mat), Match) self.assertIsInstance(mat, Match) # these should just work Pattern[Union[str, bytes]] Match[Union[bytes, str]] def test_alias_equality(self): self.assertEqual(Pattern[str], Pattern[str]) self.assertNotEqual(Pattern[str], Pattern[bytes]) self.assertNotEqual(Pattern[str], Match[str]) self.assertNotEqual(Pattern[str], str) def test_errors(self): m = Match[Union[str, bytes]] with self.assertRaises(TypeError): m[str] with self.assertRaises(TypeError): # We don't support isinstance(). isinstance(42, Pattern[str]) with self.assertRaises(TypeError): # We don't support issubclass(). issubclass(Pattern[bytes], Pattern[str]) def test_repr(self): self.assertEqual(repr(Pattern), 'typing.Pattern') self.assertEqual(repr(Pattern[str]), 'typing.Pattern[str]') self.assertEqual(repr(Pattern[bytes]), 'typing.Pattern[bytes]') self.assertEqual(repr(Match), 'typing.Match') self.assertEqual(repr(Match[str]), 'typing.Match[str]') self.assertEqual(repr(Match[bytes]), 'typing.Match[bytes]') def test_re_submodule(self): with warnings.catch_warnings(record=True) as w: warnings.filterwarnings("default", category=DeprecationWarning) from typing.re import Match, Pattern, __all__, __name__ self.assertIs(Match, typing.Match) self.assertIs(Pattern, typing.Pattern) self.assertEqual(set(__all__), set(['Match', 'Pattern'])) self.assertEqual(__name__, 'typing.re') self.assertEqual(len(w), 1) def test_cannot_subclass(self): with self.assertRaises(TypeError) as ex: class A(typing.Match): pass self.assertEqual(str(ex.exception), "type 're.Match' is not an acceptable base type") class AnnotatedTests(BaseTestCase): def test_repr(self): self.assertEqual( repr(Annotated[int, 4, 5]), "typing.Annotated[int, 4, 5]" ) self.assertEqual( repr(Annotated[List[int], 4, 5]), "typing.Annotated[typing.List[int], 4, 5]" ) def test_flatten(self): A = Annotated[Annotated[int, 4], 5] self.assertEqual(A, Annotated[int, 4, 5]) self.assertEqual(A.__metadata__, (4, 5)) self.assertEqual(A.__origin__, int) def test_specialize(self): L = Annotated[List[T], "my decoration"] LI = Annotated[List[int], "my decoration"] self.assertEqual(L[int], Annotated[List[int], "my decoration"]) self.assertEqual(L[int].__metadata__, ("my decoration",)) self.assertEqual(L[int].__origin__, List[int]) with self.assertRaises(TypeError): LI[int] with self.assertRaises(TypeError): L[int, float] def test_hash_eq(self): self.assertEqual(len({Annotated[int, 4, 5], Annotated[int, 4, 5]}), 1) self.assertNotEqual(Annotated[int, 4, 5], Annotated[int, 5, 4]) self.assertNotEqual(Annotated[int, 4, 5], Annotated[str, 4, 5]) self.assertNotEqual(Annotated[int, 4], Annotated[int, 4, 4]) self.assertEqual( {Annotated[int, 4, 5], Annotated[int, 4, 5], Annotated[T, 4, 5]}, {Annotated[int, 4, 5], Annotated[T, 4, 5]} ) def test_instantiate(self): class C: classvar = 4 def __init__(self, x): self.x = x def __eq__(self, other): if not isinstance(other, C): return NotImplemented return other.x == self.x A = Annotated[C, "a decoration"] a = A(5) c = C(5) self.assertEqual(a, c) self.assertEqual(a.x, c.x) self.assertEqual(a.classvar, c.classvar) def test_instantiate_generic(self): MyCount = Annotated[typing.Counter[T], "my decoration"] self.assertEqual(MyCount([4, 4, 5]), {4: 2, 5: 1}) self.assertEqual(MyCount[int]([4, 4, 5]), {4: 2, 5: 1}) def test_cannot_instantiate_forward(self): A = Annotated["int", (5, 6)] with self.assertRaises(TypeError): A(5) def test_cannot_instantiate_type_var(self): A = Annotated[T, (5, 6)] with self.assertRaises(TypeError): A(5) def test_cannot_getattr_typevar(self): with self.assertRaises(AttributeError): Annotated[T, (5, 7)].x def test_attr_passthrough(self): class C: classvar = 4 A = Annotated[C, "a decoration"] self.assertEqual(A.classvar, 4) A.x = 5 self.assertEqual(C.x, 5) def test_hash_eq(self): self.assertEqual(len({Annotated[int, 4, 5], Annotated[int, 4, 5]}), 1) self.assertNotEqual(Annotated[int, 4, 5], Annotated[int, 5, 4]) self.assertNotEqual(Annotated[int, 4, 5], Annotated[str, 4, 5]) self.assertNotEqual(Annotated[int, 4], Annotated[int, 4, 4]) self.assertEqual( {Annotated[int, 4, 5], Annotated[int, 4, 5], Annotated[T, 4, 5]}, {Annotated[int, 4, 5], Annotated[T, 4, 5]} ) def test_cannot_subclass(self): with self.assertRaisesRegex(TypeError, "Cannot subclass .*Annotated"): class C(Annotated): pass def test_cannot_check_instance(self): with self.assertRaises(TypeError): isinstance(5, Annotated[int, "positive"]) def test_cannot_check_subclass(self): with self.assertRaises(TypeError): issubclass(int, Annotated[int, "positive"]) def test_pickle(self): samples = [typing.Any, typing.Union[int, str], typing.Optional[str], Tuple[int, ...], typing.Callable[[str], bytes]] for t in samples: x = Annotated[t, "a"] for prot in range(pickle.HIGHEST_PROTOCOL + 1): with self.subTest(protocol=prot, type=t): pickled = pickle.dumps(x, prot) restored = pickle.loads(pickled) self.assertEqual(x, restored) global _Annotated_test_G class _Annotated_test_G(Generic[T]): x = 1 G = Annotated[_Annotated_test_G[int], "A decoration"] G.foo = 42 G.bar = 'abc' for proto in range(pickle.HIGHEST_PROTOCOL + 1): z = pickle.dumps(G, proto) x = pickle.loads(z) self.assertEqual(x.foo, 42) self.assertEqual(x.bar, 'abc') self.assertEqual(x.x, 1) def test_subst(self): dec = "a decoration" dec2 = "another decoration" S = Annotated[T, dec2] self.assertEqual(S[int], Annotated[int, dec2]) self.assertEqual(S[Annotated[int, dec]], Annotated[int, dec, dec2]) L = Annotated[List[T], dec] self.assertEqual(L[int], Annotated[List[int], dec]) with self.assertRaises(TypeError): L[int, int] self.assertEqual(S[L[int]], Annotated[List[int], dec, dec2]) D = Annotated[typing.Dict[KT, VT], dec] self.assertEqual(D[str, int], Annotated[typing.Dict[str, int], dec]) with self.assertRaises(TypeError): D[int] It = Annotated[int, dec] with self.assertRaises(TypeError): It[None] LI = L[int] with self.assertRaises(TypeError): LI[None] def test_annotated_in_other_types(self): X = List[Annotated[T, 5]] self.assertEqual(X[int], List[Annotated[int, 5]]) def test_annotated_mro(self): class X(Annotated[int, (1, 10)]): ... self.assertEqual(X.__mro__, (X, int, object), "Annotated should be transparent.") class TypeAliasTests(BaseTestCase): def test_canonical_usage_with_variable_annotation(self): Alias: TypeAlias = Employee def test_canonical_usage_with_type_comment(self): Alias = Employee # type: TypeAlias def test_cannot_instantiate(self): with self.assertRaises(TypeError): TypeAlias() def test_no_isinstance(self): with self.assertRaises(TypeError): isinstance(42, TypeAlias) def test_no_issubclass(self): with self.assertRaises(TypeError): issubclass(Employee, TypeAlias) with self.assertRaises(TypeError): issubclass(TypeAlias, Employee) def test_cannot_subclass(self): with self.assertRaises(TypeError): class C(TypeAlias): pass with self.assertRaises(TypeError): class C(type(TypeAlias)): pass def test_repr(self): self.assertEqual(repr(TypeAlias), 'typing.TypeAlias') def test_cannot_subscript(self): with self.assertRaises(TypeError): TypeAlias[int] class ParamSpecTests(BaseTestCase): def test_basic_plain(self): P = ParamSpec('P') self.assertEqual(P, P) self.assertIsInstance(P, ParamSpec) def test_valid_uses(self): P = ParamSpec('P') T = TypeVar('T') C1 = Callable[P, int] self.assertEqual(C1.__args__, (P, int)) self.assertEqual(C1.__parameters__, (P,)) C2 = Callable[P, T] self.assertEqual(C2.__args__, (P, T)) self.assertEqual(C2.__parameters__, (P, T)) # Test collections.abc.Callable too. C3 = collections.abc.Callable[P, int] self.assertEqual(C3.__args__, (P, int)) self.assertEqual(C3.__parameters__, (P,)) C4 = collections.abc.Callable[P, T] self.assertEqual(C4.__args__, (P, T)) self.assertEqual(C4.__parameters__, (P, T)) def test_args_kwargs(self): P = ParamSpec('P') self.assertIn('args', dir(P)) self.assertIn('kwargs', dir(P)) self.assertIsInstance(P.args, ParamSpecArgs) self.assertIsInstance(P.kwargs, ParamSpecKwargs) self.assertIs(P.args.__origin__, P) self.assertIs(P.kwargs.__origin__, P) self.assertEqual(repr(P.args), "P.args") self.assertEqual(repr(P.kwargs), "P.kwargs") def test_user_generics(self): T = TypeVar("T") P = ParamSpec("P") P_2 = ParamSpec("P_2") class X(Generic[T, P]): f: Callable[P, int] x: T G1 = X[int, P_2] self.assertEqual(G1.__args__, (int, P_2)) self.assertEqual(G1.__parameters__, (P_2,)) with self.assertRaisesRegex(TypeError, "few arguments for"): X[int] with self.assertRaisesRegex(TypeError, "many arguments for"): X[int, P_2, str] G2 = X[int, Concatenate[int, P_2]] self.assertEqual(G2.__args__, (int, Concatenate[int, P_2])) self.assertEqual(G2.__parameters__, (P_2,)) G3 = X[int, [int, bool]] self.assertEqual(G3.__args__, (int, (int, bool))) self.assertEqual(G3.__parameters__, ()) G4 = X[int, ...] self.assertEqual(G4.__args__, (int, Ellipsis)) self.assertEqual(G4.__parameters__, ()) class Z(Generic[P]): f: Callable[P, int] G5 = Z[[int, str, bool]] self.assertEqual(G5.__args__, ((int, str, bool),)) self.assertEqual(G5.__parameters__, ()) G6 = Z[int, str, bool] self.assertEqual(G6.__args__, ((int, str, bool),)) self.assertEqual(G6.__parameters__, ()) # G5 and G6 should be equivalent according to the PEP self.assertEqual(G5.__args__, G6.__args__) self.assertEqual(G5.__origin__, G6.__origin__) self.assertEqual(G5.__parameters__, G6.__parameters__) self.assertEqual(G5, G6) G7 = Z[int] self.assertEqual(G7.__args__, ((int,),)) self.assertEqual(G7.__parameters__, ()) with self.assertRaisesRegex(TypeError, "many arguments for"): Z[[int, str], bool] with self.assertRaisesRegex(TypeError, "many arguments for"): Z[P_2, bool] def test_multiple_paramspecs_in_user_generics(self): P = ParamSpec("P") P2 = ParamSpec("P2") class X(Generic[P, P2]): f: Callable[P, int] g: Callable[P2, str] G1 = X[[int, str], [bytes]] G2 = X[[int], [str, bytes]] self.assertNotEqual(G1, G2) self.assertEqual(G1.__args__, ((int, str), (bytes,))) self.assertEqual(G2.__args__, ((int,), (str, bytes))) def test_no_paramspec_in__parameters__(self): # ParamSpec should not be found in __parameters__ # of generics. Usages outside Callable, Concatenate # and Generic are invalid. T = TypeVar("T") P = ParamSpec("P") self.assertNotIn(P, List[P].__parameters__) self.assertIn(T, Tuple[T, P].__parameters__) # Test for consistency with builtin generics. self.assertNotIn(P, list[P].__parameters__) self.assertIn(T, tuple[T, P].__parameters__) self.assertNotIn(P, (list[P] | int).__parameters__) self.assertIn(T, (tuple[T, P] | int).__parameters__) def test_paramspec_in_nested_generics(self): # Although ParamSpec should not be found in __parameters__ of most # generics, they probably should be found when nested in # a valid location. T = TypeVar("T") P = ParamSpec("P") C1 = Callable[P, T] G1 = List[C1] G2 = list[C1] G3 = list[C1] | int self.assertEqual(G1.__parameters__, (P, T)) self.assertEqual(G2.__parameters__, (P, T)) self.assertEqual(G3.__parameters__, (P, T)) class ConcatenateTests(BaseTestCase): def test_basics(self): P = ParamSpec('P') class MyClass: ... c = Concatenate[MyClass, P] self.assertNotEqual(c, Concatenate) def test_valid_uses(self): P = ParamSpec('P') T = TypeVar('T') C1 = Callable[Concatenate[int, P], int] self.assertEqual(C1.__args__, (Concatenate[int, P], int)) self.assertEqual(C1.__parameters__, (P,)) C2 = Callable[Concatenate[int, T, P], T] self.assertEqual(C2.__args__, (Concatenate[int, T, P], T)) self.assertEqual(C2.__parameters__, (T, P)) # Test collections.abc.Callable too. C3 = collections.abc.Callable[Concatenate[int, P], int] self.assertEqual(C3.__args__, (Concatenate[int, P], int)) self.assertEqual(C3.__parameters__, (P,)) C4 = collections.abc.Callable[Concatenate[int, T, P], T] self.assertEqual(C4.__args__, (Concatenate[int, T, P], T)) self.assertEqual(C4.__parameters__, (T, P)) class TypeGuardTests(BaseTestCase): def test_basics(self): TypeGuard[int] # OK def foo(arg) -> TypeGuard[int]: ... self.assertEqual(gth(foo), {'return': TypeGuard[int]}) def test_repr(self): self.assertEqual(repr(TypeGuard), 'typing.TypeGuard') cv = TypeGuard[int] self.assertEqual(repr(cv), 'typing.TypeGuard[int]') cv = TypeGuard[Employee] self.assertEqual(repr(cv), 'typing.TypeGuard[%s.Employee]' % __name__) cv = TypeGuard[tuple[int]] self.assertEqual(repr(cv), 'typing.TypeGuard[tuple[int]]') def test_cannot_subclass(self): with self.assertRaises(TypeError): class C(type(TypeGuard)): pass with self.assertRaises(TypeError): class C(type(TypeGuard[int])): pass def test_cannot_init(self): with self.assertRaises(TypeError): TypeGuard() with self.assertRaises(TypeError): type(TypeGuard)() with self.assertRaises(TypeError): type(TypeGuard[Optional[int]])() def test_no_isinstance(self): with self.assertRaises(TypeError): isinstance(1, TypeGuard[int]) with self.assertRaises(TypeError): issubclass(int, TypeGuard) SpecialAttrsP = typing.ParamSpec('SpecialAttrsP') SpecialAttrsT = typing.TypeVar('SpecialAttrsT', int, float, complex) class SpecialAttrsTests(BaseTestCase): def test_special_attrs(self): cls_to_check = { # ABC classes typing.AbstractSet: 'AbstractSet', typing.AsyncContextManager: 'AsyncContextManager', typing.AsyncGenerator: 'AsyncGenerator', typing.AsyncIterable: 'AsyncIterable', typing.AsyncIterator: 'AsyncIterator', typing.Awaitable: 'Awaitable', typing.ByteString: 'ByteString', typing.Callable: 'Callable', typing.ChainMap: 'ChainMap', typing.Collection: 'Collection', typing.Container: 'Container', typing.ContextManager: 'ContextManager', typing.Coroutine: 'Coroutine', typing.Counter: 'Counter', typing.DefaultDict: 'DefaultDict', typing.Deque: 'Deque', typing.Dict: 'Dict', typing.FrozenSet: 'FrozenSet', typing.Generator: 'Generator', typing.Hashable: 'Hashable', typing.ItemsView: 'ItemsView', typing.Iterable: 'Iterable', typing.Iterator: 'Iterator', typing.KeysView: 'KeysView', typing.List: 'List', typing.Mapping: 'Mapping', typing.MappingView: 'MappingView', typing.MutableMapping: 'MutableMapping', typing.MutableSequence: 'MutableSequence', typing.MutableSet: 'MutableSet', typing.OrderedDict: 'OrderedDict', typing.Reversible: 'Reversible', typing.Sequence: 'Sequence', typing.Set: 'Set', typing.Sized: 'Sized', typing.Tuple: 'Tuple', typing.Type: 'Type', typing.ValuesView: 'ValuesView', # Subscribed ABC classes typing.AbstractSet[Any]: 'AbstractSet', typing.AsyncContextManager[Any]: 'AsyncContextManager', typing.AsyncGenerator[Any, Any]: 'AsyncGenerator', typing.AsyncIterable[Any]: 'AsyncIterable', typing.AsyncIterator[Any]: 'AsyncIterator', typing.Awaitable[Any]: 'Awaitable', typing.Callable[[], Any]: 'Callable', typing.Callable[..., Any]: 'Callable', typing.ChainMap[Any, Any]: 'ChainMap', typing.Collection[Any]: 'Collection', typing.Container[Any]: 'Container', typing.ContextManager[Any]: 'ContextManager', typing.Coroutine[Any, Any, Any]: 'Coroutine', typing.Counter[Any]: 'Counter', typing.DefaultDict[Any, Any]: 'DefaultDict', typing.Deque[Any]: 'Deque', typing.Dict[Any, Any]: 'Dict', typing.FrozenSet[Any]: 'FrozenSet', typing.Generator[Any, Any, Any]: 'Generator', typing.ItemsView[Any, Any]: 'ItemsView', typing.Iterable[Any]: 'Iterable', typing.Iterator[Any]: 'Iterator', typing.KeysView[Any]: 'KeysView', typing.List[Any]: 'List', typing.Mapping[Any, Any]: 'Mapping', typing.MappingView[Any]: 'MappingView', typing.MutableMapping[Any, Any]: 'MutableMapping', typing.MutableSequence[Any]: 'MutableSequence', typing.MutableSet[Any]: 'MutableSet', typing.OrderedDict[Any, Any]: 'OrderedDict', typing.Reversible[Any]: 'Reversible', typing.Sequence[Any]: 'Sequence', typing.Set[Any]: 'Set', typing.Tuple[Any]: 'Tuple', typing.Tuple[Any, ...]: 'Tuple', typing.Type[Any]: 'Type', typing.ValuesView[Any]: 'ValuesView', # Special Forms typing.Annotated: 'Annotated', typing.Any: 'Any', typing.ClassVar: 'ClassVar', typing.Concatenate: 'Concatenate', typing.Final: 'Final', typing.ForwardRef: 'ForwardRef', typing.Literal: 'Literal', typing.NewType: 'NewType', typing.NoReturn: 'NoReturn', typing.Optional: 'Optional', typing.TypeAlias: 'TypeAlias', typing.TypeGuard: 'TypeGuard', typing.TypeVar: 'TypeVar', typing.Union: 'Union', # Subscribed special forms typing.Annotated[Any, "Annotation"]: 'Annotated', typing.ClassVar[Any]: 'ClassVar', typing.Concatenate[Any, SpecialAttrsP]: 'Concatenate', typing.Final[Any]: 'Final', typing.Literal[Any]: 'Literal', typing.Optional[Any]: 'Optional', typing.TypeGuard[Any]: 'TypeGuard', typing.Union[Any]: 'Any', typing.Union[int, float]: 'Union', # Incompatible special forms (tested in test_special_attrs2) # - typing.ForwardRef('set[Any]') # - typing.NewType('TypeName', Any) # - typing.ParamSpec('SpecialAttrsP') # - typing.TypeVar('T') } for cls, name in cls_to_check.items(): with self.subTest(cls=cls): self.assertEqual(cls.__name__, name, str(cls)) self.assertEqual(cls.__qualname__, name, str(cls)) self.assertEqual(cls.__module__, 'typing', str(cls)) for proto in range(pickle.HIGHEST_PROTOCOL + 1): s = pickle.dumps(cls, proto) loaded = pickle.loads(s) self.assertIs(cls, loaded) TypeName = typing.NewType('SpecialAttrsTests.TypeName', Any) def test_special_attrs2(self): # Forward refs provide a different introspection API. __name__ and # __qualname__ make little sense for forward refs as they can store # complex typing expressions. fr = typing.ForwardRef('set[Any]') self.assertFalse(hasattr(fr, '__name__')) self.assertFalse(hasattr(fr, '__qualname__')) self.assertEqual(fr.__module__, 'typing') # Forward refs are currently unpicklable. for proto in range(pickle.HIGHEST_PROTOCOL + 1): with self.assertRaises(TypeError) as exc: pickle.dumps(fr, proto) self.assertEqual(SpecialAttrsTests.TypeName.__name__, 'TypeName') self.assertEqual( SpecialAttrsTests.TypeName.__qualname__, 'SpecialAttrsTests.TypeName', ) self.assertEqual( SpecialAttrsTests.TypeName.__module__, 'test.test_typing', ) # NewTypes are picklable assuming correct qualname information. for proto in range(pickle.HIGHEST_PROTOCOL + 1): s = pickle.dumps(SpecialAttrsTests.TypeName, proto) loaded = pickle.loads(s) self.assertIs(SpecialAttrsTests.TypeName, loaded) # Type variables don't support non-global instantiation per PEP 484 # restriction that "The argument to TypeVar() must be a string equal # to the variable name to which it is assigned". Thus, providing # __qualname__ is unnecessary. self.assertEqual(SpecialAttrsT.__name__, 'SpecialAttrsT') self.assertFalse(hasattr(SpecialAttrsT, '__qualname__')) self.assertEqual(SpecialAttrsT.__module__, 'test.test_typing') # Module-level type variables are picklable. for proto in range(pickle.HIGHEST_PROTOCOL + 1): s = pickle.dumps(SpecialAttrsT, proto) loaded = pickle.loads(s) self.assertIs(SpecialAttrsT, loaded) self.assertEqual(SpecialAttrsP.__name__, 'SpecialAttrsP') self.assertFalse(hasattr(SpecialAttrsP, '__qualname__')) self.assertEqual(SpecialAttrsP.__module__, 'test.test_typing') # Module-level ParamSpecs are picklable. for proto in range(pickle.HIGHEST_PROTOCOL + 1): s = pickle.dumps(SpecialAttrsP, proto) loaded = pickle.loads(s) self.assertIs(SpecialAttrsP, loaded) class AllTests(BaseTestCase): """Tests for __all__.""" def test_all(self): from typing import __all__ as a # Just spot-check the first and last of every category. self.assertIn('AbstractSet', a) self.assertIn('ValuesView', a) self.assertIn('cast', a) self.assertIn('overload', a) if hasattr(contextlib, 'AbstractContextManager'): self.assertIn('ContextManager', a) # Check that io and re are not exported. self.assertNotIn('io', a) self.assertNotIn('re', a) # Spot-check that stdlib modules aren't exported. self.assertNotIn('os', a) self.assertNotIn('sys', a) # Check that Text is defined. self.assertIn('Text', a) # Check previously missing classes. self.assertIn('SupportsBytes', a) self.assertIn('SupportsComplex', a) def test_all_exported_names(self): import typing actual_all = set(typing.__all__) computed_all = { k for k, v in vars(typing).items() # explicitly exported, not a thing with __module__ if k in actual_all or ( # avoid private names not k.startswith('_') and k not in {'io', 're'} and # there's a few types and metaclasses that aren't exported not k.endswith(('Meta', '_contra', '_co')) and not k.upper() == k and # but export all things that have __module__ == 'typing' getattr(v, '__module__', None) == typing.__name__ ) } self.assertSetEqual(computed_all, actual_all) if __name__ == '__main__': main()
""" python main.py --learning_rate 0.001 --model ResNetAE --loss l2 --optimizer adam --msg demo1 python main.py --learning_rate 0.001 --model ViTAE --loss l2 --optimizer adam --msg demo1 --paths 197 --zdim 384 """ import argparse import os import logging import datetime import torch import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.optim import torch.utils.data import torch.utils.data.distributed from torch.utils.data import DataLoader from torch.optim.lr_scheduler import CosineAnnealingLR import numpy as np from torchvision.datasets.mnist import FashionMNIST, MNIST from torchvision import transforms from torchvision.datasets import ImageFolder import torchvision.utils as vutils from tqdm import tqdm import models as models import matplotlib.pyplot as plt from helper import mkdir_p, save_model, save_args, set_seed, Logger def parse_args(): """Parameters""" parser = argparse.ArgumentParser('training') parser.add_argument('-c', '--checkpoint', type=str, metavar='PATH', help='path to save checkpoint (default: checkpoint)') parser.add_argument('--msg', type=str, help='message after checkpoint') parser.add_argument('--model', default='RealAE', help='model name [default: pointnet_cls]') # training parser.add_argument('--batch_size', type=int, default=32, help='batch size in training') parser.add_argument('--epoch', default=80, type=int, help='number of epoch in training') parser.add_argument('--learning_rate', default=0.1, type=float, help='learning rate in training') parser.add_argument('--weight_decay', type=float, default=1e-4, help='decay rate') parser.add_argument('--seed', type=int, help='random seed') parser.add_argument('--workers', default=4, type=int, help='workers') parser.add_argument('--frequency', default=5, type=int, help='workers') parser.add_argument('--loss', default='l2') parser.add_argument('--optimizer', default='sgd') # models # imsize = 28, paths = 4, segments = 5, samples = 2, zdim = 1024, stroke_width = None parser.add_argument('--imsize', default=224, type=int) parser.add_argument('--paths', default=128, type=int) parser.add_argument('--segments', default=3, type=int) parser.add_argument('--samples', default=2, type=int) parser.add_argument('--zdim', default=2048, type=int) parser.add_argument('--max_width', default=2, type=int) parser.add_argument('--pretained_encoder', dest='pretained_encoder', action='store_true') return parser.parse_args() args = parse_args() os.environ["HDF5_USE_FILE_LOCKING"] = "FALSE" # Verbose operations: make folder, init logger, fix seed, set device time_str = str(datetime.datetime.now().strftime('-%Y%m%d%H%M%S')) message = time_str if args.msg is None else "-" + args.msg args.checkpoint = 'checkpoints/' + args.model + message args.visualize = 'checkpoints/' + args.model + message +'/visualize' if not os.path.isdir(args.checkpoint): mkdir_p(args.checkpoint) if not os.path.isdir(args.visualize): mkdir_p(args.visualize) screen_logger = logging.getLogger("Model") screen_logger.setLevel(logging.INFO) formatter = logging.Formatter('%(message)s') file_handler = logging.FileHandler(os.path.join(args.checkpoint, "screen_out.txt")) file_handler.setLevel(logging.INFO) file_handler.setFormatter(formatter) screen_logger.addHandler(file_handler) def printf(str): screen_logger.info(str) print(str) def main(): if args.seed is not None: set_seed(args.seed) printf(f'==> fixing the random seed to: {args.seed}') device = 'cuda' if torch.cuda.is_available() else 'cpu' printf(f'==> using device: {device}') printf(f"==> args: {args}") # building models printf(f'==> Building model: {args.model}') net = models.__dict__[args.model]( imsize=args.imsize, paths=args.paths, segments=args.segments, samples=args.samples, zdim=args.zdim, max_width=2, pretained_encoder=args.pretained_encoder) if args.loss == 'l1': criterion = nn.L1Loss().to(device) printf(f"==> Using criterion L1 loss.") else: criterion = nn.MSELoss().to(device) printf(f"==> Using criterion MSE loss.") net = net.to(device) if device == 'cuda': net = torch.nn.DataParallel(net) cudnn.benchmark = True best_test_loss = float("inf") start_epoch = 0 # start from epoch 0 or last checkpoint epoch optimizer_dict = None if not os.path.isfile(os.path.join(args.checkpoint, "last_checkpoint.pth")): save_args(args) logger = Logger(os.path.join(args.checkpoint, 'log.txt'), title="main") logger.set_names(["Epoch-Num", 'Learning-Rate', 'Train-Loss', 'Test-Loss']) else: printf(f"Resuming last checkpoint from {args.checkpoint}") checkpoint_path = os.path.join(args.checkpoint, "last_checkpoint.pth") checkpoint = torch.load(checkpoint_path) net.load_state_dict(checkpoint['net']) start_epoch = checkpoint['epoch'] best_test_loss = checkpoint['best_test_loss'] logger = Logger(os.path.join(args.checkpoint, 'log.txt'), title="main", resume=True) optimizer_dict = checkpoint['optimizer'] printf('==> Preparing data..') transform = transforms.Compose([ transforms.Resize((args.imsize,args.imsize)), transforms.RandomHorizontalFlip(), transforms.ToTensor() ]) dataset = ImageFolder(root="./data/full_emoji/", transform=transform) train_loader = DataLoader(dataset, num_workers=args.workers, batch_size=args.batch_size, shuffle=True, pin_memory=False) test_loader = DataLoader(dataset, num_workers=args.workers, batch_size=args.batch_size, shuffle=False, pin_memory=False) if args.optimizer =="sgd": printf("==> Using SGD optimizer") optimizer = torch.optim.SGD(net.parameters(), lr=args.learning_rate, momentum=0.9, weight_decay=args.weight_decay) else: printf("==> Using Adam optimizer") optimizer = torch.optim.Adam(net.parameters(), lr=args.learning_rate) if optimizer_dict is not None: optimizer.load_state_dict(optimizer_dict) scheduler = CosineAnnealingLR(optimizer, args.epoch, eta_min=args.learning_rate / 100, last_epoch=start_epoch - 1) # init save images # visualize(net, train_loader, device, args.checkpoint +'/epoch-0', nrow=8) visualize(net, test_loader, device, "init") for epoch in range(start_epoch, args.epoch): printf('Epoch(%d/%s) Learning Rate %s:' % (epoch + 1, args.epoch, optimizer.param_groups[0]['lr'])) train_out = train(net, train_loader, optimizer, criterion, device) # {"loss"} test_out = validate(net, test_loader, criterion, device) # {"loss"} visualize(net, test_loader, device, epoch) scheduler.step() if test_out["loss"] < best_test_loss: best_test_loss = test_out["loss"] is_best = True else: is_best = False save_model(net, epoch, path=args.checkpoint, is_best=is_best, best_test_loss = best_test_loss, test_loss=test_out["loss"], optimizer=optimizer.state_dict()) logger.append([epoch, optimizer.param_groups[0]['lr'], train_out["loss"], test_out["loss"]]) printf(f"Train loss:{train_out["loss"]} Test loss:{test_out["loss"]} [best test loss:{best_test_loss}]") # printf(f"==> saving visualized images ... \n\n") # img_save_path = args.checkpoint +'/epoch'+str(epoch+1) # visualize(net, train_loader, device, img_save_path, nrow=8) logger.close() def train(net, trainloader, optimizer, criterion, device): net.train() train_loss = 0 time_cost = datetime.datetime.now() for batch_idx, (data, label) in enumerate(trainloader): data, label = data.to(device), label.to(device) optimizer.zero_grad() out = net(data) loss = criterion(data, out) loss.backward() optimizer.step() train_loss += loss.item() if batch_idx > 1 and batch_idx % args.frequency == 0: time_cost = int((datetime.datetime.now() - time_cost).total_seconds()) printf( f"[{batch_idx}/{len(trainloader)}]\t Train time {time_cost}s Train loss {train_loss / (batch_idx + 1)}") time_cost = datetime.datetime.now() return { "loss": float("%.3f" % (train_loss / (batch_idx + 1))) } def validate(net, testloader, criterion, device): net.eval() test_loss = 0 with torch.no_grad(): for batch_idx, (data, label) in enumerate(tqdm(testloader)): data, label = data.to(device), label.to(device) out = net(data) loss = criterion(out, data) test_loss += loss.item() return { "loss": float("%.3f" % (test_loss / (batch_idx + 1))) } def visualize(net, testloader, device, epoch): net.eval() inputpath = os.path.join(args.visualize, f"epoch_{epoch}_input.png") svgpath = os.path.join(args.visualize, f"epoch_{epoch}_svg.svg") renderpath = os.path.join(args.visualize, f"epoch_{epoch}_render.png") with torch.no_grad(): data, label = next(iter(testloader)) data, label = data.to(device), label.to(device) net.module.visualize(data, inputpath=inputpath, svgpath=svgpath, renderpath=renderpath) printf(f"Finish visualization of epoch {epoch}.") if __name__ == '__main__': main()
""" python main.py --learning_rate 0.001 --model ResNetAE --loss l2 --optimizer adam --msg demo1 python main.py --learning_rate 0.001 --model ViTAE --loss l2 --optimizer adam --msg demo1 --paths 197 --zdim 384 """ import argparse import os import logging import datetime import torch import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.optim import torch.utils.data import torch.utils.data.distributed from torch.utils.data import DataLoader from torch.optim.lr_scheduler import CosineAnnealingLR import numpy as np from torchvision.datasets.mnist import FashionMNIST, MNIST from torchvision import transforms from torchvision.datasets import ImageFolder import torchvision.utils as vutils from tqdm import tqdm import models as models import matplotlib.pyplot as plt from helper import mkdir_p, save_model, save_args, set_seed, Logger def parse_args(): """Parameters""" parser = argparse.ArgumentParser('training') parser.add_argument('-c', '--checkpoint', type=str, metavar='PATH', help='path to save checkpoint (default: checkpoint)') parser.add_argument('--msg', type=str, help='message after checkpoint') parser.add_argument('--model', default='RealAE', help='model name [default: pointnet_cls]') # training parser.add_argument('--batch_size', type=int, default=32, help='batch size in training') parser.add_argument('--epoch', default=80, type=int, help='number of epoch in training') parser.add_argument('--learning_rate', default=0.1, type=float, help='learning rate in training') parser.add_argument('--weight_decay', type=float, default=1e-4, help='decay rate') parser.add_argument('--seed', type=int, help='random seed') parser.add_argument('--workers', default=4, type=int, help='workers') parser.add_argument('--frequency', default=5, type=int, help='workers') parser.add_argument('--loss', default='l2') parser.add_argument('--optimizer', default='sgd') # models # imsize = 28, paths = 4, segments = 5, samples = 2, zdim = 1024, stroke_width = None parser.add_argument('--imsize', default=224, type=int) parser.add_argument('--paths', default=128, type=int) parser.add_argument('--segments', default=3, type=int) parser.add_argument('--samples', default=2, type=int) parser.add_argument('--zdim', default=2048, type=int) parser.add_argument('--max_width', default=2, type=int) parser.add_argument('--pretained_encoder', dest='pretained_encoder', action='store_true') return parser.parse_args() args = parse_args() os.environ["HDF5_USE_FILE_LOCKING"] = "FALSE" # Verbose operations: make folder, init logger, fix seed, set device time_str = str(datetime.datetime.now().strftime('-%Y%m%d%H%M%S')) message = time_str if args.msg is None else "-" + args.msg args.checkpoint = 'checkpoints/' + args.model + message args.visualize = 'checkpoints/' + args.model + message +'/visualize' if not os.path.isdir(args.checkpoint): mkdir_p(args.checkpoint) if not os.path.isdir(args.visualize): mkdir_p(args.visualize) screen_logger = logging.getLogger("Model") screen_logger.setLevel(logging.INFO) formatter = logging.Formatter('%(message)s') file_handler = logging.FileHandler(os.path.join(args.checkpoint, "screen_out.txt")) file_handler.setLevel(logging.INFO) file_handler.setFormatter(formatter) screen_logger.addHandler(file_handler) def printf(str): screen_logger.info(str) print(str) def main(): if args.seed is not None: set_seed(args.seed) printf(f'==> fixing the random seed to: {args.seed}') device = 'cuda' if torch.cuda.is_available() else 'cpu' printf(f'==> using device: {device}') printf(f"==> args: {args}") # building models printf(f'==> Building model: {args.model}') net = models.__dict__[args.model]( imsize=args.imsize, paths=args.paths, segments=args.segments, samples=args.samples, zdim=args.zdim, max_width=2, pretained_encoder=args.pretained_encoder) if args.loss == 'l1': criterion = nn.L1Loss().to(device) printf(f"==> Using criterion L1 loss.") else: criterion = nn.MSELoss().to(device) printf(f"==> Using criterion MSE loss.") net = net.to(device) if device == 'cuda': net = torch.nn.DataParallel(net) cudnn.benchmark = True best_test_loss = float("inf") start_epoch = 0 # start from epoch 0 or last checkpoint epoch optimizer_dict = None if not os.path.isfile(os.path.join(args.checkpoint, "last_checkpoint.pth")): save_args(args) logger = Logger(os.path.join(args.checkpoint, 'log.txt'), title="main") logger.set_names(["Epoch-Num", 'Learning-Rate', 'Train-Loss', 'Test-Loss']) else: printf(f"Resuming last checkpoint from {args.checkpoint}") checkpoint_path = os.path.join(args.checkpoint, "last_checkpoint.pth") checkpoint = torch.load(checkpoint_path) net.load_state_dict(checkpoint['net']) start_epoch = checkpoint['epoch'] best_test_loss = checkpoint['best_test_loss'] logger = Logger(os.path.join(args.checkpoint, 'log.txt'), title="main", resume=True) optimizer_dict = checkpoint['optimizer'] printf('==> Preparing data..') transform = transforms.Compose([ transforms.Resize((args.imsize,args.imsize)), transforms.RandomHorizontalFlip(), transforms.ToTensor() ]) dataset = ImageFolder(root="./data/full_emoji/", transform=transform) train_loader = DataLoader(dataset, num_workers=args.workers, batch_size=args.batch_size, shuffle=True, pin_memory=False) test_loader = DataLoader(dataset, num_workers=args.workers, batch_size=args.batch_size, shuffle=False, pin_memory=False) if args.optimizer =="sgd": printf("==> Using SGD optimizer") optimizer = torch.optim.SGD(net.parameters(), lr=args.learning_rate, momentum=0.9, weight_decay=args.weight_decay) else: printf("==> Using Adam optimizer") optimizer = torch.optim.Adam(net.parameters(), lr=args.learning_rate) if optimizer_dict is not None: optimizer.load_state_dict(optimizer_dict) scheduler = CosineAnnealingLR(optimizer, args.epoch, eta_min=args.learning_rate / 100, last_epoch=start_epoch - 1) # init save images # visualize(net, train_loader, device, args.checkpoint +'/epoch-0', nrow=8) visualize(net, test_loader, device, "init") for epoch in range(start_epoch, args.epoch): printf('Epoch(%d/%s) Learning Rate %s:' % (epoch + 1, args.epoch, optimizer.param_groups[0]['lr'])) train_out = train(net, train_loader, optimizer, criterion, device) # {"loss"} test_out = validate(net, test_loader, criterion, device) # {"loss"} visualize(net, test_loader, device, epoch) scheduler.step() if test_out["loss"] < best_test_loss: best_test_loss = test_out["loss"] is_best = True else: is_best = False save_model(net, epoch, path=args.checkpoint, is_best=is_best, best_test_loss = best_test_loss, test_loss=test_out["loss"], optimizer=optimizer.state_dict()) logger.append([epoch, optimizer.param_groups[0]['lr'], train_out["loss"], test_out["loss"]]) printf(f"Train loss:{train_out['loss']} Test loss:{test_out['loss']} [best test loss:{best_test_loss}]") # printf(f"==> saving visualized images ... \n\n") # img_save_path = args.checkpoint +'/epoch'+str(epoch+1) # visualize(net, train_loader, device, img_save_path, nrow=8) logger.close() def train(net, trainloader, optimizer, criterion, device): net.train() train_loss = 0 time_cost = datetime.datetime.now() for batch_idx, (data, label) in enumerate(trainloader): data, label = data.to(device), label.to(device) optimizer.zero_grad() out = net(data) loss = criterion(data, out) loss.backward() optimizer.step() train_loss += loss.item() if batch_idx > 1 and batch_idx % args.frequency == 0: time_cost = int((datetime.datetime.now() - time_cost).total_seconds()) printf( f"[{batch_idx}/{len(trainloader)}]\t Train time {time_cost}s Train loss {train_loss / (batch_idx + 1)}") time_cost = datetime.datetime.now() return { "loss": float("%.3f" % (train_loss / (batch_idx + 1))) } def validate(net, testloader, criterion, device): net.eval() test_loss = 0 with torch.no_grad(): for batch_idx, (data, label) in enumerate(tqdm(testloader)): data, label = data.to(device), label.to(device) out = net(data) loss = criterion(out, data) test_loss += loss.item() return { "loss": float("%.3f" % (test_loss / (batch_idx + 1))) } def visualize(net, testloader, device, epoch): net.eval() inputpath = os.path.join(args.visualize, f"epoch_{epoch}_input.png") svgpath = os.path.join(args.visualize, f"epoch_{epoch}_svg.svg") renderpath = os.path.join(args.visualize, f"epoch_{epoch}_render.png") with torch.no_grad(): data, label = next(iter(testloader)) data, label = data.to(device), label.to(device) net.module.visualize(data, inputpath=inputpath, svgpath=svgpath, renderpath=renderpath) printf(f"Finish visualization of epoch {epoch}.") if __name__ == '__main__': main()
# -*- coding: utf-8 -*- """ The features module. Extract useful features for training the model. Created by Romain Mondon-Cancel on 2020-09-25 22:26:54 """ import bisect import functools as ft import logging import random import typing as t import pandas as pd import sklearn.model_selection from . import perf logger = logging.getLogger(__name__) def add_trip_id(df: pd.DataFrame) -> pd.DataFrame: """ Add a trip id to ``df``, identifying a unique trip booking. Args: df: The dataframe to update. Returns: A dataframe containing a string column identifying a unique trip booking, represented by the time of departure to the minute and the origin and destination stations. """ return df.assign( trip_id=lambda df: [ f"{datetime.strftime("%Y%m%d%H%M")}{start}{end}" for datetime, start, end in zip( df.departure_datetime, df.station_origin, df.station_destination ) ] ) def add_trip_path(df: pd.DataFrame) -> pd.DataFrame: """ Add a trip path to ``df``, identifying the path of a trip. Args: df: The dataframe to update. Returns: A dataframe containing a string column representing the path of each trip, represented by the name of the origin and the destination stations. """ return df.assign( trip_path=lambda df: [ f"{start}{end}" for start, end in zip(df.station_origin, df.station_destination) ] ) def add_sale_delta(df: pd.DataFrame) -> pd.DataFrame: """ Add sale time delta data to ``df``. Args: df: The dataframe to update. Returns: A dataframe containing two additional columns, ``sale_timedelta`` containing the time difference between the departure and the sale time, and ``sale_day`` containing the number of days between the sale and the departure. ``sale_day=0`` means the sale happened after the departure. """ # fmt: off return ( df .assign(sale_timedelta=lambda df: df.sale_datetime - df.departure_datetime) .assign(sale_day=lambda df: df.sale_timedelta.dt.days) ) # fmt: on def add_cancel_delta(df: pd.DataFrame) -> pd.DataFrame: """ Add cancellation time delta data to ``df``. Args: df: The dataframe to update. Returns: A dataframe containing two additional columns, ``cancel_timedelta`` containing the time difference between the departure and the cancellation time if it exists, and ``cancel_day`` containing the number of days between the cancellation and the departure. ``cancel_day=0`` means the cancellation happened after the departure. """ # fmt: off return ( df .assign(cancel_timedelta=lambda df: df.cancel_datetime - df.departure_datetime) .assign(cancel_day=lambda df: df.cancel_timedelta.dt.days) ) # fmt: on @perf.timer def one_hot_encode( df: pd.DataFrame, values: t.List, columns: t.List[str], function: t.Callable[[pd.DataFrame], pd.Series], ) -> pd.DataFrame: """ One-hot encode some values. Args: df: The dataframe to update values: The expected different values to one-hot encode. columns: The names of the columns corresponding to each one-hot encoded value. function: The function applied to ``df``, returning a series containing the values to one-hot encode. Returns: A dataframe containing additional columns, one for each one-hot encoded value, containing ``1`` if ``function(df)`` is equal to the corresponding value and ``0`` otherwise. """ series = function(df) return df.assign( **{ columns[idx]: (series == value).astype(int) for idx, value in enumerate(values) } ) HOURS = list(range(24)) HOUR_COLUMNS = [f"hour_{h}" for h in HOURS] add_hour = ft.partial( one_hot_encode, values=HOURS, columns=HOUR_COLUMNS, function=lambda df: df.departure_datetime.dt.hour, ) """ Add information about the hour of the departure time of the train. Args: df: The dataframe to update. Returns: A dataframe containing additional, one-hot encoded columns for each hour of the day, with 1 if the train departs on that hour. """ DAYS_OF_WEEK = list(range(7)) DAY_OF_WEEK_COLUMNS = [f"day_of_week_{d}" for d in DAYS_OF_WEEK] add_day_of_week = ft.partial( one_hot_encode, values=DAYS_OF_WEEK, columns=DAY_OF_WEEK_COLUMNS, function=lambda df: df.departure_datetime.dt.weekday, ) """ Add information about the day of week of the departure date of the train. Args: df: The dataframe to update. Returns: A dataframe containing additional, one-hot encoded columns for each day of the week, with 1 if the train departs on that day. """ PERIODS = list(range(24)) PERIOD_COLUMNS = [f"period_{p}" for p in PERIODS] add_period = ft.partial( one_hot_encode, values=PERIODS, columns=PERIOD_COLUMNS, function=lambda df: ( (df.departure_datetime.dt.month - 1) * 2 + (df.departure_datetime.dt.day > 15) ), ) """ Add information about the period in the year of the departure date of the train. Args: df: The dataframe to update. Returns: A dataframe containing additional, one-hot encoded columns for each period of the year, with 1 if the train departs on that period. A period is roughly defined as a half-month. The first period of each month ends on the 15th day of that month, and the second period starts on the 16th day. """ PATHS = ["AB", "BA"] PATH_COLUMNS = [f"path_{p}" for p in PATHS] add_path = ft.partial( one_hot_encode, values=PATHS, columns=PATH_COLUMNS, function=lambda df: df.trip_path, ) """ Add information about the path of the trip. Args: df: The dataframe to update. Returns: A dataframe containing additional, one-hot encoded columns for each unique path the train can take; in that case, the trip can only travel between two stations A and B, which means the two unique paths are AB and BA. """ def add_features(df: pd.DataFrame) -> pd.DataFrame: """ Add all the useful features to enrich a dataframe. Args: df: The dataframe to update. Returns: A dataframe containing additional, useful columns. """ return ( df.pipe(add_trip_id) .pipe(add_trip_path) .pipe(add_sale_delta) .pipe(add_cancel_delta) .pipe(add_hour) .pipe(add_day_of_week) .pipe(add_period) .pipe(add_path) ) INFO_COLUMNS = HOUR_COLUMNS + DAY_OF_WEEK_COLUMNS + PERIOD_COLUMNS + PATH_COLUMNS DEFAULT_TEST_SIZE = 0.1 def train_test_split( df: pd.DataFrame, train_size: t.Optional[float] = None, test_size: t.Optional[float] = None, ) -> t.Tuple[pd.DataFrame, pd.DataFrame]: """ Split a dataframe in random groups along the ``trip_id`` column. Args: df: The dataframe to split. The dataframe must contain the column ``trip_id``. train_size: Defaults to ``None``. The size of the training set, as a ratio. Must be between 0 and 1. If ``None``, set such that ``train_size + test_size = 1``. test_size: Defaults to ``None``. The size of the test set, as a ratio. If both ``train_size`` and ``test_size`` are ``None``, defaults to 0.1. Must be between 0 and 1. If ``None``, set such that ``train_size + test_size = 1``. Returns: Two datasets extracted from ``df``. The first one contains ``train_size`` of the unique trip ids of ``df``, while the second one contains ``test_size`` of them. """ if train_size is None and test_size is None: test_size = DEFAULT_TEST_SIZE train_ids, test_ids = sklearn.model_selection.train_test_split( df.trip_id.unique(), train_size=train_size, test_size=test_size ) return ( df.loc[lambda df: df.trip_id.isin(train_ids)], df.loc[lambda df: df.trip_id.isin(test_ids)], ) def split_X_y(df: pd.DataFrame) -> t.Tuple[pd.DataFrame, pd.Series]: """ Split the dataframe ``df`` into ``X`` and ``y`` parts. Args: df: The dataframe to split. Must contain the column ``demand``, the target. Returns: A dataframe containing the input ``X`` for the model, consisting of all the columns except for ``demand``, and the target ``y`` for the model, the column ``demand``. """ X_cols = [c for c in df.columns if c != "demand"] return df[X_cols], df.demand PriceGenerator = t.Callable[[float, float, int], t.List[float]] def generate_prices(min_price: float, max_price: float, n_prices: int) -> t.List[float]: """ Generate a sorted list of prices in a given range. Args: min_price: The minimum price of tickets. max_price: The maximum price of tickets. n_prices: The number of prices to generate. Returns: A list of prices uniformly picked over a range [m, M] such that 5% of values are picked between m and min_price, 90% of values between min_price and max_price, and 5% between max_price and M. """ delta = (max_price - min_price) / 0.9 adjusted_min = min_price - 0.05 * delta return sorted( round(adjusted_min + delta * random.random(), 2) for _ in range(n_prices) ) def compute_demands( sale_prices: t.List[float], target_prices: t.List[float] ) -> t.List[int]: """ Compute the demand for each of target prices, given the full list of sale prices. Using binary search, this algorithm is in O(n log m), where n is the number of target prices and m is the number of sale prices. Args: sale_prices: The sorted list of prices at which tickets were sold. target_prices: The prices to compute the demand for. Returns: The list of demands for each target price. The demand is the number of tickets sold for at least the target value. """ n = len(sale_prices) sale_idx = 0 ans = [] for price in target_prices: sale_idx = bisect.bisect_left(sale_prices, price, lo=sale_idx) ans.append(n - sale_idx) return ans def merge_sorted(arr1: t.List[float], arr2: t.List[float]) -> t.List[float]: """ Merge two sorted arrays into a third sorted array. Using two pointers, this algorithm is in O(n1 + n2), where n1 and n2 are respectively the lengths of ``arr1`` and ``arr2``. Args: arr1: The first array to merge. arr2: The second array to merge. Returns: A sorted array containing all values from ``arr1`` and ``arr2``. """ ans = [] idx1 = 0 idx2 = 0 n1 = len(arr1) n2 = len(arr2) while idx1 < n1 or idx2 < n2: if idx1 == n1: ans.extend(arr2[idx2:]) idx2 = n2 elif idx2 == n2: ans.extend(arr1[idx1:]) idx1 = n1 elif arr1[idx1] < arr2[idx2]: ans.append(arr1[idx1]) idx1 += 1 else: ans.append(arr2[idx2]) idx2 += 1 return ans def describe_previous_demand( previous_total_demand: int, previous_prices: t.List[float], day: int, prices: t.List[float], ) -> pd.DataFrame: """ Describe the demand prior to a given day for a trip given a list of prices. Args: previous_total_demand: The total number of tickets sold up to the day before. previous_prices: The list of all prices for tickets sold up to the day before. day: The day considered, relative to the departure day. prices: The list of prices to compute demand for. Returns: A dataframe containing, for each price in ``prices``, the corresponding demand on all prior days, the total demand on all prior days, the prices, and the day number itself. """ previous_price_demands = compute_demands(previous_prices, prices) return pd.DataFrame( dict( day=day, price=prices, previous_total_demand=previous_total_demand, previous_price_demand=previous_price_demands, ) ) def describe_demand( day_prices: t.List[float], previous_total_demand: int, previous_prices: t.List[float], day: int, prices: t.List[float], ) -> pd.DataFrame: """ Describe the demand on a given day for a trip given a list of prices. Args: day_prices: The prices at which the tickets were sold on a given day. previous_total_demand: The total number of tickets sold up to the day before. previous_prices: The list of all prices for tickets sold up to the day before. day: The day considered, relative to the departure day. prices: The list of prices to compute demand for. Returns: A dataframe containing, for each price in ``prices``, the corresponding demand on that day, as well as the corresponding demand on all prior days, the total demand on all prior days, the prices, and the day number itself. """ price_demands = compute_demands(day_prices, prices) return describe_previous_demand( previous_total_demand, previous_prices, day, prices ).assign(demand=price_demands) def get_trip_info(trip_df: pd.DataFrame) -> pd.Series: """ Extract the information describing a given trip. Args: trip_df: The dataframe containing the data for a given trip. Returns: A Series containing data describing that trip. """ min_price = trip_df.price.min() max_price = trip_df.price.max() return ( trip_df[INFO_COLUMNS].assign(min_price=min_price, max_price=max_price).iloc[0] ) DEFAULT_N_PRICES = 20 def process_trip_at_day( trip_df: pd.DataFrame, day: int, prices: t.List[float] ) -> pd.DataFrame: """ Process the trip data on a given day; does not include the demand on that day. Args: trip_df: The dataframe of the data for a given trip. day: The day to consider. prices: The list of prices to process the data for. Returns: A dataframe containing all the contextual information required to describe what is known of a trip prior ot ``day`` for a given list of ``prices``. This includes one-hot encoded information about the trip itself, the hour of the departure, the day of the week, and the period during the year when the trip occurred, as well as information about bookings prior to ``day``, as described by ``describe_previous_demand``. """ trip_df = trip_df.sort_values("price") trip_info = get_trip_info(trip_df) previous_df = trip_df.loc[lambda df: df.sale_day < day] previous_total_demand = previous_df.shape[0] previous_prices = previous_df.price.tolist() return describe_previous_demand( previous_total_demand, previous_prices, day, prices ).assign(**trip_info) @perf.timer def process_trip( trip_df: pd.DataFrame, n_prices: int = DEFAULT_N_PRICES, ) -> pd.DataFrame: """ Process a trip dataframe to return the data as expected by the model. Args: trip_df: The dataframe corresponding to a unique trip. n_prices: Defaults to ``DEFAULT_N_PRICES``. The number of prices to generate. Returns: A dataframe containing, for each day when sales occurred, ``n_prices`` lines, where the script generates that many random prices. The features are built by the ``describe_demand`` function. """ rows = [] previous_total_demand = 0 previous_prices: t.List[float] = [] trip_info = get_trip_info(trip_df) min_price = trip_info.min_price max_price = trip_info.max_price for day, day_trip_df in trip_df.sort_values("price").groupby("sale_day"): prices = generate_prices(min_price, max_price, n_prices) day_prices = day_trip_df.price.tolist() day_demand = describe_demand( day_prices, previous_total_demand, previous_prices, day, prices, ) rows.append(day_demand) previous_total_demand += day_trip_df.shape[0] previous_prices = merge_sorted(previous_prices, day_prices) return pd.concat(rows).assign(**trip_info) def process_df(df: pd.DataFrame, n_prices: int = DEFAULT_N_PRICES) -> pd.DataFrame: """ Process all trips in ``df`` to generate a full dataframe as expected by the model. Args: df: The dataframe to process. n_prices: Defaults to ``DEFAULT_N_PRICES``. The number of prices to generate. Returns: A full dataframe, as processed by ``process_trip`` for each unique trip in ``df``. """ groups = [] for trip_id, trip_df in df.groupby("trip_id"): groups.append(process_trip(trip_df, n_prices)) logger.info(f"Processed trip {trip_id} successfully.") return pd.concat(groups)
# -*- coding: utf-8 -*- """ The features module. Extract useful features for training the model. Created by Romain Mondon-Cancel on 2020-09-25 22:26:54 """ import bisect import functools as ft import logging import random import typing as t import pandas as pd import sklearn.model_selection from . import perf logger = logging.getLogger(__name__) def add_trip_id(df: pd.DataFrame) -> pd.DataFrame: """ Add a trip id to ``df``, identifying a unique trip booking. Args: df: The dataframe to update. Returns: A dataframe containing a string column identifying a unique trip booking, represented by the time of departure to the minute and the origin and destination stations. """ return df.assign( trip_id=lambda df: [ f"{datetime.strftime('%Y%m%d%H%M')}{start}{end}" for datetime, start, end in zip( df.departure_datetime, df.station_origin, df.station_destination ) ] ) def add_trip_path(df: pd.DataFrame) -> pd.DataFrame: """ Add a trip path to ``df``, identifying the path of a trip. Args: df: The dataframe to update. Returns: A dataframe containing a string column representing the path of each trip, represented by the name of the origin and the destination stations. """ return df.assign( trip_path=lambda df: [ f"{start}{end}" for start, end in zip(df.station_origin, df.station_destination) ] ) def add_sale_delta(df: pd.DataFrame) -> pd.DataFrame: """ Add sale time delta data to ``df``. Args: df: The dataframe to update. Returns: A dataframe containing two additional columns, ``sale_timedelta`` containing the time difference between the departure and the sale time, and ``sale_day`` containing the number of days between the sale and the departure. ``sale_day=0`` means the sale happened after the departure. """ # fmt: off return ( df .assign(sale_timedelta=lambda df: df.sale_datetime - df.departure_datetime) .assign(sale_day=lambda df: df.sale_timedelta.dt.days) ) # fmt: on def add_cancel_delta(df: pd.DataFrame) -> pd.DataFrame: """ Add cancellation time delta data to ``df``. Args: df: The dataframe to update. Returns: A dataframe containing two additional columns, ``cancel_timedelta`` containing the time difference between the departure and the cancellation time if it exists, and ``cancel_day`` containing the number of days between the cancellation and the departure. ``cancel_day=0`` means the cancellation happened after the departure. """ # fmt: off return ( df .assign(cancel_timedelta=lambda df: df.cancel_datetime - df.departure_datetime) .assign(cancel_day=lambda df: df.cancel_timedelta.dt.days) ) # fmt: on @perf.timer def one_hot_encode( df: pd.DataFrame, values: t.List, columns: t.List[str], function: t.Callable[[pd.DataFrame], pd.Series], ) -> pd.DataFrame: """ One-hot encode some values. Args: df: The dataframe to update values: The expected different values to one-hot encode. columns: The names of the columns corresponding to each one-hot encoded value. function: The function applied to ``df``, returning a series containing the values to one-hot encode. Returns: A dataframe containing additional columns, one for each one-hot encoded value, containing ``1`` if ``function(df)`` is equal to the corresponding value and ``0`` otherwise. """ series = function(df) return df.assign( **{ columns[idx]: (series == value).astype(int) for idx, value in enumerate(values) } ) HOURS = list(range(24)) HOUR_COLUMNS = [f"hour_{h}" for h in HOURS] add_hour = ft.partial( one_hot_encode, values=HOURS, columns=HOUR_COLUMNS, function=lambda df: df.departure_datetime.dt.hour, ) """ Add information about the hour of the departure time of the train. Args: df: The dataframe to update. Returns: A dataframe containing additional, one-hot encoded columns for each hour of the day, with 1 if the train departs on that hour. """ DAYS_OF_WEEK = list(range(7)) DAY_OF_WEEK_COLUMNS = [f"day_of_week_{d}" for d in DAYS_OF_WEEK] add_day_of_week = ft.partial( one_hot_encode, values=DAYS_OF_WEEK, columns=DAY_OF_WEEK_COLUMNS, function=lambda df: df.departure_datetime.dt.weekday, ) """ Add information about the day of week of the departure date of the train. Args: df: The dataframe to update. Returns: A dataframe containing additional, one-hot encoded columns for each day of the week, with 1 if the train departs on that day. """ PERIODS = list(range(24)) PERIOD_COLUMNS = [f"period_{p}" for p in PERIODS] add_period = ft.partial( one_hot_encode, values=PERIODS, columns=PERIOD_COLUMNS, function=lambda df: ( (df.departure_datetime.dt.month - 1) * 2 + (df.departure_datetime.dt.day > 15) ), ) """ Add information about the period in the year of the departure date of the train. Args: df: The dataframe to update. Returns: A dataframe containing additional, one-hot encoded columns for each period of the year, with 1 if the train departs on that period. A period is roughly defined as a half-month. The first period of each month ends on the 15th day of that month, and the second period starts on the 16th day. """ PATHS = ["AB", "BA"] PATH_COLUMNS = [f"path_{p}" for p in PATHS] add_path = ft.partial( one_hot_encode, values=PATHS, columns=PATH_COLUMNS, function=lambda df: df.trip_path, ) """ Add information about the path of the trip. Args: df: The dataframe to update. Returns: A dataframe containing additional, one-hot encoded columns for each unique path the train can take; in that case, the trip can only travel between two stations A and B, which means the two unique paths are AB and BA. """ def add_features(df: pd.DataFrame) -> pd.DataFrame: """ Add all the useful features to enrich a dataframe. Args: df: The dataframe to update. Returns: A dataframe containing additional, useful columns. """ return ( df.pipe(add_trip_id) .pipe(add_trip_path) .pipe(add_sale_delta) .pipe(add_cancel_delta) .pipe(add_hour) .pipe(add_day_of_week) .pipe(add_period) .pipe(add_path) ) INFO_COLUMNS = HOUR_COLUMNS + DAY_OF_WEEK_COLUMNS + PERIOD_COLUMNS + PATH_COLUMNS DEFAULT_TEST_SIZE = 0.1 def train_test_split( df: pd.DataFrame, train_size: t.Optional[float] = None, test_size: t.Optional[float] = None, ) -> t.Tuple[pd.DataFrame, pd.DataFrame]: """ Split a dataframe in random groups along the ``trip_id`` column. Args: df: The dataframe to split. The dataframe must contain the column ``trip_id``. train_size: Defaults to ``None``. The size of the training set, as a ratio. Must be between 0 and 1. If ``None``, set such that ``train_size + test_size = 1``. test_size: Defaults to ``None``. The size of the test set, as a ratio. If both ``train_size`` and ``test_size`` are ``None``, defaults to 0.1. Must be between 0 and 1. If ``None``, set such that ``train_size + test_size = 1``. Returns: Two datasets extracted from ``df``. The first one contains ``train_size`` of the unique trip ids of ``df``, while the second one contains ``test_size`` of them. """ if train_size is None and test_size is None: test_size = DEFAULT_TEST_SIZE train_ids, test_ids = sklearn.model_selection.train_test_split( df.trip_id.unique(), train_size=train_size, test_size=test_size ) return ( df.loc[lambda df: df.trip_id.isin(train_ids)], df.loc[lambda df: df.trip_id.isin(test_ids)], ) def split_X_y(df: pd.DataFrame) -> t.Tuple[pd.DataFrame, pd.Series]: """ Split the dataframe ``df`` into ``X`` and ``y`` parts. Args: df: The dataframe to split. Must contain the column ``demand``, the target. Returns: A dataframe containing the input ``X`` for the model, consisting of all the columns except for ``demand``, and the target ``y`` for the model, the column ``demand``. """ X_cols = [c for c in df.columns if c != "demand"] return df[X_cols], df.demand PriceGenerator = t.Callable[[float, float, int], t.List[float]] def generate_prices(min_price: float, max_price: float, n_prices: int) -> t.List[float]: """ Generate a sorted list of prices in a given range. Args: min_price: The minimum price of tickets. max_price: The maximum price of tickets. n_prices: The number of prices to generate. Returns: A list of prices uniformly picked over a range [m, M] such that 5% of values are picked between m and min_price, 90% of values between min_price and max_price, and 5% between max_price and M. """ delta = (max_price - min_price) / 0.9 adjusted_min = min_price - 0.05 * delta return sorted( round(adjusted_min + delta * random.random(), 2) for _ in range(n_prices) ) def compute_demands( sale_prices: t.List[float], target_prices: t.List[float] ) -> t.List[int]: """ Compute the demand for each of target prices, given the full list of sale prices. Using binary search, this algorithm is in O(n log m), where n is the number of target prices and m is the number of sale prices. Args: sale_prices: The sorted list of prices at which tickets were sold. target_prices: The prices to compute the demand for. Returns: The list of demands for each target price. The demand is the number of tickets sold for at least the target value. """ n = len(sale_prices) sale_idx = 0 ans = [] for price in target_prices: sale_idx = bisect.bisect_left(sale_prices, price, lo=sale_idx) ans.append(n - sale_idx) return ans def merge_sorted(arr1: t.List[float], arr2: t.List[float]) -> t.List[float]: """ Merge two sorted arrays into a third sorted array. Using two pointers, this algorithm is in O(n1 + n2), where n1 and n2 are respectively the lengths of ``arr1`` and ``arr2``. Args: arr1: The first array to merge. arr2: The second array to merge. Returns: A sorted array containing all values from ``arr1`` and ``arr2``. """ ans = [] idx1 = 0 idx2 = 0 n1 = len(arr1) n2 = len(arr2) while idx1 < n1 or idx2 < n2: if idx1 == n1: ans.extend(arr2[idx2:]) idx2 = n2 elif idx2 == n2: ans.extend(arr1[idx1:]) idx1 = n1 elif arr1[idx1] < arr2[idx2]: ans.append(arr1[idx1]) idx1 += 1 else: ans.append(arr2[idx2]) idx2 += 1 return ans def describe_previous_demand( previous_total_demand: int, previous_prices: t.List[float], day: int, prices: t.List[float], ) -> pd.DataFrame: """ Describe the demand prior to a given day for a trip given a list of prices. Args: previous_total_demand: The total number of tickets sold up to the day before. previous_prices: The list of all prices for tickets sold up to the day before. day: The day considered, relative to the departure day. prices: The list of prices to compute demand for. Returns: A dataframe containing, for each price in ``prices``, the corresponding demand on all prior days, the total demand on all prior days, the prices, and the day number itself. """ previous_price_demands = compute_demands(previous_prices, prices) return pd.DataFrame( dict( day=day, price=prices, previous_total_demand=previous_total_demand, previous_price_demand=previous_price_demands, ) ) def describe_demand( day_prices: t.List[float], previous_total_demand: int, previous_prices: t.List[float], day: int, prices: t.List[float], ) -> pd.DataFrame: """ Describe the demand on a given day for a trip given a list of prices. Args: day_prices: The prices at which the tickets were sold on a given day. previous_total_demand: The total number of tickets sold up to the day before. previous_prices: The list of all prices for tickets sold up to the day before. day: The day considered, relative to the departure day. prices: The list of prices to compute demand for. Returns: A dataframe containing, for each price in ``prices``, the corresponding demand on that day, as well as the corresponding demand on all prior days, the total demand on all prior days, the prices, and the day number itself. """ price_demands = compute_demands(day_prices, prices) return describe_previous_demand( previous_total_demand, previous_prices, day, prices ).assign(demand=price_demands) def get_trip_info(trip_df: pd.DataFrame) -> pd.Series: """ Extract the information describing a given trip. Args: trip_df: The dataframe containing the data for a given trip. Returns: A Series containing data describing that trip. """ min_price = trip_df.price.min() max_price = trip_df.price.max() return ( trip_df[INFO_COLUMNS].assign(min_price=min_price, max_price=max_price).iloc[0] ) DEFAULT_N_PRICES = 20 def process_trip_at_day( trip_df: pd.DataFrame, day: int, prices: t.List[float] ) -> pd.DataFrame: """ Process the trip data on a given day; does not include the demand on that day. Args: trip_df: The dataframe of the data for a given trip. day: The day to consider. prices: The list of prices to process the data for. Returns: A dataframe containing all the contextual information required to describe what is known of a trip prior ot ``day`` for a given list of ``prices``. This includes one-hot encoded information about the trip itself, the hour of the departure, the day of the week, and the period during the year when the trip occurred, as well as information about bookings prior to ``day``, as described by ``describe_previous_demand``. """ trip_df = trip_df.sort_values("price") trip_info = get_trip_info(trip_df) previous_df = trip_df.loc[lambda df: df.sale_day < day] previous_total_demand = previous_df.shape[0] previous_prices = previous_df.price.tolist() return describe_previous_demand( previous_total_demand, previous_prices, day, prices ).assign(**trip_info) @perf.timer def process_trip( trip_df: pd.DataFrame, n_prices: int = DEFAULT_N_PRICES, ) -> pd.DataFrame: """ Process a trip dataframe to return the data as expected by the model. Args: trip_df: The dataframe corresponding to a unique trip. n_prices: Defaults to ``DEFAULT_N_PRICES``. The number of prices to generate. Returns: A dataframe containing, for each day when sales occurred, ``n_prices`` lines, where the script generates that many random prices. The features are built by the ``describe_demand`` function. """ rows = [] previous_total_demand = 0 previous_prices: t.List[float] = [] trip_info = get_trip_info(trip_df) min_price = trip_info.min_price max_price = trip_info.max_price for day, day_trip_df in trip_df.sort_values("price").groupby("sale_day"): prices = generate_prices(min_price, max_price, n_prices) day_prices = day_trip_df.price.tolist() day_demand = describe_demand( day_prices, previous_total_demand, previous_prices, day, prices, ) rows.append(day_demand) previous_total_demand += day_trip_df.shape[0] previous_prices = merge_sorted(previous_prices, day_prices) return pd.concat(rows).assign(**trip_info) def process_df(df: pd.DataFrame, n_prices: int = DEFAULT_N_PRICES) -> pd.DataFrame: """ Process all trips in ``df`` to generate a full dataframe as expected by the model. Args: df: The dataframe to process. n_prices: Defaults to ``DEFAULT_N_PRICES``. The number of prices to generate. Returns: A full dataframe, as processed by ``process_trip`` for each unique trip in ``df``. """ groups = [] for trip_id, trip_df in df.groupby("trip_id"): groups.append(process_trip(trip_df, n_prices)) logger.info(f"Processed trip {trip_id} successfully.") return pd.concat(groups)
import re from collections import deque, UserDict from dataclasses import dataclass from decimal import Decimal from typing import Generator import questionary class Constants: MAX_TOPPINGS = 4 TOPPINGS = ['lettuce', 'mayo', 'cheese', 'rice', 'tomato', 'hot sauce', 'queso'] MEATS = ['pork', 'extra pork + $1.00', 'beef', 'extra beef + $1.00'] SHELLS = ['hard shell', 'soft shell', 'crispy nacho shell + $1.00'] BASE_TACO_PRICE = 10 TACO_PARENT_KEY = 'Taco' def to_decimal(value): return Decimal(str(value)) class MetaDataNode(UserDict): def __init__(self, meta: dict = None, **kwargs): super().__init__(**kwargs) self.meta = meta if meta is not None else {} def set_price(self, price): self.meta['price'] = price return self class Receipt: @dataclass class ItemInfo: __slots__ = ('name', 'value', 'depth', 'is_item', 'is_parent', 'price', 'has_price') name: str value: 'MetaDataNode' depth: int is_item: bool is_parent: bool price: Decimal has_price: bool def __init__(self): self.data = MetaDataNode() def _get_and_ensure_key_path(self, data, keys): for key in keys: if key not in data: data[key] = MetaDataNode({'is_parent': True}) data = data[key] return data def add_parent(self, name, prefix_keys=()): return self._get_and_ensure_key_path(self.data, (*prefix_keys, name)) def append(self, name, price=None, prefix_keys=()): node = self._get_and_ensure_key_path(self.data, prefix_keys) node[name] = MetaDataNode( {'price': price} if price is not None else {} ) return node def iter_items(self) -> Generator['ItemInfo', None, None]: queue = deque((k, v, 0) for k, v in self.data.items()) while queue: key, value, depth = queue.pop() is_parent = value.meta.get('is_parent', False) price = value.meta.get('price', -1) iteminfo = self.ItemInfo( name=key, value=value, depth=depth, is_item=price >= 0, is_parent=is_parent, price=max(to_decimal(0), price), has_price=price >= 0 ) yield iteminfo if is_parent: queue.extendleft((k, v, depth + 1) for k, v in value.items()) def topping_validator(chooses): if len(chooses) > Constants.MAX_TOPPINGS: return f'Cannot select more than {Constants.MAX_TOPPINGS} toppings!' return True def handle_additional_price_selection(receipt: Receipt, args, prefix_keys=()): if len(args) >= 2: receipt.append(f'+ {args[0].strip()}', to_decimal(re.sub(r'[^0-9.]', '', args[1])), prefix_keys=prefix_keys) else: receipt.append(f'~ {args[0].strip()}', prefix_keys=prefix_keys) def ask_for_taco(): receipt = Receipt() receipt.add_parent(Constants.TACO_PARENT_KEY).set_price(Constants.BASE_TACO_PRICE) shell_args = questionary.select('choose a shell', Constants.SHELLS, use_shortcuts=True).ask().split('+', 1) handle_additional_price_selection(receipt, shell_args, prefix_keys=(Constants.TACO_PARENT_KEY,)) meat_args = questionary.select('choose your meat', Constants.MEATS, use_shortcuts=True).ask().split('+', 1) handle_additional_price_selection(receipt, meat_args, prefix_keys=(Constants.TACO_PARENT_KEY,)) toppings = questionary.checkbox('choose your toppings', Constants.TOPPINGS, validate=topping_validator).ask() for topping in toppings: receipt.append(topping, prefix_keys=(Constants.TACO_PARENT_KEY,)) print('\n\n') total = 0 for item in receipt.iter_items(): if item.has_price: total += item.price print(f'{' ' * item.depth}{item.name} {f'(${item.price})' if item.has_price else ''}') else: print(f'{' ' * item.depth}{item.name}') print(f'\nTOTAL: ${total}') ask_for_taco()
import re from collections import deque, UserDict from dataclasses import dataclass from decimal import Decimal from typing import Generator import questionary class Constants: MAX_TOPPINGS = 4 TOPPINGS = ['lettuce', 'mayo', 'cheese', 'rice', 'tomato', 'hot sauce', 'queso'] MEATS = ['pork', 'extra pork + $1.00', 'beef', 'extra beef + $1.00'] SHELLS = ['hard shell', 'soft shell', 'crispy nacho shell + $1.00'] BASE_TACO_PRICE = 10 TACO_PARENT_KEY = 'Taco' def to_decimal(value): return Decimal(str(value)) class MetaDataNode(UserDict): def __init__(self, meta: dict = None, **kwargs): super().__init__(**kwargs) self.meta = meta if meta is not None else {} def set_price(self, price): self.meta['price'] = price return self class Receipt: @dataclass class ItemInfo: __slots__ = ('name', 'value', 'depth', 'is_item', 'is_parent', 'price', 'has_price') name: str value: 'MetaDataNode' depth: int is_item: bool is_parent: bool price: Decimal has_price: bool def __init__(self): self.data = MetaDataNode() def _get_and_ensure_key_path(self, data, keys): for key in keys: if key not in data: data[key] = MetaDataNode({'is_parent': True}) data = data[key] return data def add_parent(self, name, prefix_keys=()): return self._get_and_ensure_key_path(self.data, (*prefix_keys, name)) def append(self, name, price=None, prefix_keys=()): node = self._get_and_ensure_key_path(self.data, prefix_keys) node[name] = MetaDataNode( {'price': price} if price is not None else {} ) return node def iter_items(self) -> Generator['ItemInfo', None, None]: queue = deque((k, v, 0) for k, v in self.data.items()) while queue: key, value, depth = queue.pop() is_parent = value.meta.get('is_parent', False) price = value.meta.get('price', -1) iteminfo = self.ItemInfo( name=key, value=value, depth=depth, is_item=price >= 0, is_parent=is_parent, price=max(to_decimal(0), price), has_price=price >= 0 ) yield iteminfo if is_parent: queue.extendleft((k, v, depth + 1) for k, v in value.items()) def topping_validator(chooses): if len(chooses) > Constants.MAX_TOPPINGS: return f'Cannot select more than {Constants.MAX_TOPPINGS} toppings!' return True def handle_additional_price_selection(receipt: Receipt, args, prefix_keys=()): if len(args) >= 2: receipt.append(f'+ {args[0].strip()}', to_decimal(re.sub(r'[^0-9.]', '', args[1])), prefix_keys=prefix_keys) else: receipt.append(f'~ {args[0].strip()}', prefix_keys=prefix_keys) def ask_for_taco(): receipt = Receipt() receipt.add_parent(Constants.TACO_PARENT_KEY).set_price(Constants.BASE_TACO_PRICE) shell_args = questionary.select('choose a shell', Constants.SHELLS, use_shortcuts=True).ask().split('+', 1) handle_additional_price_selection(receipt, shell_args, prefix_keys=(Constants.TACO_PARENT_KEY,)) meat_args = questionary.select('choose your meat', Constants.MEATS, use_shortcuts=True).ask().split('+', 1) handle_additional_price_selection(receipt, meat_args, prefix_keys=(Constants.TACO_PARENT_KEY,)) toppings = questionary.checkbox('choose your toppings', Constants.TOPPINGS, validate=topping_validator).ask() for topping in toppings: receipt.append(topping, prefix_keys=(Constants.TACO_PARENT_KEY,)) print('\n\n') total = 0 for item in receipt.iter_items(): if item.has_price: total += item.price print(f'{" " * item.depth}{item.name} {f"(${item.price})" if item.has_price else ""}') else: print(f'{" " * item.depth}{item.name}') print(f'\nTOTAL: ${total}') ask_for_taco()
# Copyright (C) 2019 The Raphielscape Company LLC. # # Licensed under the Raphielscape Public License, Version 1.d (the "License"); # you may not use this file except in compliance with the License. # """ Userbot module containing various sites direct links generators""" import re import urllib.parse import json import requests from subprocess import PIPE, Popen from random import choice from bs4 import BeautifulSoup from humanize import naturalsize from pikabot import CMD_HELP from pikabot.utils import ItzSjDude def subprocess_run(cmd): reply = "" subproc = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True, universal_newlines=True, executable="bash") talk = subproc.communicate() exitCode = subproc.returncode if exitCode != 0: reply += ('```An error was detected while running the subprocess:\n' f'exit code: {exitCode}\n' f'stdout: {talk[0]}\n' f'stderr: {talk[1]}```') return reply return talk @ItzSjDude(outgoing=True, pattern=r"direct(?: |$)([\s\S]*)") async def direct_link_generator(request): """ direct links generator """ await request.edit("`Processing...`") textx = await request.get_reply_message() message = request.pattern_match.group(1) if message: pass elif textx: message = textx.text else: await request.edit("`Usage: .direct <url>`") return reply = '' links = re.findall(r'\bhttps?://.*\.\S+', message) if not links: reply = "`No links found!`" await request.edit(reply) for link in links: if 'drive.google.com' in link: reply += gdrive(link) elif 'zippyshare.com' in link: reply += zippy_share(link) elif 'yadi.sk' in link: reply += yandex_disk(link) elif 'cloud.mail.ru' in link: reply += cm_ru(link) elif 'mediafire.com' in link: reply += mediafire(link) elif 'sourceforge.net' in link: reply += sourceforge(link) elif 'osdn.net' in link: reply += osdn(link) elif 'androidfilehost.com' in link: reply += androidfilehost(link) else: reply += re.findall(r"\bhttps?://(.*?[^/]+)", link)[0] + 'is not supported' await request.edit(reply) def gdrive(url: str) -> str: """ GDrive direct links generator """ drive = 'https://drive.google.com' try: link = re.findall(r'\bhttps?://drive\.google\.com\S+', url)[0] except IndexError: reply = "`No Google drive links found`\n" return reply file_id = '' reply = '' if link.find("view") != -1: file_id = link.split('/')[-2] elif link.find("open?id=") != -1: file_id = link.split("open?id=")[1].strip() elif link.find("uc?id=") != -1: file_id = link.split("uc?id=")[1].strip() url = f'{drive}/uc?export=download&id={file_id}' download = requests.get(url, stream=True, allow_redirects=False) cookies = download.cookies try: # In case of small file size, Google downloads directly dl_url = download.headers["location"] if 'accounts.google.com' in dl_url: # non-public file reply += '`Link is not public!`\n' return reply name = 'Direct Download Link' except KeyError: # In case of download warning page page = BeautifulSoup(download.content, 'lxml') export = drive + page.find('a', {'id': 'uc-download-link'}).get('href') name = page.find('span', {'class': 'uc-name-size'}).text response = requests.get(export, stream=True, allow_redirects=False, cookies=cookies) dl_url = response.headers['location'] if 'accounts.google.com' in dl_url: reply += 'Link is not public!' return reply reply += f'[{name}]({dl_url})\n' return reply def zippy_share(url: str) -> str: """ ZippyShare direct links generator Based on https://github.com/LameLemon/ziggy""" reply = '' dl_url = '' try: link = re.findall(r'\bhttps?://.*zippyshare\.com\S+', url)[0] except IndexError: reply = "`No ZippyShare links found`\n" return reply session = requests.Session() base_url = re.search('http.+.com', link).group() response = session.get(link) page_soup = BeautifulSoup(response.content, "lxml") scripts = page_soup.find_all("script", {"type": "text/javascript"}) for script in scripts: if "getElementById('dlbutton')" in script.text: url_raw = re.search(r'= (?P<url>\".+\" \+ (?P<math>\(.+\)) .+);', script.text).group('url') math = re.search(r'= (?P<url>\".+\" \+ (?P<math>\(.+\)) .+);', script.text).group('math') dl_url = url_raw.replace(math, '"' + str(eval(math)) + '"') break dl_url = base_url + eval(dl_url) name = urllib.parse.unquote(dl_url.split('/')[-1]) reply += f'[{name}]({dl_url})\n' return reply def yandex_disk(url: str) -> str: """ Yandex.Disk direct links generator Based on https://github.com/wldhx/yadisk-direct""" reply = '' try: link = re.findall(r'\bhttps?://.*yadi\.sk\S+', url)[0] except IndexError: reply = "`No Yandex.Disk links found`\n" return reply api = 'https://cloud-api.yandex.net/v1/disk/public/resources/download?public_key={}' try: dl_url = requests.get(api.format(link)).json()['href'] name = dl_url.split('filename=')[1].split('&disposition')[0] reply += f'[{name}]({dl_url})\n' except KeyError: reply += '`Error: File not found / Download limit reached`\n' return reply return reply def cm_ru(url: str) -> str: """ cloud.mail.ru direct links generator Using https://github.com/JrMasterModelBuilder/cmrudl.py""" reply = '' try: link = re.findall(r'\bhttps?://.*cloud\.mail\.ru\S+', url)[0] except IndexError: reply = "`No cloud.mail.ru links found`\n" return reply cmd = f'bin/cmrudl -s {link}' result = subprocess_run(cmd) try: result = result[0].splitlines()[-1] data = json.loads(result) except json.decoder.JSONDecodeError: reply += "`Error: Can't extract the link`\n" return reply except IndexError: return reply dl_url = data['download'] name = data['file_name'] size = naturalsize(int(data['file_size'])) reply += f'[{name} ({size})]({dl_url})\n' return reply def mediafire(url: str) -> str: """ MediaFire direct links generator """ try: link = re.findall(r'\bhttps?://.*mediafire\.com\S+', url)[0] except IndexError: reply = "`No MediaFire links found`\n" return reply reply = '' page = BeautifulSoup(requests.get(link).content, 'lxml') info = page.find('a', {'aria-label': 'Download file'}) dl_url = info.get('href') size = re.findall(r'\(.*\)', info.text)[0] name = page.find('div', {'class': 'filename'}).text reply += f'[{name} {size}]({dl_url})\n' return reply def sourceforge(url: str) -> str: """ SourceForge direct links generator """ try: link = re.findall(r'\bhttps?://.*sourceforge\.net\S+', url)[0] except IndexError: reply = "`No SourceForge links found`\n" return reply file_path = re.findall(r'files(.*)/download', link)[0] reply = f"Mirrors for __{file_path.split("/")[-1]}__\n" project = re.findall(r'projects?/(.*?)/files', link)[0] mirrors = f'https://sourceforge.net/settings/mirror_choices?' \ f'projectname={project}&filename={file_path}' page = BeautifulSoup(requests.get(mirrors).content, 'html.parser') info = page.find('ul', {'id': 'mirrorList'}).findAll('li') for mirror in info[1:]: name = re.findall(r'\((.*)\)', mirror.text.strip())[0] dl_url = f'https://{mirror['id']}.dl.sourceforge.net/project/{project}/{file_path}' reply += f'[{name}]({dl_url}) ' return reply def osdn(url: str) -> str: """ OSDN direct links generator """ osdn_link = 'https://osdn.net' try: link = re.findall(r'\bhttps?://.*osdn\.net\S+', url)[0] except IndexError: reply = "`No OSDN links found`\n" return reply page = BeautifulSoup( requests.get(link, allow_redirects=True).content, 'lxml') info = page.find('a', {'class': 'mirror_link'}) link = urllib.parse.unquote(osdn_link + info['href']) reply = f"Mirrors for __{link.split("/")[-1]}__\n" mirrors = page.find('form', {'id': 'mirror-select-form'}).findAll('tr') for data in mirrors[1:]: mirror = data.find('input')['value'] name = re.findall(r'\((.*)\)', data.findAll('td')[-1].text.strip())[0] dl_url = re.sub(r'm=(.*)&f', f'm={mirror}&f', link) reply += f'[{name}]({dl_url}) ' return reply def androidfilehost(url: str) -> str: """ AFH direct links generator """ try: link = re.findall(r'\bhttps?://.*androidfilehost.*fid.*\S+', url)[0] except IndexError: reply = "`No AFH links found`\n" return reply fid = re.findall(r'\?fid=(.*)', link)[0] session = requests.Session() user_agent = useragent() headers = {'user-agent': user_agent} res = session.get(link, headers=headers, allow_redirects=True) headers = { 'origin': 'https://androidfilehost.com', 'accept-encoding': 'gzip, deflate, br', 'accept-language': 'en-US,en;q=0.9', 'user-agent': user_agent, 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8', 'x-mod-sbb-ctype': 'xhr', 'accept': '*/*', 'referer': f'https://androidfilehost.com/?fid={fid}', 'authority': 'androidfilehost.com', 'x-requested-with': 'XMLHttpRequest', } data = { 'submit': 'submit', 'action': 'getdownloadmirrors', 'fid': f'{fid}' } mirrors = None reply = '' error = "`Error: Can't find Mirrors for the link`\n" try: req = session.post( 'https://androidfilehost.com/libs/otf/mirrors.otf.php', headers=headers, data=data, cookies=res.cookies) mirrors = req.json()['MIRRORS'] except (json.decoder.JSONDecodeError, TypeError): reply += error if not mirrors: reply += error return reply for item in mirrors: name = item['name'] dl_url = item['url'] reply += f'[{name}]({dl_url}) ' return reply def useragent(): """ useragent random setter """ useragents = BeautifulSoup( requests.get( 'https://developers.whatismybrowser.com/' 'useragents/explore/operating_system_name/android/').content, 'lxml').findAll('td', {'class': 'useragent'}) user_agent = choice(useragents) return user_agent.text CMD_HELP.update({ "direct": ".direct <url> <url>\n" "Usage: Generate direct download link from supported URL(s)\n" "Supported websites:\n" "`Google Drive - MEGA.nz - Cloud Mail - Yandex.Disk - AFH - " "ZippyShare - MediaFire - SourceForge - OSDN - GitHub`" })
# Copyright (C) 2019 The Raphielscape Company LLC. # # Licensed under the Raphielscape Public License, Version 1.d (the "License"); # you may not use this file except in compliance with the License. # """ Userbot module containing various sites direct links generators""" import re import urllib.parse import json import requests from subprocess import PIPE, Popen from random import choice from bs4 import BeautifulSoup from humanize import naturalsize from pikabot import CMD_HELP from pikabot.utils import ItzSjDude def subprocess_run(cmd): reply = "" subproc = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True, universal_newlines=True, executable="bash") talk = subproc.communicate() exitCode = subproc.returncode if exitCode != 0: reply += ('```An error was detected while running the subprocess:\n' f'exit code: {exitCode}\n' f'stdout: {talk[0]}\n' f'stderr: {talk[1]}```') return reply return talk @ItzSjDude(outgoing=True, pattern=r"direct(?: |$)([\s\S]*)") async def direct_link_generator(request): """ direct links generator """ await request.edit("`Processing...`") textx = await request.get_reply_message() message = request.pattern_match.group(1) if message: pass elif textx: message = textx.text else: await request.edit("`Usage: .direct <url>`") return reply = '' links = re.findall(r'\bhttps?://.*\.\S+', message) if not links: reply = "`No links found!`" await request.edit(reply) for link in links: if 'drive.google.com' in link: reply += gdrive(link) elif 'zippyshare.com' in link: reply += zippy_share(link) elif 'yadi.sk' in link: reply += yandex_disk(link) elif 'cloud.mail.ru' in link: reply += cm_ru(link) elif 'mediafire.com' in link: reply += mediafire(link) elif 'sourceforge.net' in link: reply += sourceforge(link) elif 'osdn.net' in link: reply += osdn(link) elif 'androidfilehost.com' in link: reply += androidfilehost(link) else: reply += re.findall(r"\bhttps?://(.*?[^/]+)", link)[0] + 'is not supported' await request.edit(reply) def gdrive(url: str) -> str: """ GDrive direct links generator """ drive = 'https://drive.google.com' try: link = re.findall(r'\bhttps?://drive\.google\.com\S+', url)[0] except IndexError: reply = "`No Google drive links found`\n" return reply file_id = '' reply = '' if link.find("view") != -1: file_id = link.split('/')[-2] elif link.find("open?id=") != -1: file_id = link.split("open?id=")[1].strip() elif link.find("uc?id=") != -1: file_id = link.split("uc?id=")[1].strip() url = f'{drive}/uc?export=download&id={file_id}' download = requests.get(url, stream=True, allow_redirects=False) cookies = download.cookies try: # In case of small file size, Google downloads directly dl_url = download.headers["location"] if 'accounts.google.com' in dl_url: # non-public file reply += '`Link is not public!`\n' return reply name = 'Direct Download Link' except KeyError: # In case of download warning page page = BeautifulSoup(download.content, 'lxml') export = drive + page.find('a', {'id': 'uc-download-link'}).get('href') name = page.find('span', {'class': 'uc-name-size'}).text response = requests.get(export, stream=True, allow_redirects=False, cookies=cookies) dl_url = response.headers['location'] if 'accounts.google.com' in dl_url: reply += 'Link is not public!' return reply reply += f'[{name}]({dl_url})\n' return reply def zippy_share(url: str) -> str: """ ZippyShare direct links generator Based on https://github.com/LameLemon/ziggy""" reply = '' dl_url = '' try: link = re.findall(r'\bhttps?://.*zippyshare\.com\S+', url)[0] except IndexError: reply = "`No ZippyShare links found`\n" return reply session = requests.Session() base_url = re.search('http.+.com', link).group() response = session.get(link) page_soup = BeautifulSoup(response.content, "lxml") scripts = page_soup.find_all("script", {"type": "text/javascript"}) for script in scripts: if "getElementById('dlbutton')" in script.text: url_raw = re.search(r'= (?P<url>\".+\" \+ (?P<math>\(.+\)) .+);', script.text).group('url') math = re.search(r'= (?P<url>\".+\" \+ (?P<math>\(.+\)) .+);', script.text).group('math') dl_url = url_raw.replace(math, '"' + str(eval(math)) + '"') break dl_url = base_url + eval(dl_url) name = urllib.parse.unquote(dl_url.split('/')[-1]) reply += f'[{name}]({dl_url})\n' return reply def yandex_disk(url: str) -> str: """ Yandex.Disk direct links generator Based on https://github.com/wldhx/yadisk-direct""" reply = '' try: link = re.findall(r'\bhttps?://.*yadi\.sk\S+', url)[0] except IndexError: reply = "`No Yandex.Disk links found`\n" return reply api = 'https://cloud-api.yandex.net/v1/disk/public/resources/download?public_key={}' try: dl_url = requests.get(api.format(link)).json()['href'] name = dl_url.split('filename=')[1].split('&disposition')[0] reply += f'[{name}]({dl_url})\n' except KeyError: reply += '`Error: File not found / Download limit reached`\n' return reply return reply def cm_ru(url: str) -> str: """ cloud.mail.ru direct links generator Using https://github.com/JrMasterModelBuilder/cmrudl.py""" reply = '' try: link = re.findall(r'\bhttps?://.*cloud\.mail\.ru\S+', url)[0] except IndexError: reply = "`No cloud.mail.ru links found`\n" return reply cmd = f'bin/cmrudl -s {link}' result = subprocess_run(cmd) try: result = result[0].splitlines()[-1] data = json.loads(result) except json.decoder.JSONDecodeError: reply += "`Error: Can't extract the link`\n" return reply except IndexError: return reply dl_url = data['download'] name = data['file_name'] size = naturalsize(int(data['file_size'])) reply += f'[{name} ({size})]({dl_url})\n' return reply def mediafire(url: str) -> str: """ MediaFire direct links generator """ try: link = re.findall(r'\bhttps?://.*mediafire\.com\S+', url)[0] except IndexError: reply = "`No MediaFire links found`\n" return reply reply = '' page = BeautifulSoup(requests.get(link).content, 'lxml') info = page.find('a', {'aria-label': 'Download file'}) dl_url = info.get('href') size = re.findall(r'\(.*\)', info.text)[0] name = page.find('div', {'class': 'filename'}).text reply += f'[{name} {size}]({dl_url})\n' return reply def sourceforge(url: str) -> str: """ SourceForge direct links generator """ try: link = re.findall(r'\bhttps?://.*sourceforge\.net\S+', url)[0] except IndexError: reply = "`No SourceForge links found`\n" return reply file_path = re.findall(r'files(.*)/download', link)[0] reply = f"Mirrors for __{file_path.split('/')[-1]}__\n" project = re.findall(r'projects?/(.*?)/files', link)[0] mirrors = f'https://sourceforge.net/settings/mirror_choices?' \ f'projectname={project}&filename={file_path}' page = BeautifulSoup(requests.get(mirrors).content, 'html.parser') info = page.find('ul', {'id': 'mirrorList'}).findAll('li') for mirror in info[1:]: name = re.findall(r'\((.*)\)', mirror.text.strip())[0] dl_url = f'https://{mirror["id"]}.dl.sourceforge.net/project/{project}/{file_path}' reply += f'[{name}]({dl_url}) ' return reply def osdn(url: str) -> str: """ OSDN direct links generator """ osdn_link = 'https://osdn.net' try: link = re.findall(r'\bhttps?://.*osdn\.net\S+', url)[0] except IndexError: reply = "`No OSDN links found`\n" return reply page = BeautifulSoup( requests.get(link, allow_redirects=True).content, 'lxml') info = page.find('a', {'class': 'mirror_link'}) link = urllib.parse.unquote(osdn_link + info['href']) reply = f"Mirrors for __{link.split('/')[-1]}__\n" mirrors = page.find('form', {'id': 'mirror-select-form'}).findAll('tr') for data in mirrors[1:]: mirror = data.find('input')['value'] name = re.findall(r'\((.*)\)', data.findAll('td')[-1].text.strip())[0] dl_url = re.sub(r'm=(.*)&f', f'm={mirror}&f', link) reply += f'[{name}]({dl_url}) ' return reply def androidfilehost(url: str) -> str: """ AFH direct links generator """ try: link = re.findall(r'\bhttps?://.*androidfilehost.*fid.*\S+', url)[0] except IndexError: reply = "`No AFH links found`\n" return reply fid = re.findall(r'\?fid=(.*)', link)[0] session = requests.Session() user_agent = useragent() headers = {'user-agent': user_agent} res = session.get(link, headers=headers, allow_redirects=True) headers = { 'origin': 'https://androidfilehost.com', 'accept-encoding': 'gzip, deflate, br', 'accept-language': 'en-US,en;q=0.9', 'user-agent': user_agent, 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8', 'x-mod-sbb-ctype': 'xhr', 'accept': '*/*', 'referer': f'https://androidfilehost.com/?fid={fid}', 'authority': 'androidfilehost.com', 'x-requested-with': 'XMLHttpRequest', } data = { 'submit': 'submit', 'action': 'getdownloadmirrors', 'fid': f'{fid}' } mirrors = None reply = '' error = "`Error: Can't find Mirrors for the link`\n" try: req = session.post( 'https://androidfilehost.com/libs/otf/mirrors.otf.php', headers=headers, data=data, cookies=res.cookies) mirrors = req.json()['MIRRORS'] except (json.decoder.JSONDecodeError, TypeError): reply += error if not mirrors: reply += error return reply for item in mirrors: name = item['name'] dl_url = item['url'] reply += f'[{name}]({dl_url}) ' return reply def useragent(): """ useragent random setter """ useragents = BeautifulSoup( requests.get( 'https://developers.whatismybrowser.com/' 'useragents/explore/operating_system_name/android/').content, 'lxml').findAll('td', {'class': 'useragent'}) user_agent = choice(useragents) return user_agent.text CMD_HELP.update({ "direct": ".direct <url> <url>\n" "Usage: Generate direct download link from supported URL(s)\n" "Supported websites:\n" "`Google Drive - MEGA.nz - Cloud Mail - Yandex.Disk - AFH - " "ZippyShare - MediaFire - SourceForge - OSDN - GitHub`" })
#!/usr/bin/env python # -*- coding: utf-8 -*- import json import urllib.request import urllib.parse import logging from pathlib import Path from datetime import datetime from multiprocessing import cpu_count import rasterio import geopandas as gpd from shapely.wkt import loads from ost.helpers import vector as vec, raster as ras from ost.helpers import scihub, helpers as h, srtm from ost.helpers.settings import set_log_level, setup_logfile, OST_ROOT from ost.helpers.settings import check_ard_parameters from ost.s1 import search, refine_inventory, download from ost.s1 import burst_inventory, burst_batch from ost.s1 import grd_batch # get the logger logger = logging.getLogger(__name__) # global variables OST_DATEFORMAT = "%Y-%m-%d" OST_INVENTORY_FILE = 'full.inventory.gpkg' class Generic: def __init__( self, project_dir, aoi, start='1978-06-28', end=datetime.today().strftime(OST_DATEFORMAT), data_mount=None, log_level=logging.INFO ): # ------------------------------------------ # 1 Start logger # set log level to logging.INFO as standard set_log_level(log_level) # ------------------------------------------ # 2 Handle directories # get absolute path to project directory self.project_dir = Path(project_dir).resolve() # create project directory if not existent try: self.project_dir.mkdir(parents=True, exist_ok=True) logger.info(f'Created project directory at {self.project_dir}') except FileExistsError: logger.info('Project directory already exists. ' 'No data has been deleted at this point but ' 'make sure you really want to use this folder.') # define project sub-directories if not set, and create folders self.download_dir = self.project_dir.joinpath('download') self.download_dir.mkdir(parents=True, exist_ok=True) logger.info( f'Downloaded data will be stored in: {self.download_dir}.' ) self.inventory_dir = self.project_dir.joinpath('inventory') self.inventory_dir.mkdir(parents=True, exist_ok=True) logger.info( f'Inventory files will be stored in: {self.inventory_dir}.' ) self.processing_dir = self.project_dir.joinpath('processing') self.processing_dir.mkdir(parents=True, exist_ok=True) logger.info( f'Processed data will be stored in: {self.processing_dir}.' ) self.temp_dir = self.project_dir.joinpath('temp') self.temp_dir.mkdir(parents=True, exist_ok=True) logger.info( f'Using {self.temp_dir} as directory for temporary files.' ) # ------------------------------------------ # 3 create a standard logfile setup_logfile(self.project_dir.joinpath('.processing.log')) # ------------------------------------------ # 4 handle AOI (read and get back WKT) self.aoi = vec.aoi_to_wkt(aoi) # ------------------------------------------ # 5 Handle Period of Interest try: datetime.strptime(start, OST_DATEFORMAT) self.start = start except ValueError: raise ValueError("Incorrect date format for start date. " "It should be YYYY-MM-DD") try: datetime.strptime(end, OST_DATEFORMAT) self.end = end except ValueError: raise ValueError("Incorrect date format for end date. " "It should be YYYY-MM-DD") # ------------------------------------------ # 6 Check data mount if data_mount: if Path(data_mount).exists(): self.data_mount = Path(data_mount) else: raise NotADirectoryError(f'{data_mount} is not a directory.') else: self.data_mount = None # ------------------------------------------ # 7 put all parameters in a dictionary self.config_dict = { 'project_dir': str(self.project_dir), 'download_dir': str(self.download_dir), 'inventory_dir': str(self.inventory_dir), 'processing_dir': str(self.processing_dir), 'temp_dir': str(self.temp_dir), 'data_mount': str(self.data_mount), 'aoi': self.aoi, 'start_date': self.start, 'end_date': self.end } class Sentinel1(Generic): """ A Sentinel-1 specific subclass of the Generic OST class This subclass creates a Sentinel-1 specific """ def __init__( self, project_dir, aoi, start='2014-10-01', end=datetime.today().strftime(OST_DATEFORMAT), data_mount=None, product_type='*', beam_mode='*', polarisation='*', log_level=logging.INFO ): # ------------------------------------------ # 1 Get Generic class attributes super().__init__(project_dir, aoi, start, end, data_mount, log_level) # ------------------------------------------ # 2 Check and set product type if product_type in ['*', 'RAW', 'SLC', 'GRD']: self.product_type = product_type else: raise ValueError( "Product type must be one out of '*', 'RAW', 'SLC', 'GRD'" ) # ------------------------------------------ # 3 Check and set beam mode if beam_mode in ['*', 'IW', 'EW', 'SM']: self.beam_mode = beam_mode else: raise ValueError("Beam mode must be one out of 'IW', 'EW', 'SM'") # ------------------------------------------ # 4 Check and set polarisations possible_pols = ['*', 'VV', 'VH', 'HV', 'HH', 'VV VH', 'HH HV'] if polarisation in possible_pols: self.polarisation = polarisation else: raise ValueError( f"Polarisation must be one out of {possible_pols}" ) # ------------------------------------------ # 5 Initialize the inventory file inventory_file = self.inventory_dir.joinpath(OST_INVENTORY_FILE) if inventory_file.exists(): self.inventory_file = inventory_file logging.info( 'Found an existing inventory file. This can be overwritten ' 'by re-executing the search.' ) self.read_inventory() else: self.inventory = None self.inventory_file = None # ------------------------------------------ # 6 Initialize refinements self.refined_inventory_dict = None self.coverages = None # ------------------------------------------ # 7 Initialize burst inventories self.burst_inventory = None self.burst_inventory_file = None # ------------------------------------------ # 7 Initialize uname and pword to None self.scihub_uname = None self.scihub_pword = None self.asf_uname = None self.asf_pword = None self.peps_uname = None self.peps_pword = None self.onda_uname = None self.onda_pword = None # ------------------------------------------ # methods def search(self, outfile=OST_INVENTORY_FILE, append=False, base_url='https://apihub.copernicus.eu/apihub'): """High Level search function :param outfile: :param append: :param base_url: :return: """ # create scihub conform aoi string aoi = scihub.create_aoi_str(self.aoi) # create scihub conform TOI toi = scihub.create_toi_str(self.start, self.end) # create scihub conform product specification product_specs = scihub.create_s1_product_specs( self.product_type, self.polarisation, self.beam_mode ) # construct the final query query = urllib.parse.quote( f'Sentinel-1 AND {product_specs} AND {aoi} AND {toi}' ) if not self.scihub_uname or not self.scihub_pword: # ask for username and password self.scihub_uname, self.scihub_pword = scihub.ask_credentials() # do the search if outfile == OST_INVENTORY_FILE: self.inventory_file = self.inventory_dir.joinpath( OST_INVENTORY_FILE ) else: self.inventory_file = outfile search.scihub_catalogue( query, self.inventory_file, append, self.scihub_uname, self.scihub_pword, base_url ) if self.inventory_file.exists(): # read inventory into the inventory attribute self.read_inventory() else: logger.info('No images found in the AOI for this date range') def read_inventory(self): """Read the Sentinel-1 data inventory from a OST invetory shapefile :param """ # define column names of inventory file (since in shp they are # truncated) column_names = ['id', 'identifier', 'polarisationmode', 'orbitdirection', 'acquisitiondate', 'relativeorbit', 'orbitnumber', 'product_type', 'slicenumber', 'size', 'beginposition', 'endposition', 'lastrelativeorbitnumber', 'lastorbitnumber', 'uuid', 'platformidentifier', 'missiondatatakeid', 'swathidentifier', 'ingestiondate', 'sensoroperationalmode', 'geometry'] geodataframe = gpd.read_file(self.inventory_file) geodataframe.columns = column_names # add download_path to inventory, so we can check if data needs to be # downloaded self.inventory = search.check_availability( geodataframe, self.download_dir, self.data_mount ) def download_size(self, inventory_df=None): """Function to get the total size of all products when extracted in GB :param inventory_df: :return: """ if inventory_df is None: download_size = self.inventory[ 'size'].str.replace(' GB', '').astype('float32').sum() else: download_size = inventory_df[ 'size'].str.replace(' GB', '').astype('float32').sum() logger.info( f'There are about {download_size} GB need to be downloaded.' ) def refine_inventory(self, exclude_marginal=True, full_aoi_crossing=True, mosaic_refine=True, area_reduce=0.05, complete_coverage=True): self.refined_inventory_dict, self.coverages = ( refine_inventory.search_refinement( self.aoi, self.inventory, self.inventory_dir, exclude_marginal=exclude_marginal, full_aoi_crossing=full_aoi_crossing, mosaic_refine=mosaic_refine, area_reduce=area_reduce, complete_coverage=complete_coverage ) ) # summing up information print('--------------------------------------------') print(' Summing up the info about mosaics') print('--------------------------------------------') for key in self.refined_inventory_dict: print('') print(f' {self.coverages[key]} mosaics for mosaic key {key}') def download(self, inventory_df, mirror=None, concurrent=2, uname=None, pword=None): # if an old inventory exists drop download_path if 'download_path' in inventory_df: inventory_df.drop('download_path', axis=1) # check if scenes exist inventory_df = search.check_availability( inventory_df, self.download_dir, self.data_mount) # extract only those scenes that need to be downloaded download_df = inventory_df[inventory_df.download_path == 'None'] # to download or not ot download - that is here the question if not download_df.any().any(): logger.info('All scenes are ready for being processed.') else: logger.info('One or more scene(s) need(s) to be downloaded.') download.download_sentinel1( download_df, self.download_dir, mirror=mirror, concurrent=concurrent, uname=uname, pword=pword ) def create_burst_inventory( self, inventory_df=None, refine=True, outfile=None, uname=None, pword=None ): # assert SLC product type if not self.product_type == 'SLC': raise ValueError( 'Burst inventory is only possible for the SLC product type' ) # in case a custom inventory is given (e.g. a refined inventory) if inventory_df is None: inventory_df = self.inventory else: # assert that all products are SLCs if not inventory_df.product_type.unique() == 'SLC': raise ValueError( 'The inventory dataframe can only contain SLC products ' 'for the burst inventory ' ) if not outfile: outfile = self.inventory_dir.joinpath('burst_inventory.gpkg') # run the burst inventory self.burst_inventory = burst_inventory.burst_inventory( inventory_df, outfile, download_dir=self.download_dir, data_mount=self.data_mount, uname=uname, pword=pword ) # refine the burst inventory if refine: self.burst_inventory = burst_inventory.refine_burst_inventory( self.aoi, self.burst_inventory, f'{str(outfile)[:-5]}.refined.gpkg' ) def read_burst_inventory(self, burst_file=None): """ :param burst_file: a GeoPackage file created by OST holding a burst inventory :return: geodataframe """ if not burst_file: non_ref = self.inventory_dir.joinpath('burst_inventory.gpkg') refined = self.inventory_dir.joinpath( 'burst_inventory.refined.gpkg' ) if refined.exists(): logger.info( f'Importing refined burst inventory file {str(refined)}.') burst_file = refined elif non_ref.exists(): logger.info( f'Importing refined burst inventory file {str(non_ref)}.') burst_file = non_ref else: raise FileNotFoundError( 'No previously created burst inventory file ' 'has been found.' ) # define column names of file (since in shp they are truncated) # create column names for empty data frame column_names = ['SceneID', 'Track', 'Direction', 'Date', 'SwathID', 'AnxTime', 'BurstNr', 'geometry'] geodataframe = gpd.read_file(burst_file) geodataframe = geodataframe[column_names] self.burst_inventory = geodataframe return geodataframe def plot_inventory(self, inventory_df=None, transparency=0.05, annotate=False): if inventory_df is None: vec.plot_inventory( self.aoi, self.inventory, transparency, annotate ) else: vec.plot_inventory(self.aoi, inventory_df, transparency, annotate) class Sentinel1Batch(Sentinel1): """ A Sentinel-1 specific subclass of the Generic OST class This subclass creates a Sentinel-1 specific """ def __init__( self, project_dir, aoi, start='2014-10-01', end=datetime.today().strftime(OST_DATEFORMAT), data_mount=None, product_type='SLC', beam_mode='IW', polarisation='*', ard_type='OST-GTC', snap_cpu_parallelism=cpu_count(), max_workers=1, log_level=logging.INFO ): # ------------------------------------------ # 1 Initialize super class super().__init__( project_dir, aoi, start, end, data_mount, product_type, beam_mode, polarisation, log_level ) # --------------------------------------- # 1 Check and set ARD type # possible ard types to select from for GRD if product_type == 'GRD': ard_types_grd = ['CEOS', 'Earth-Engine', 'OST-GTC', 'OST-RTC'] if ard_type in ard_types_grd: self.ard_type = ard_type else: raise ValueError('No valid ARD type for product type GRD.' f'Select from {ard_types_grd}') # possible ard types to select from for GRD elif product_type == 'SLC': ard_types_slc = ['OST-GTC', 'OST-RTC', 'OST-COH', 'OST-RTCCOH', 'OST-POL', 'OST-ALL'] if ard_type in ard_types_slc: self.ard_type = ard_type else: raise ValueError('No valid ARD type for product type GRD.' f'Select from {ard_types_slc}') # otherwise the product type is not supported else: raise ValueError(f'Product type {self.product_type} not ' f'supported for processing. Only GRD and SLC ' f'are supported.') # --------------------------------------- # 2 Check beam mode if not beam_mode == 'IW': raise ValueError("Only 'IW' beam mode supported for processing.") # --------------------------------------- # 3 Add snap_cpu_parallelism self.config_dict['snap_cpu_parallelism'] = snap_cpu_parallelism self.config_dict['max_workers'] = max_workers self.config_dict['executor_type'] = 'billiard' # --------------------------------------- # 4 Set up project JSON self.config_file = self.project_dir.joinpath('config.json') self.ard_parameters = self.get_ard_parameters(ard_type) # re-create config dict with update ard parameters self.config_dict.update( processing=self.ard_parameters ) # --------------------------------------- # methods def get_ard_parameters(self, ard_type): # find respective template for selected ARD type template_file = OST_ROOT.joinpath( f"graphs/ard_json/{self.product_type.lower()}" f".{ard_type.replace("-", "_").lower()}.json" ) # open and load parameters with open(template_file, 'r') as ard_file: self.ard_parameters = json.load(ard_file)['processing'] # returning ard_parameters return self.ard_parameters def update_ard_parameters(self, ard_type=None): # if a ard type is selected, load if ard_type: self.get_ard_parameters(ard_type) # check for correctness of ard parameters check_ard_parameters(self.ard_parameters) # re-create project dict with update ard parameters self.config_dict.update( processing=self.ard_parameters ) # dump to json file with open(self.config_file, 'w') as outfile: json.dump(self.config_dict, outfile, indent=4) def set_external_dem(self, dem_file, ellipsoid_correction=True): # check if file exists if not Path(dem_file).exists(): raise FileNotFoundError(f'No file found at {dem_file}.') # get no data value with rasterio.open(dem_file) as file: dem_nodata = int(file.nodata) # get resampling adn projection‚ img_res = self.ard_parameters['single_ARD']['dem']['image_resampling'] dem_res = self.ard_parameters['single_ARD']['dem']['dem_resampling'] projection = self.ard_parameters['single_ARD']['dem']['out_projection'] # update ard parameters dem_dict = dict({'dem_name': 'External DEM', 'dem_file': dem_file, 'dem_nodata': dem_nodata, 'dem_resampling': dem_res, 'image_resampling': img_res, 'egm_correction': ellipsoid_correction, 'out_projection': projection }) # update ard_parameters self.ard_parameters['single_ARD']['dem'] = dem_dict def pre_download_srtm(self): logger.info('Pre-downloading SRTM tiles') srtm.download_srtm(self.aoi) def bursts_to_ards( self, timeseries=False, timescan=False, mosaic=False, overwrite=False ): """Batch processing function for full burst pre-processing workflow This function allows for the generation of the :param timeseries: if True, Time-series will be generated for each burst id :type timeseries: bool, optional :param timescan: if True, Timescans will be generated for each burst id type: timescan: bool, optional :param mosaic: if True, Mosaics will be generated from the Time-Series/Timescans of each burst id :type mosaic: bool, optional :param overwrite: (if True, the processing folder will be emptied :type overwrite: bool, optional :param max_workers: number of parallel burst :type max_workers: int, default=1 processing jobs :return: """ # -------------------------------------------- # 2 Check if within SRTM coverage # set ellipsoid correction and force GTC production # when outside SRTM center_lat = loads(self.aoi).centroid.y if float(center_lat) > 59 or float(center_lat) < -59: logger.info('Scene is outside SRTM coverage. Snap will therefore ' 'use the Earth\'s geoid model.') self.ard_parameters['single_ARD']['dem'][ 'dem_name'] = 'Aster 1sec GDEM' # -------------------------------------------- # 3 subset determination # we need a check function that checks self.config_dict['subset'] = False # This does not work at the moment, and maybe does not even make sense, # since for the co-registration we would need a sufficient # part of the image # self.config_dict['subset'] = vec.set_subset( # self.aoi, self.burst_inventory # ) # -------------------------------------------- # 4 Check ard parameters in case they have been updated, # and write them to json file self.update_ard_parameters() # -------------------------------------------- # 1 delete data from previous runnings # delete data in temporary directory in case there is # something left from previous runs h.remove_folder_content(self.config_dict['temp_dir']) # in case we strat from scratch, delete all data # within processing folder if overwrite: logger.info('Deleting processing folder to start from scratch') h.remove_folder_content(self.config_dict['processing_dir']) # -------------------------------------------- # 5 set resolution to degree # self.ard_parameters['resolution'] = h.resolution_in_degree( # self.center_lat, self.ard_parameters['resolution']) if self.config_dict['max_workers'] > 1: self.pre_download_srtm() # -------------------------------------------- # 6 run the burst to ard batch routine (up to 3 times if needed) i = 1 while i < 4: processed_bursts_df = burst_batch.bursts_to_ards( self.burst_inventory, self.config_file ) if False in processed_bursts_df.error.isnull().tolist(): i += 1 else: i = 5 # write processed df to file processing_dir = Path(self.config_dict['processing_dir']) processed_bursts_df.to_pickle( processing_dir.joinpath('processed_bursts.pickle') ) # if not all have been processed, raise an error to avoid # false time-series processing if i == 4: raise RuntimeError( 'Not all all bursts have been successfully processed' ) # -------------------------------------------- # 6 run the timeseries creation if timeseries or timescan: tseries_df = burst_batch.ards_to_timeseries( self.burst_inventory, self.config_file ) # -------------------------------------------- # 7 run the timescan creation if timescan: burst_batch.timeseries_to_timescan( self.burst_inventory, self.config_file ) # -------------------------------------------- # 8 mosaic the time-series if mosaic and timeseries: burst_batch.mosaic_timeseries( self.burst_inventory, self.config_file ) # -------------------------------------------- # 9 mosaic the timescans if mosaic and timescan: burst_batch.mosaic_timescan( self.burst_inventory, self.config_file ) # return tseries_df @staticmethod def create_timeseries_animation( timeseries_dir, product_list, outfile, shrink_factor=1, resampling_factor=5, duration=1, add_dates=False, prefix=False ): ras.create_timeseries_animation(timeseries_dir, product_list, outfile, shrink_factor=shrink_factor, duration=duration, resampling_factor=resampling_factor, add_dates=add_dates, prefix=prefix) def grds_to_ards( self, inventory_df, timeseries=False, timescan=False, mosaic=False, overwrite=False, max_workers=1, executor_type='billiard' ): self.config_dict['max_workers'] = max_workers self.config_dict['executor_type'] = executor_type # in case we start from scratch, delete all data # within processing folder if overwrite: logger.info('Deleting processing folder to start from scratch') h.remove_folder_content(self.processing_dir) # -------------------------------------------- # 2 Check if within SRTM coverage # set ellipsoid correction and force GTC production # when outside SRTM center_lat = loads(self.aoi).centroid.y if float(center_lat) > 59 or float(center_lat) < -59: logger.info( 'Scene is outside SRTM coverage. Snap will therefore use ' 'the GETASSE30 DEM. Also consider to use a stereographic ' 'projection. and project to NSIDC Sea Ice Polar ' 'Stereographic North projection (EPSG 3413).' ) epsg = input( 'Please type the EPSG you want to project the output data or ' 'just press enter for keeping Lat/Lon coordinate system ' '(e.g. 3413 for NSIDC Sea Ice Polar Stereographic North ' 'projection, or 3976 for NSIDC Sea Ice Polar Stereographic ' 'South projection' ) if not epsg: epsg = 4326 self.ard_parameters['single_ARD']['dem'][ 'dem_name'] = 'GETASSE30' self.ard_parameters['single_ARD']['dem'][ 'out_projection'] = int(epsg) # -------------------------------------------- # 3 subset determination # we need a check function that checks self.config_dict.update( subset=vec.set_subset(self.aoi, inventory_df) ) # dump to json file with open(self.config_file, 'w') as outfile: json.dump(self.config_dict, outfile, indent=4) # -------------------------------------------- # 4 Check ard parameters in case they have been updated, # and write them to json file self.update_ard_parameters() # -------------------------------------------- # 1 delete data in case of previous runs # delete data in temporary directory in case there is # something left from aborted previous runs h.remove_folder_content(self.config_dict['temp_dir']) # -------------------------------------------- # 5 set resolution in degree # self.center_lat = loads(self.aoi).centroid.y # if float(self.center_lat) > 59 or float(self.center_lat) < -59: # logger.info( # 'Scene is outside SRTM coverage. Will use 30m # # 'ASTER DEM instead.' # ) # self.ard_parameters['dem'] = 'ASTER 1sec GDEM' # -------------------------------------------- # 5 set resolution in degree # the grd to ard batch routine processing_df = grd_batch.grd_to_ard_batch( inventory_df, self.config_file ) # time-series part if timeseries or timescan: grd_batch.ards_to_timeseries(inventory_df, self.config_file) if timescan: grd_batch.timeseries_to_timescan(inventory_df, self.config_file) if mosaic and timeseries: grd_batch.mosaic_timeseries(inventory_df, self.config_file) # -------------------------------------------- # 9 mosaic the timescans if mosaic and timescan: grd_batch.mosaic_timescan(self.config_file) return processing_df
#!/usr/bin/env python # -*- coding: utf-8 -*- import json import urllib.request import urllib.parse import logging from pathlib import Path from datetime import datetime from multiprocessing import cpu_count import rasterio import geopandas as gpd from shapely.wkt import loads from ost.helpers import vector as vec, raster as ras from ost.helpers import scihub, helpers as h, srtm from ost.helpers.settings import set_log_level, setup_logfile, OST_ROOT from ost.helpers.settings import check_ard_parameters from ost.s1 import search, refine_inventory, download from ost.s1 import burst_inventory, burst_batch from ost.s1 import grd_batch # get the logger logger = logging.getLogger(__name__) # global variables OST_DATEFORMAT = "%Y-%m-%d" OST_INVENTORY_FILE = 'full.inventory.gpkg' class Generic: def __init__( self, project_dir, aoi, start='1978-06-28', end=datetime.today().strftime(OST_DATEFORMAT), data_mount=None, log_level=logging.INFO ): # ------------------------------------------ # 1 Start logger # set log level to logging.INFO as standard set_log_level(log_level) # ------------------------------------------ # 2 Handle directories # get absolute path to project directory self.project_dir = Path(project_dir).resolve() # create project directory if not existent try: self.project_dir.mkdir(parents=True, exist_ok=True) logger.info(f'Created project directory at {self.project_dir}') except FileExistsError: logger.info('Project directory already exists. ' 'No data has been deleted at this point but ' 'make sure you really want to use this folder.') # define project sub-directories if not set, and create folders self.download_dir = self.project_dir.joinpath('download') self.download_dir.mkdir(parents=True, exist_ok=True) logger.info( f'Downloaded data will be stored in: {self.download_dir}.' ) self.inventory_dir = self.project_dir.joinpath('inventory') self.inventory_dir.mkdir(parents=True, exist_ok=True) logger.info( f'Inventory files will be stored in: {self.inventory_dir}.' ) self.processing_dir = self.project_dir.joinpath('processing') self.processing_dir.mkdir(parents=True, exist_ok=True) logger.info( f'Processed data will be stored in: {self.processing_dir}.' ) self.temp_dir = self.project_dir.joinpath('temp') self.temp_dir.mkdir(parents=True, exist_ok=True) logger.info( f'Using {self.temp_dir} as directory for temporary files.' ) # ------------------------------------------ # 3 create a standard logfile setup_logfile(self.project_dir.joinpath('.processing.log')) # ------------------------------------------ # 4 handle AOI (read and get back WKT) self.aoi = vec.aoi_to_wkt(aoi) # ------------------------------------------ # 5 Handle Period of Interest try: datetime.strptime(start, OST_DATEFORMAT) self.start = start except ValueError: raise ValueError("Incorrect date format for start date. " "It should be YYYY-MM-DD") try: datetime.strptime(end, OST_DATEFORMAT) self.end = end except ValueError: raise ValueError("Incorrect date format for end date. " "It should be YYYY-MM-DD") # ------------------------------------------ # 6 Check data mount if data_mount: if Path(data_mount).exists(): self.data_mount = Path(data_mount) else: raise NotADirectoryError(f'{data_mount} is not a directory.') else: self.data_mount = None # ------------------------------------------ # 7 put all parameters in a dictionary self.config_dict = { 'project_dir': str(self.project_dir), 'download_dir': str(self.download_dir), 'inventory_dir': str(self.inventory_dir), 'processing_dir': str(self.processing_dir), 'temp_dir': str(self.temp_dir), 'data_mount': str(self.data_mount), 'aoi': self.aoi, 'start_date': self.start, 'end_date': self.end } class Sentinel1(Generic): """ A Sentinel-1 specific subclass of the Generic OST class This subclass creates a Sentinel-1 specific """ def __init__( self, project_dir, aoi, start='2014-10-01', end=datetime.today().strftime(OST_DATEFORMAT), data_mount=None, product_type='*', beam_mode='*', polarisation='*', log_level=logging.INFO ): # ------------------------------------------ # 1 Get Generic class attributes super().__init__(project_dir, aoi, start, end, data_mount, log_level) # ------------------------------------------ # 2 Check and set product type if product_type in ['*', 'RAW', 'SLC', 'GRD']: self.product_type = product_type else: raise ValueError( "Product type must be one out of '*', 'RAW', 'SLC', 'GRD'" ) # ------------------------------------------ # 3 Check and set beam mode if beam_mode in ['*', 'IW', 'EW', 'SM']: self.beam_mode = beam_mode else: raise ValueError("Beam mode must be one out of 'IW', 'EW', 'SM'") # ------------------------------------------ # 4 Check and set polarisations possible_pols = ['*', 'VV', 'VH', 'HV', 'HH', 'VV VH', 'HH HV'] if polarisation in possible_pols: self.polarisation = polarisation else: raise ValueError( f"Polarisation must be one out of {possible_pols}" ) # ------------------------------------------ # 5 Initialize the inventory file inventory_file = self.inventory_dir.joinpath(OST_INVENTORY_FILE) if inventory_file.exists(): self.inventory_file = inventory_file logging.info( 'Found an existing inventory file. This can be overwritten ' 'by re-executing the search.' ) self.read_inventory() else: self.inventory = None self.inventory_file = None # ------------------------------------------ # 6 Initialize refinements self.refined_inventory_dict = None self.coverages = None # ------------------------------------------ # 7 Initialize burst inventories self.burst_inventory = None self.burst_inventory_file = None # ------------------------------------------ # 7 Initialize uname and pword to None self.scihub_uname = None self.scihub_pword = None self.asf_uname = None self.asf_pword = None self.peps_uname = None self.peps_pword = None self.onda_uname = None self.onda_pword = None # ------------------------------------------ # methods def search(self, outfile=OST_INVENTORY_FILE, append=False, base_url='https://apihub.copernicus.eu/apihub'): """High Level search function :param outfile: :param append: :param base_url: :return: """ # create scihub conform aoi string aoi = scihub.create_aoi_str(self.aoi) # create scihub conform TOI toi = scihub.create_toi_str(self.start, self.end) # create scihub conform product specification product_specs = scihub.create_s1_product_specs( self.product_type, self.polarisation, self.beam_mode ) # construct the final query query = urllib.parse.quote( f'Sentinel-1 AND {product_specs} AND {aoi} AND {toi}' ) if not self.scihub_uname or not self.scihub_pword: # ask for username and password self.scihub_uname, self.scihub_pword = scihub.ask_credentials() # do the search if outfile == OST_INVENTORY_FILE: self.inventory_file = self.inventory_dir.joinpath( OST_INVENTORY_FILE ) else: self.inventory_file = outfile search.scihub_catalogue( query, self.inventory_file, append, self.scihub_uname, self.scihub_pword, base_url ) if self.inventory_file.exists(): # read inventory into the inventory attribute self.read_inventory() else: logger.info('No images found in the AOI for this date range') def read_inventory(self): """Read the Sentinel-1 data inventory from a OST invetory shapefile :param """ # define column names of inventory file (since in shp they are # truncated) column_names = ['id', 'identifier', 'polarisationmode', 'orbitdirection', 'acquisitiondate', 'relativeorbit', 'orbitnumber', 'product_type', 'slicenumber', 'size', 'beginposition', 'endposition', 'lastrelativeorbitnumber', 'lastorbitnumber', 'uuid', 'platformidentifier', 'missiondatatakeid', 'swathidentifier', 'ingestiondate', 'sensoroperationalmode', 'geometry'] geodataframe = gpd.read_file(self.inventory_file) geodataframe.columns = column_names # add download_path to inventory, so we can check if data needs to be # downloaded self.inventory = search.check_availability( geodataframe, self.download_dir, self.data_mount ) def download_size(self, inventory_df=None): """Function to get the total size of all products when extracted in GB :param inventory_df: :return: """ if inventory_df is None: download_size = self.inventory[ 'size'].str.replace(' GB', '').astype('float32').sum() else: download_size = inventory_df[ 'size'].str.replace(' GB', '').astype('float32').sum() logger.info( f'There are about {download_size} GB need to be downloaded.' ) def refine_inventory(self, exclude_marginal=True, full_aoi_crossing=True, mosaic_refine=True, area_reduce=0.05, complete_coverage=True): self.refined_inventory_dict, self.coverages = ( refine_inventory.search_refinement( self.aoi, self.inventory, self.inventory_dir, exclude_marginal=exclude_marginal, full_aoi_crossing=full_aoi_crossing, mosaic_refine=mosaic_refine, area_reduce=area_reduce, complete_coverage=complete_coverage ) ) # summing up information print('--------------------------------------------') print(' Summing up the info about mosaics') print('--------------------------------------------') for key in self.refined_inventory_dict: print('') print(f' {self.coverages[key]} mosaics for mosaic key {key}') def download(self, inventory_df, mirror=None, concurrent=2, uname=None, pword=None): # if an old inventory exists drop download_path if 'download_path' in inventory_df: inventory_df.drop('download_path', axis=1) # check if scenes exist inventory_df = search.check_availability( inventory_df, self.download_dir, self.data_mount) # extract only those scenes that need to be downloaded download_df = inventory_df[inventory_df.download_path == 'None'] # to download or not ot download - that is here the question if not download_df.any().any(): logger.info('All scenes are ready for being processed.') else: logger.info('One or more scene(s) need(s) to be downloaded.') download.download_sentinel1( download_df, self.download_dir, mirror=mirror, concurrent=concurrent, uname=uname, pword=pword ) def create_burst_inventory( self, inventory_df=None, refine=True, outfile=None, uname=None, pword=None ): # assert SLC product type if not self.product_type == 'SLC': raise ValueError( 'Burst inventory is only possible for the SLC product type' ) # in case a custom inventory is given (e.g. a refined inventory) if inventory_df is None: inventory_df = self.inventory else: # assert that all products are SLCs if not inventory_df.product_type.unique() == 'SLC': raise ValueError( 'The inventory dataframe can only contain SLC products ' 'for the burst inventory ' ) if not outfile: outfile = self.inventory_dir.joinpath('burst_inventory.gpkg') # run the burst inventory self.burst_inventory = burst_inventory.burst_inventory( inventory_df, outfile, download_dir=self.download_dir, data_mount=self.data_mount, uname=uname, pword=pword ) # refine the burst inventory if refine: self.burst_inventory = burst_inventory.refine_burst_inventory( self.aoi, self.burst_inventory, f'{str(outfile)[:-5]}.refined.gpkg' ) def read_burst_inventory(self, burst_file=None): """ :param burst_file: a GeoPackage file created by OST holding a burst inventory :return: geodataframe """ if not burst_file: non_ref = self.inventory_dir.joinpath('burst_inventory.gpkg') refined = self.inventory_dir.joinpath( 'burst_inventory.refined.gpkg' ) if refined.exists(): logger.info( f'Importing refined burst inventory file {str(refined)}.') burst_file = refined elif non_ref.exists(): logger.info( f'Importing refined burst inventory file {str(non_ref)}.') burst_file = non_ref else: raise FileNotFoundError( 'No previously created burst inventory file ' 'has been found.' ) # define column names of file (since in shp they are truncated) # create column names for empty data frame column_names = ['SceneID', 'Track', 'Direction', 'Date', 'SwathID', 'AnxTime', 'BurstNr', 'geometry'] geodataframe = gpd.read_file(burst_file) geodataframe = geodataframe[column_names] self.burst_inventory = geodataframe return geodataframe def plot_inventory(self, inventory_df=None, transparency=0.05, annotate=False): if inventory_df is None: vec.plot_inventory( self.aoi, self.inventory, transparency, annotate ) else: vec.plot_inventory(self.aoi, inventory_df, transparency, annotate) class Sentinel1Batch(Sentinel1): """ A Sentinel-1 specific subclass of the Generic OST class This subclass creates a Sentinel-1 specific """ def __init__( self, project_dir, aoi, start='2014-10-01', end=datetime.today().strftime(OST_DATEFORMAT), data_mount=None, product_type='SLC', beam_mode='IW', polarisation='*', ard_type='OST-GTC', snap_cpu_parallelism=cpu_count(), max_workers=1, log_level=logging.INFO ): # ------------------------------------------ # 1 Initialize super class super().__init__( project_dir, aoi, start, end, data_mount, product_type, beam_mode, polarisation, log_level ) # --------------------------------------- # 1 Check and set ARD type # possible ard types to select from for GRD if product_type == 'GRD': ard_types_grd = ['CEOS', 'Earth-Engine', 'OST-GTC', 'OST-RTC'] if ard_type in ard_types_grd: self.ard_type = ard_type else: raise ValueError('No valid ARD type for product type GRD.' f'Select from {ard_types_grd}') # possible ard types to select from for GRD elif product_type == 'SLC': ard_types_slc = ['OST-GTC', 'OST-RTC', 'OST-COH', 'OST-RTCCOH', 'OST-POL', 'OST-ALL'] if ard_type in ard_types_slc: self.ard_type = ard_type else: raise ValueError('No valid ARD type for product type GRD.' f'Select from {ard_types_slc}') # otherwise the product type is not supported else: raise ValueError(f'Product type {self.product_type} not ' f'supported for processing. Only GRD and SLC ' f'are supported.') # --------------------------------------- # 2 Check beam mode if not beam_mode == 'IW': raise ValueError("Only 'IW' beam mode supported for processing.") # --------------------------------------- # 3 Add snap_cpu_parallelism self.config_dict['snap_cpu_parallelism'] = snap_cpu_parallelism self.config_dict['max_workers'] = max_workers self.config_dict['executor_type'] = 'billiard' # --------------------------------------- # 4 Set up project JSON self.config_file = self.project_dir.joinpath('config.json') self.ard_parameters = self.get_ard_parameters(ard_type) # re-create config dict with update ard parameters self.config_dict.update( processing=self.ard_parameters ) # --------------------------------------- # methods def get_ard_parameters(self, ard_type): # find respective template for selected ARD type template_file = OST_ROOT.joinpath( f"graphs/ard_json/{self.product_type.lower()}" f".{ard_type.replace('-', '_').lower()}.json" ) # open and load parameters with open(template_file, 'r') as ard_file: self.ard_parameters = json.load(ard_file)['processing'] # returning ard_parameters return self.ard_parameters def update_ard_parameters(self, ard_type=None): # if a ard type is selected, load if ard_type: self.get_ard_parameters(ard_type) # check for correctness of ard parameters check_ard_parameters(self.ard_parameters) # re-create project dict with update ard parameters self.config_dict.update( processing=self.ard_parameters ) # dump to json file with open(self.config_file, 'w') as outfile: json.dump(self.config_dict, outfile, indent=4) def set_external_dem(self, dem_file, ellipsoid_correction=True): # check if file exists if not Path(dem_file).exists(): raise FileNotFoundError(f'No file found at {dem_file}.') # get no data value with rasterio.open(dem_file) as file: dem_nodata = int(file.nodata) # get resampling adn projection‚ img_res = self.ard_parameters['single_ARD']['dem']['image_resampling'] dem_res = self.ard_parameters['single_ARD']['dem']['dem_resampling'] projection = self.ard_parameters['single_ARD']['dem']['out_projection'] # update ard parameters dem_dict = dict({'dem_name': 'External DEM', 'dem_file': dem_file, 'dem_nodata': dem_nodata, 'dem_resampling': dem_res, 'image_resampling': img_res, 'egm_correction': ellipsoid_correction, 'out_projection': projection }) # update ard_parameters self.ard_parameters['single_ARD']['dem'] = dem_dict def pre_download_srtm(self): logger.info('Pre-downloading SRTM tiles') srtm.download_srtm(self.aoi) def bursts_to_ards( self, timeseries=False, timescan=False, mosaic=False, overwrite=False ): """Batch processing function for full burst pre-processing workflow This function allows for the generation of the :param timeseries: if True, Time-series will be generated for each burst id :type timeseries: bool, optional :param timescan: if True, Timescans will be generated for each burst id type: timescan: bool, optional :param mosaic: if True, Mosaics will be generated from the Time-Series/Timescans of each burst id :type mosaic: bool, optional :param overwrite: (if True, the processing folder will be emptied :type overwrite: bool, optional :param max_workers: number of parallel burst :type max_workers: int, default=1 processing jobs :return: """ # -------------------------------------------- # 2 Check if within SRTM coverage # set ellipsoid correction and force GTC production # when outside SRTM center_lat = loads(self.aoi).centroid.y if float(center_lat) > 59 or float(center_lat) < -59: logger.info('Scene is outside SRTM coverage. Snap will therefore ' 'use the Earth\'s geoid model.') self.ard_parameters['single_ARD']['dem'][ 'dem_name'] = 'Aster 1sec GDEM' # -------------------------------------------- # 3 subset determination # we need a check function that checks self.config_dict['subset'] = False # This does not work at the moment, and maybe does not even make sense, # since for the co-registration we would need a sufficient # part of the image # self.config_dict['subset'] = vec.set_subset( # self.aoi, self.burst_inventory # ) # -------------------------------------------- # 4 Check ard parameters in case they have been updated, # and write them to json file self.update_ard_parameters() # -------------------------------------------- # 1 delete data from previous runnings # delete data in temporary directory in case there is # something left from previous runs h.remove_folder_content(self.config_dict['temp_dir']) # in case we strat from scratch, delete all data # within processing folder if overwrite: logger.info('Deleting processing folder to start from scratch') h.remove_folder_content(self.config_dict['processing_dir']) # -------------------------------------------- # 5 set resolution to degree # self.ard_parameters['resolution'] = h.resolution_in_degree( # self.center_lat, self.ard_parameters['resolution']) if self.config_dict['max_workers'] > 1: self.pre_download_srtm() # -------------------------------------------- # 6 run the burst to ard batch routine (up to 3 times if needed) i = 1 while i < 4: processed_bursts_df = burst_batch.bursts_to_ards( self.burst_inventory, self.config_file ) if False in processed_bursts_df.error.isnull().tolist(): i += 1 else: i = 5 # write processed df to file processing_dir = Path(self.config_dict['processing_dir']) processed_bursts_df.to_pickle( processing_dir.joinpath('processed_bursts.pickle') ) # if not all have been processed, raise an error to avoid # false time-series processing if i == 4: raise RuntimeError( 'Not all all bursts have been successfully processed' ) # -------------------------------------------- # 6 run the timeseries creation if timeseries or timescan: tseries_df = burst_batch.ards_to_timeseries( self.burst_inventory, self.config_file ) # -------------------------------------------- # 7 run the timescan creation if timescan: burst_batch.timeseries_to_timescan( self.burst_inventory, self.config_file ) # -------------------------------------------- # 8 mosaic the time-series if mosaic and timeseries: burst_batch.mosaic_timeseries( self.burst_inventory, self.config_file ) # -------------------------------------------- # 9 mosaic the timescans if mosaic and timescan: burst_batch.mosaic_timescan( self.burst_inventory, self.config_file ) # return tseries_df @staticmethod def create_timeseries_animation( timeseries_dir, product_list, outfile, shrink_factor=1, resampling_factor=5, duration=1, add_dates=False, prefix=False ): ras.create_timeseries_animation(timeseries_dir, product_list, outfile, shrink_factor=shrink_factor, duration=duration, resampling_factor=resampling_factor, add_dates=add_dates, prefix=prefix) def grds_to_ards( self, inventory_df, timeseries=False, timescan=False, mosaic=False, overwrite=False, max_workers=1, executor_type='billiard' ): self.config_dict['max_workers'] = max_workers self.config_dict['executor_type'] = executor_type # in case we start from scratch, delete all data # within processing folder if overwrite: logger.info('Deleting processing folder to start from scratch') h.remove_folder_content(self.processing_dir) # -------------------------------------------- # 2 Check if within SRTM coverage # set ellipsoid correction and force GTC production # when outside SRTM center_lat = loads(self.aoi).centroid.y if float(center_lat) > 59 or float(center_lat) < -59: logger.info( 'Scene is outside SRTM coverage. Snap will therefore use ' 'the GETASSE30 DEM. Also consider to use a stereographic ' 'projection. and project to NSIDC Sea Ice Polar ' 'Stereographic North projection (EPSG 3413).' ) epsg = input( 'Please type the EPSG you want to project the output data or ' 'just press enter for keeping Lat/Lon coordinate system ' '(e.g. 3413 for NSIDC Sea Ice Polar Stereographic North ' 'projection, or 3976 for NSIDC Sea Ice Polar Stereographic ' 'South projection' ) if not epsg: epsg = 4326 self.ard_parameters['single_ARD']['dem'][ 'dem_name'] = 'GETASSE30' self.ard_parameters['single_ARD']['dem'][ 'out_projection'] = int(epsg) # -------------------------------------------- # 3 subset determination # we need a check function that checks self.config_dict.update( subset=vec.set_subset(self.aoi, inventory_df) ) # dump to json file with open(self.config_file, 'w') as outfile: json.dump(self.config_dict, outfile, indent=4) # -------------------------------------------- # 4 Check ard parameters in case they have been updated, # and write them to json file self.update_ard_parameters() # -------------------------------------------- # 1 delete data in case of previous runs # delete data in temporary directory in case there is # something left from aborted previous runs h.remove_folder_content(self.config_dict['temp_dir']) # -------------------------------------------- # 5 set resolution in degree # self.center_lat = loads(self.aoi).centroid.y # if float(self.center_lat) > 59 or float(self.center_lat) < -59: # logger.info( # 'Scene is outside SRTM coverage. Will use 30m # # 'ASTER DEM instead.' # ) # self.ard_parameters['dem'] = 'ASTER 1sec GDEM' # -------------------------------------------- # 5 set resolution in degree # the grd to ard batch routine processing_df = grd_batch.grd_to_ard_batch( inventory_df, self.config_file ) # time-series part if timeseries or timescan: grd_batch.ards_to_timeseries(inventory_df, self.config_file) if timescan: grd_batch.timeseries_to_timescan(inventory_df, self.config_file) if mosaic and timeseries: grd_batch.mosaic_timeseries(inventory_df, self.config_file) # -------------------------------------------- # 9 mosaic the timescans if mosaic and timescan: grd_batch.mosaic_timescan(self.config_file) return processing_df
from datetime import datetime as dt, timedelta as td import boto3 from botocore.errorfactory import ClientError def get_client(): return boto3.client('s3') def get_prev_file_name(bucket, file_prefix, bookmark_file, baseline_file): s3_client = get_client() try: bookmark_file = s3_client.get_object( Bucket=bucket, Key=f"{file_prefix}/{bookmark_file}" ) prev_file = bookmark_file['Body'].read().decode('utf-8') except ClientError as e: if e.response['Error']['Code'] == 'NoSuchKey': prev_file = baseline_file else: raise return prev_file def get_next_file_name(file_name): dt_part = file_name.split('.')[0] next_file = f"{dt.strftime(dt.strptime(dt_part, "%Y-%M-%d-%H") + td(hours=1), "%Y-%M-%d-%-H")}.json.gz" return next_file def upload_bookmark(bucket, file_prefix, bookmark_file, bookmark_contents): s3_client = get_client() s3_client.put_object( Bucket=bucket, Key=f'{file_prefix}/{bookmark_file}', Body=bookmark_contents.encode('utf-8') )
from datetime import datetime as dt, timedelta as td import boto3 from botocore.errorfactory import ClientError def get_client(): return boto3.client('s3') def get_prev_file_name(bucket, file_prefix, bookmark_file, baseline_file): s3_client = get_client() try: bookmark_file = s3_client.get_object( Bucket=bucket, Key=f"{file_prefix}/{bookmark_file}" ) prev_file = bookmark_file['Body'].read().decode('utf-8') except ClientError as e: if e.response['Error']['Code'] == 'NoSuchKey': prev_file = baseline_file else: raise return prev_file def get_next_file_name(file_name): dt_part = file_name.split('.')[0] next_file = f"{dt.strftime(dt.strptime(dt_part, '%Y-%M-%d-%H') + td(hours=1), '%Y-%M-%d-%-H')}.json.gz" return next_file def upload_bookmark(bucket, file_prefix, bookmark_file, bookmark_contents): s3_client = get_client() s3_client.put_object( Bucket=bucket, Key=f'{file_prefix}/{bookmark_file}', Body=bookmark_contents.encode('utf-8') )
import ast from dataclasses import Field, field, MISSING, FrozenInstanceError import inspect class TypedObjectMixin: # pylint: disable=no-method-argument def __new__(*args, **kw): cls, *args = args self = object.__new__(cls) if getattr(cls, '__init__', None) is not cls.__init_fields__: setattr = object.__setattr__ for name, spec in cls.__fields__: if spec.default is not MISSING: setattr(self, name, spec.default) elif spec.default_factory is not MISSING: setattr(self, name, spec.default_factory()) return self def __init_fields__(*args, **kw): self, *args = args setattr = object.__setattr__ it = iter(self.__fields__) src = None if args and isinstance(args[0], type(self)): src, *args = args for arg in args: while True: try: name, field = next(it) except StopIteration: raise TypeError('too many positional arguments') from None if field.init: setattr(self, name, arg) break for name, field in it: if not field.init: continue if name in kw: setattr(self, name, kw.pop(name)) elif src is not None: setattr(self, name, getattr(src, name)) elif field.default is not MISSING: setattr(self, name, field.default) elif field.default_factory is not MISSING: setattr(self, name, field.default_factory()) else: raise TypeError(f'{name}: required argument not provided') if kw: k, _v = kw.popitem() raise TypeError(f'{k}: no such argument') def __getstate__(self): return tuple((name, getattr(self, name)) for name, _ in self.__fields__) def __setstate__(self, state): setattr = object.__setattr__ for name, value in state: setattr(self, name, value) def __repr__(self): params = [f'{name}={getattr(self, name)!r}' for name, spec in self.__fields__ if spec.repr] return f'{type(self).__name__}({', '.join(params)})' def __setattr__(self, name, value): raise FrozenInstanceError(name) def __delattr__(self, name): raise FrozenInstanceError(name) def __hash__(self): return hash(tuple(getattr(self, name) for name, field in self.__fields__ if field.hash)) def __eq__(self, other): if self.__fields__ is not getattr(other, '__fields__', ()): return NotImplemented return all(getattr(self, name) == getattr(other, name) for name, field in self.__fields__ if field.compare) def __ne__(self, other): eq = self == other if eq is NotImplemented: return NotImplemented return not eq def __lt__(self, other): if self.__fields__ is not getattr(other, '__fields__', ()): return NotImplemented return (tuple(getattr(self, name) for name, field in self.__fields__ if field.compare) < tuple(getattr(other, name) for name, field in self.__fields__ if field.compare)) def __gt__(self, other): return other < self def __le__(self, other): n = other < self if n is NotImplemented: return NotImplemented return not n def __ge__(self, other): n = self < other if n is NotImplemented: return NotImplemented return not n class TypedObjectBuilder: def __init__(self, *, init, repr, eq, order, frozen): self._init = init self._repr = repr self._eq = eq self._order = order self._frozen = frozen def __call__(self, *args, init=MISSING, repr=MISSING, eq=MISSING, order=MISSING, frozen=MISSING): if not args: if init is MISSING: init = self._init if repr is MISSING: repr = self._repr if eq is MISSING: eq = self._eq if order is MISSING: order = self._order if frozen is MISSING: frozen = self._frozen return TypedObjectBuilder(init=init, repr=repr, eq=eq, order=order, frozen=frozen) elif len(args) == 1: return self._build_from_template(args[0]) else: return self._build(*args) def _build_from_template(self, template): metacls = type(template) ns = dict(template.__dict__) annots = ns.get('__annotations__', {}) defaults = { k: ns.pop(k) for k in annots if k in ns } fields = {} for k in annots: if k.startswith('__'): raise TypeError(f'{template.__name__}.{k}: field names must not start with a double underscore') if k not in defaults: fields[k] = field() else: v = defaults[k] if isinstance(v, Field): fields[k] = v else: fields[k] = field(default=v) return self._build(template.__name__, fields, template.__bases__, ns, metacls) def _build(self, clsname, fields, bases=(), ns=(), metacls=type): if not issubclass(metacls, type): raise TypeError('typedobject doesn\'t work with classes that are not instances of type') ns = dict(ns) ns.pop('__dict__', None) ns.pop('__weakref__', None) for base in bases: for name, _field in getattr(base, '__fields__', ()): if name in fields: raise TypeError(f'{name}: already defined in {base.__name__}') ns['__slots__'] = tuple(fields) ns['__new__'] = TypedObjectMixin.__new__ ns['__init_fields__'] = TypedObjectMixin.__init_fields__ if self._init and '__init__' not in ns: ns['__init__'] = TypedObjectMixin.__init_fields__ ns['__getstate__'] = TypedObjectMixin.__getstate__ ns['__setstate__'] = TypedObjectMixin.__setstate__ if self._repr: ns['__repr__'] = TypedObjectMixin.__repr__ if self._frozen: ns['__setattr__'] = TypedObjectMixin.__setattr__ ns['__delattr__'] = TypedObjectMixin.__delattr__ if self._eq: if '__hash__' not in ns: ns['__hash__'] = TypedObjectMixin.__hash__ if '__eq__' not in ns: ns['__eq__'] = TypedObjectMixin.__eq__ ns['__ne__'] = TypedObjectMixin.__ne__ if self._order: if '__lt__' not in ns: ns['__lt__'] = TypedObjectMixin.__lt__ ns['__gt__'] = TypedObjectMixin.__gt__ ns['__le__'] = TypedObjectMixin.__le__ ns['__ge__'] = TypedObjectMixin.__ge__ cls = metacls(clsname, bases, ns) all_fields = {} for base in reversed(inspect.getmro(cls)): all_fields.update(getattr(base, '__fields__', ())) for name in ns: fld = all_fields.get(name) if fld is not None: all_fields[name] = field(init=False, compare=fld.compare, repr=fld.repr) all_fields.update(fields) cls.__fields__ = tuple(all_fields.items()) return cls @property def no_init(self): return TypedObjectBuilder(init=False, repr=self._repr, eq=self._eq, order=self._order, frozen=self._frozen) @property def no_repr(self): return TypedObjectBuilder(init=self._init, repr=False, eq=self._eq, order=self._order, frozen=self._frozen) @property def no_eq(self): return TypedObjectBuilder(init=self._init, repr=self._repr, eq=False, order=self._order, frozen=self._frozen) @property def frozen(self): return TypedObjectBuilder(init=self._init, repr=self._repr, eq=self._eq, order=self._order, frozen=True) @property def ordered(self): return TypedObjectBuilder(init=self._init, repr=self._repr, eq=self._eq, order=True, frozen=self._frozen) typedobject = TypedObjectBuilder(init=True, repr=True, eq=True, order=False, frozen=False)
import ast from dataclasses import Field, field, MISSING, FrozenInstanceError import inspect class TypedObjectMixin: # pylint: disable=no-method-argument def __new__(*args, **kw): cls, *args = args self = object.__new__(cls) if getattr(cls, '__init__', None) is not cls.__init_fields__: setattr = object.__setattr__ for name, spec in cls.__fields__: if spec.default is not MISSING: setattr(self, name, spec.default) elif spec.default_factory is not MISSING: setattr(self, name, spec.default_factory()) return self def __init_fields__(*args, **kw): self, *args = args setattr = object.__setattr__ it = iter(self.__fields__) src = None if args and isinstance(args[0], type(self)): src, *args = args for arg in args: while True: try: name, field = next(it) except StopIteration: raise TypeError('too many positional arguments') from None if field.init: setattr(self, name, arg) break for name, field in it: if not field.init: continue if name in kw: setattr(self, name, kw.pop(name)) elif src is not None: setattr(self, name, getattr(src, name)) elif field.default is not MISSING: setattr(self, name, field.default) elif field.default_factory is not MISSING: setattr(self, name, field.default_factory()) else: raise TypeError(f'{name}: required argument not provided') if kw: k, _v = kw.popitem() raise TypeError(f'{k}: no such argument') def __getstate__(self): return tuple((name, getattr(self, name)) for name, _ in self.__fields__) def __setstate__(self, state): setattr = object.__setattr__ for name, value in state: setattr(self, name, value) def __repr__(self): params = [f'{name}={getattr(self, name)!r}' for name, spec in self.__fields__ if spec.repr] return f'{type(self).__name__}({", ".join(params)})' def __setattr__(self, name, value): raise FrozenInstanceError(name) def __delattr__(self, name): raise FrozenInstanceError(name) def __hash__(self): return hash(tuple(getattr(self, name) for name, field in self.__fields__ if field.hash)) def __eq__(self, other): if self.__fields__ is not getattr(other, '__fields__', ()): return NotImplemented return all(getattr(self, name) == getattr(other, name) for name, field in self.__fields__ if field.compare) def __ne__(self, other): eq = self == other if eq is NotImplemented: return NotImplemented return not eq def __lt__(self, other): if self.__fields__ is not getattr(other, '__fields__', ()): return NotImplemented return (tuple(getattr(self, name) for name, field in self.__fields__ if field.compare) < tuple(getattr(other, name) for name, field in self.__fields__ if field.compare)) def __gt__(self, other): return other < self def __le__(self, other): n = other < self if n is NotImplemented: return NotImplemented return not n def __ge__(self, other): n = self < other if n is NotImplemented: return NotImplemented return not n class TypedObjectBuilder: def __init__(self, *, init, repr, eq, order, frozen): self._init = init self._repr = repr self._eq = eq self._order = order self._frozen = frozen def __call__(self, *args, init=MISSING, repr=MISSING, eq=MISSING, order=MISSING, frozen=MISSING): if not args: if init is MISSING: init = self._init if repr is MISSING: repr = self._repr if eq is MISSING: eq = self._eq if order is MISSING: order = self._order if frozen is MISSING: frozen = self._frozen return TypedObjectBuilder(init=init, repr=repr, eq=eq, order=order, frozen=frozen) elif len(args) == 1: return self._build_from_template(args[0]) else: return self._build(*args) def _build_from_template(self, template): metacls = type(template) ns = dict(template.__dict__) annots = ns.get('__annotations__', {}) defaults = { k: ns.pop(k) for k in annots if k in ns } fields = {} for k in annots: if k.startswith('__'): raise TypeError(f'{template.__name__}.{k}: field names must not start with a double underscore') if k not in defaults: fields[k] = field() else: v = defaults[k] if isinstance(v, Field): fields[k] = v else: fields[k] = field(default=v) return self._build(template.__name__, fields, template.__bases__, ns, metacls) def _build(self, clsname, fields, bases=(), ns=(), metacls=type): if not issubclass(metacls, type): raise TypeError('typedobject doesn\'t work with classes that are not instances of type') ns = dict(ns) ns.pop('__dict__', None) ns.pop('__weakref__', None) for base in bases: for name, _field in getattr(base, '__fields__', ()): if name in fields: raise TypeError(f'{name}: already defined in {base.__name__}') ns['__slots__'] = tuple(fields) ns['__new__'] = TypedObjectMixin.__new__ ns['__init_fields__'] = TypedObjectMixin.__init_fields__ if self._init and '__init__' not in ns: ns['__init__'] = TypedObjectMixin.__init_fields__ ns['__getstate__'] = TypedObjectMixin.__getstate__ ns['__setstate__'] = TypedObjectMixin.__setstate__ if self._repr: ns['__repr__'] = TypedObjectMixin.__repr__ if self._frozen: ns['__setattr__'] = TypedObjectMixin.__setattr__ ns['__delattr__'] = TypedObjectMixin.__delattr__ if self._eq: if '__hash__' not in ns: ns['__hash__'] = TypedObjectMixin.__hash__ if '__eq__' not in ns: ns['__eq__'] = TypedObjectMixin.__eq__ ns['__ne__'] = TypedObjectMixin.__ne__ if self._order: if '__lt__' not in ns: ns['__lt__'] = TypedObjectMixin.__lt__ ns['__gt__'] = TypedObjectMixin.__gt__ ns['__le__'] = TypedObjectMixin.__le__ ns['__ge__'] = TypedObjectMixin.__ge__ cls = metacls(clsname, bases, ns) all_fields = {} for base in reversed(inspect.getmro(cls)): all_fields.update(getattr(base, '__fields__', ())) for name in ns: fld = all_fields.get(name) if fld is not None: all_fields[name] = field(init=False, compare=fld.compare, repr=fld.repr) all_fields.update(fields) cls.__fields__ = tuple(all_fields.items()) return cls @property def no_init(self): return TypedObjectBuilder(init=False, repr=self._repr, eq=self._eq, order=self._order, frozen=self._frozen) @property def no_repr(self): return TypedObjectBuilder(init=self._init, repr=False, eq=self._eq, order=self._order, frozen=self._frozen) @property def no_eq(self): return TypedObjectBuilder(init=self._init, repr=self._repr, eq=False, order=self._order, frozen=self._frozen) @property def frozen(self): return TypedObjectBuilder(init=self._init, repr=self._repr, eq=self._eq, order=self._order, frozen=True) @property def ordered(self): return TypedObjectBuilder(init=self._init, repr=self._repr, eq=self._eq, order=True, frozen=self._frozen) typedobject = TypedObjectBuilder(init=True, repr=True, eq=True, order=False, frozen=False)
""" This module contains shared fixtures for web UI tests. """ import json import pytest from selenium.webdriver import Chrome, Firefox CONFIG_PATH = 'tests/config.json' DEFAULT_WAIT_TIME = 10 SUPPORTED_BROWSERS = ['chrome', 'firefox'] @pytest.fixture(scope='session') def config(): # Read the JSON config file and returns it as a parsed dict with open(CONFIG_PATH) as config_file: data = json.load(config_file) return data @pytest.fixture(scope='session') def config_browser(config): # Validate and return the browser choice from the config data if 'browser' not in config: raise Exception('The config file does not contain "browser"') elif config['browser'] not in SUPPORTED_BROWSERS: raise Exception(f'"{config['browser']}" is not a supported browser') return config['browser'] @pytest.fixture(scope='session') def config_wait_time(config): # Validate and return the wait time from the config data return config['wait_time'] if 'wait_time' in config else DEFAULT_WAIT_TIME @pytest.fixture def browser(config_browser, config_wait_time): # Initialize WebDriver if config_browser == 'chrome': driver = Chrome() elif config_browser == 'firefox': driver = Firefox() else: raise Exception(f'"{config_browser}" is not a supported browser') # Wait implicitly for elements to be ready before attempting interactions driver.implicitly_wait(config_wait_time) # Return the driver object at the end of setup yield driver # For cleanup, quit the driver driver.quit()
""" This module contains shared fixtures for web UI tests. """ import json import pytest from selenium.webdriver import Chrome, Firefox CONFIG_PATH = 'tests/config.json' DEFAULT_WAIT_TIME = 10 SUPPORTED_BROWSERS = ['chrome', 'firefox'] @pytest.fixture(scope='session') def config(): # Read the JSON config file and returns it as a parsed dict with open(CONFIG_PATH) as config_file: data = json.load(config_file) return data @pytest.fixture(scope='session') def config_browser(config): # Validate and return the browser choice from the config data if 'browser' not in config: raise Exception('The config file does not contain "browser"') elif config['browser'] not in SUPPORTED_BROWSERS: raise Exception(f'"{config["browser"]}" is not a supported browser') return config['browser'] @pytest.fixture(scope='session') def config_wait_time(config): # Validate and return the wait time from the config data return config['wait_time'] if 'wait_time' in config else DEFAULT_WAIT_TIME @pytest.fixture def browser(config_browser, config_wait_time): # Initialize WebDriver if config_browser == 'chrome': driver = Chrome() elif config_browser == 'firefox': driver = Firefox() else: raise Exception(f'"{config_browser}" is not a supported browser') # Wait implicitly for elements to be ready before attempting interactions driver.implicitly_wait(config_wait_time) # Return the driver object at the end of setup yield driver # For cleanup, quit the driver driver.quit()
"""Test Open Peer Power template helper methods.""" from datetime import datetime import math import random from unittest.mock import patch import pytest import voluptuous as vol from openpeerpower.components import group from openpeerpower.config import async_process_op_core_config from openpeerpower.const import ( ATTR_UNIT_OF_MEASUREMENT, LENGTH_METERS, MASS_GRAMS, PRESSURE_PA, TEMP_CELSIUS, VOLUME_LITERS, ) from openpeerpower.exceptions import TemplateError from openpeerpower.helpers import device_registry as dr, template from openpeerpower.setup import async_setup_component import openpeerpower.util.dt as dt_util from openpeerpower.util.unit_system import UnitSystem from tests.common import MockConfigEntry, mock_device_registry, mock_registry def _set_up_units(opp): """Set up the tests.""" opp.config.units = UnitSystem( "custom", TEMP_CELSIUS, LENGTH_METERS, VOLUME_LITERS, MASS_GRAMS, PRESSURE_PA ) def render_to_info(opp, template_str, variables=None): """Create render info from template.""" tmp = template.Template(template_str, opp) return tmp.async_render_to_info(variables) def extract_entities(opp, template_str, variables=None): """Extract entities from a template.""" info = render_to_info(opp, template_str, variables) return info.entities def assert_result_info(info, result, entities=None, domains=None, all_states=False): """Check result info.""" assert info.result() == result assert info.all_states == all_states assert info.filter("invalid_entity_name.somewhere") == all_states if entities is not None: assert info.entities == frozenset(entities) assert all([info.filter(entity) for entity in entities]) if not all_states: assert not info.filter("invalid_entity_name.somewhere") else: assert not info.entities if domains is not None: assert info.domains == frozenset(domains) assert all([info.filter(domain + ".entity") for domain in domains]) else: assert not hasattr(info, "_domains") def test_template_equality(): """Test template comparison and hashing.""" template_one = template.Template("{{ template_one }}") template_one_1 = template.Template("{{ template_one }}") template_two = template.Template("{{ template_two }}") assert template_one == template_one_1 assert template_one != template_two assert hash(template_one) == hash(template_one_1) assert hash(template_one) != hash(template_two) assert str(template_one_1) == 'Template("{{ template_one }}")' with pytest.raises(TypeError): template.Template(["{{ template_one }}"]) def test_invalid_template(opp): """Invalid template raises error.""" tmpl = template.Template("{{", opp) with pytest.raises(TemplateError): tmpl.ensure_valid() with pytest.raises(TemplateError): tmpl.async_render() info = tmpl.async_render_to_info() with pytest.raises(TemplateError): assert info.result() == "impossible" tmpl = template.Template("{{states(keyword)}}", opp) tmpl.ensure_valid() with pytest.raises(TemplateError): tmpl.async_render() def test_referring_states_by_entity_id(opp): """Test referring states by entity id.""" opp.states.async_set("test.object", "happy") assert ( template.Template("{{ states.test.object.state }}", opp).async_render() == "happy" ) assert ( template.Template('{{ states["test.object"].state }}', opp).async_render() == "happy" ) assert ( template.Template('{{ states("test.object") }}', opp).async_render() == "happy" ) def test_invalid_entity_id(opp): """Test referring states by entity id.""" with pytest.raises(TemplateError): template.Template('{{ states["big.fat..."] }}', opp).async_render() with pytest.raises(TemplateError): template.Template('{{ states.test["big.fat..."] }}', opp).async_render() with pytest.raises(TemplateError): template.Template('{{ states["invalid/domain"] }}', opp).async_render() def test_raise_exception_on_error(opp): """Test raising an exception on error.""" with pytest.raises(TemplateError): template.Template("{{ invalid_syntax").ensure_valid() def test_iterating_all_states(opp): """Test iterating all states.""" tmpl_str = "{% for state in states %}{{ state.state }}{% endfor %}" info = render_to_info(opp, tmpl_str) assert_result_info(info, "", all_states=True) assert info.rate_limit == template.ALL_STATES_RATE_LIMIT opp.states.async_set("test.object", "happy") opp.states.async_set("sensor.temperature", 10) info = render_to_info(opp, tmpl_str) assert_result_info(info, "10happy", entities=[], all_states=True) def test_iterating_all_states_unavailable(opp): """Test iterating all states unavailable.""" opp.states.async_set("test.object", "on") tmpl_str = "{{ states | selectattr('state', 'in', ['unavailable', 'unknown', 'none']) | list | count }}" info = render_to_info(opp, tmpl_str) assert info.all_states is True assert info.rate_limit == template.ALL_STATES_RATE_LIMIT opp.states.async_set("test.object", "unknown") opp.states.async_set("sensor.temperature", 10) info = render_to_info(opp, tmpl_str) assert_result_info(info, 1, entities=[], all_states=True) def test_iterating_domain_states(opp): """Test iterating domain states.""" tmpl_str = "{% for state in states.sensor %}{{ state.state }}{% endfor %}" info = render_to_info(opp, tmpl_str) assert_result_info(info, "", domains=["sensor"]) assert info.rate_limit == template.DOMAIN_STATES_RATE_LIMIT opp.states.async_set("test.object", "happy") opp.states.async_set("sensor.back_door", "open") opp.states.async_set("sensor.temperature", 10) info = render_to_info(opp, tmpl_str) assert_result_info( info, "open10", entities=[], domains=["sensor"], ) def test_float(opp): """Test float.""" opp.states.async_set("sensor.temperature", "12") assert ( template.Template( "{{ float(states.sensor.temperature.state) }}", opp ).async_render() == 12.0 ) assert ( template.Template( "{{ float(states.sensor.temperature.state) > 11 }}", opp ).async_render() is True ) assert ( template.Template("{{ float('forgiving') }}", opp).async_render() == "forgiving" ) def test_rounding_value(opp): """Test rounding value.""" opp.states.async_set("sensor.temperature", 12.78) assert ( template.Template( "{{ states.sensor.temperature.state | round(1) }}", opp ).async_render() == 12.8 ) assert ( template.Template( "{{ states.sensor.temperature.state | multiply(10) | round }}", opp ).async_render() == 128 ) assert ( template.Template( '{{ states.sensor.temperature.state | round(1, "floor") }}', opp ).async_render() == 12.7 ) assert ( template.Template( '{{ states.sensor.temperature.state | round(1, "ceil") }}', opp ).async_render() == 12.8 ) assert ( template.Template( '{{ states.sensor.temperature.state | round(1, "half") }}', opp ).async_render() == 13.0 ) def test_rounding_value_get_original_value_on_error(opp): """Test rounding value get original value on error.""" assert template.Template("{{ None | round }}", opp).async_render() is None assert ( template.Template('{{ "no_number" | round }}', opp).async_render() == "no_number" ) def test_multiply(opp): """Test multiply.""" tests = {None: None, 10: 100, '"abcd"': "abcd"} for inp, out in tests.items(): assert ( template.Template( "{{ %s | multiply(10) | round }}" % inp, opp ).async_render() == out ) def test_logarithm(opp): """Test logarithm.""" tests = [ (4, 2, 2.0), (1000, 10, 3.0), (math.e, "", 1.0), ('"invalid"', "_", "invalid"), (10, '"invalid"', 10.0), ] for value, base, expected in tests: assert ( template.Template( f"{{{{ {value} | log({base}) | round(1) }}}}", opp ).async_render() == expected ) assert ( template.Template( f"{{{{ log({value}, {base}) | round(1) }}}}", opp ).async_render() == expected ) def test_sine(opp): """Test sine.""" tests = [ (0, 0.0), (math.pi / 2, 1.0), (math.pi, 0.0), (math.pi * 1.5, -1.0), (math.pi / 10, 0.309), ('"duck"', "duck"), ] for value, expected in tests: assert ( template.Template("{{ %s | sin | round(3) }}" % value, opp).async_render() == expected ) def test_cos(opp): """Test cosine.""" tests = [ (0, 1.0), (math.pi / 2, 0.0), (math.pi, -1.0), (math.pi * 1.5, -0.0), (math.pi / 10, 0.951), ("'error'", "error"), ] for value, expected in tests: assert ( template.Template("{{ %s | cos | round(3) }}" % value, opp).async_render() == expected ) def test_tan(opp): """Test tangent.""" tests = [ (0, 0.0), (math.pi, -0.0), (math.pi / 180 * 45, 1.0), (math.pi / 180 * 90, "1.633123935319537e+16"), (math.pi / 180 * 135, -1.0), ("'error'", "error"), ] for value, expected in tests: assert ( template.Template("{{ %s | tan | round(3) }}" % value, opp).async_render() == expected ) def test_sqrt(opp): """Test square root.""" tests = [ (0, 0.0), (1, 1.0), (2, 1.414), (10, 3.162), (100, 10.0), ("'error'", "error"), ] for value, expected in tests: assert ( template.Template("{{ %s | sqrt | round(3) }}" % value, opp).async_render() == expected ) def test_arc_sine(opp): """Test arcus sine.""" tests = [ (-2.0, -2.0), # value error (-1.0, -1.571), (-0.5, -0.524), (0.0, 0.0), (0.5, 0.524), (1.0, 1.571), (2.0, 2.0), # value error ('"error"', "error"), ] for value, expected in tests: assert ( template.Template("{{ %s | asin | round(3) }}" % value, opp).async_render() == expected ) def test_arc_cos(opp): """Test arcus cosine.""" tests = [ (-2.0, -2.0), # value error (-1.0, 3.142), (-0.5, 2.094), (0.0, 1.571), (0.5, 1.047), (1.0, 0.0), (2.0, 2.0), # value error ('"error"', "error"), ] for value, expected in tests: assert ( template.Template("{{ %s | acos | round(3) }}" % value, opp).async_render() == expected ) def test_arc_tan(opp): """Test arcus tangent.""" tests = [ (-10.0, -1.471), (-2.0, -1.107), (-1.0, -0.785), (-0.5, -0.464), (0.0, 0.0), (0.5, 0.464), (1.0, 0.785), (2.0, 1.107), (10.0, 1.471), ('"error"', "error"), ] for value, expected in tests: assert ( template.Template("{{ %s | atan | round(3) }}" % value, opp).async_render() == expected ) def test_arc_tan2(opp): """Test two parameter version of arcus tangent.""" tests = [ (-10.0, -10.0, -2.356), (-10.0, 0.0, -1.571), (-10.0, 10.0, -0.785), (0.0, -10.0, 3.142), (0.0, 0.0, 0.0), (0.0, 10.0, 0.0), (10.0, -10.0, 2.356), (10.0, 0.0, 1.571), (10.0, 10.0, 0.785), (-4.0, 3.0, -0.927), (-1.0, 2.0, -0.464), (2.0, 1.0, 1.107), ('"duck"', '"goose"', ("duck", "goose")), ] for y, x, expected in tests: assert ( template.Template( f"{{{{ ({y}, {x}) | atan2 | round(3) }}}}", opp ).async_render() == expected ) assert ( template.Template( f"{{{{ atan2({y}, {x}) | round(3) }}}}", opp ).async_render() == expected ) def test_strptime(opp): """Test the parse timestamp method.""" tests = [ ("2016-10-19 15:22:05.588122 UTC", "%Y-%m-%d %H:%M:%S.%f %Z", None), ("2016-10-19 15:22:05.588122+0100", "%Y-%m-%d %H:%M:%S.%f%z", None), ("2016-10-19 15:22:05.588122", "%Y-%m-%d %H:%M:%S.%f", None), ("2016-10-19", "%Y-%m-%d", None), ("2016", "%Y", None), ("15:22:05", "%H:%M:%S", None), ("1469119144", "%Y", 1469119144), ("invalid", "%Y", "invalid"), ] for inp, fmt, expected in tests: if expected is None: expected = str(datetime.strptime(inp, fmt)) temp = f"{{{{ strptime("{inp}", "{fmt}') }}}}" assert template.Template(temp, opp).async_render() == expected def test_timestamp_custom(opp): """Test the timestamps to custom filter.""" now = dt_util.utcnow() tests = [ (None, None, None, None), (1469119144, None, True, "2016-07-21 16:39:04"), (1469119144, "%Y", True, 2016), (1469119144, "invalid", True, "invalid"), (dt_util.as_timestamp(now), None, False, now.strftime("%Y-%m-%d %H:%M:%S")), ] for inp, fmt, local, out in tests: if fmt: fil = f"timestamp_custom('{fmt}')" elif fmt and local: fil = f"timestamp_custom('{fmt}', {local})" else: fil = "timestamp_custom" assert template.Template(f"{{{{ {inp} | {fil} }}}}", opp).async_render() == out def test_timestamp_local(opp): """Test the timestamps to local filter.""" tests = {None: None, 1469119144: "2016-07-21 16:39:04"} for inp, out in tests.items(): assert ( template.Template("{{ %s | timestamp_local }}" % inp, opp).async_render() == out ) def test_as_local(opp): """Test converting time to local.""" opp.states.async_set("test.object", "available") last_updated = opp.states.get("test.object").last_updated assert template.Template( "{{ as_local(states.test.object.last_updated) }}", opp ).async_render() == str(dt_util.as_local(last_updated)) assert template.Template( "{{ states.test.object.last_updated | as_local }}", opp ).async_render() == str(dt_util.as_local(last_updated)) def test_to_json(opp): """Test the object to JSON string filter.""" # Note that we're not testing the actual json.loads and json.dumps methods, # only the filters, so we don't need to be exhaustive with our sample JSON. expected_result = {"Foo": "Bar"} actual_result = template.Template( "{{ {'Foo': 'Bar'} | to_json }}", opp ).async_render() assert actual_result == expected_result def test_from_json(opp): """Test the JSON string to object filter.""" # Note that we're not testing the actual json.loads and json.dumps methods, # only the filters, so we don't need to be exhaustive with our sample JSON. expected_result = "Bar" actual_result = template.Template( '{{ (\'{"Foo": "Bar"}\' | from_json).Foo }}', opp ).async_render() assert actual_result == expected_result def test_min(opp): """Test the min filter.""" assert template.Template("{{ [1, 2, 3] | min }}", opp).async_render() == 1 assert template.Template("{{ min([1, 2, 3]) }}", opp).async_render() == 1 assert template.Template("{{ min(1, 2, 3) }}", opp).async_render() == 1 def test_max(opp): """Test the max filter.""" assert template.Template("{{ [1, 2, 3] | max }}", opp).async_render() == 3 assert template.Template("{{ max([1, 2, 3]) }}", opp).async_render() == 3 assert template.Template("{{ max(1, 2, 3) }}", opp).async_render() == 3 def test_ord(opp): """Test the ord filter.""" assert template.Template('{{ "d" | ord }}', opp).async_render() == 100 def test_base64_encode(opp): """Test the base64_encode filter.""" assert ( template.Template('{{ "openpeerpower" | base64_encode }}', opp).async_render() == "b3BlbnBlZXJwb3dlcg==" ) def test_base64_decode(opp): """Test the base64_decode filter.""" assert ( template.Template( '{{ "b3BlbnBlZXJwb3dlcg==" | base64_decode }}', opp ).async_render() == "openpeerpower" ) def test_ordinal(opp): """Test the ordinal filter.""" tests = [ (1, "1st"), (2, "2nd"), (3, "3rd"), (4, "4th"), (5, "5th"), (12, "12th"), (100, "100th"), (101, "101st"), ] for value, expected in tests: assert ( template.Template("{{ %s | ordinal }}" % value, opp).async_render() == expected ) def test_timestamp_utc(opp): """Test the timestamps to local filter.""" now = dt_util.utcnow() tests = { None: None, 1469119144: "2016-07-21 16:39:04", dt_util.as_timestamp(now): now.strftime("%Y-%m-%d %H:%M:%S"), } for inp, out in tests.items(): assert ( template.Template("{{ %s | timestamp_utc }}" % inp, opp).async_render() == out ) def test_as_timestamp(opp): """Test the as_timestamp function.""" assert ( template.Template('{{ as_timestamp("invalid") }}', opp).async_render() is None ) opp.mock = None assert ( template.Template("{{ as_timestamp(states.mock) }}", opp).async_render() is None ) tpl = ( '{{ as_timestamp(strptime("2024-02-03T09:10:24+0000", ' '"%Y-%m-%dT%H:%M:%S%z")) }}' ) assert template.Template(tpl, opp).async_render() == 1706951424.0 @patch.object(random, "choice") def test_random_every_time(test_choice, opp): """Ensure the random filter runs every time, not just once.""" tpl = template.Template("{{ [1,2] | random }}", opp) test_choice.return_value = "foo" assert tpl.async_render() == "foo" test_choice.return_value = "bar" assert tpl.async_render() == "bar" def test_passing_vars_as_keywords(opp): """Test passing variables as keywords.""" assert template.Template("{{ hello }}", opp).async_render(hello=127) == 127 def test_passing_vars_as_vars(opp): """Test passing variables as variables.""" assert template.Template("{{ hello }}", opp).async_render({"hello": 127}) == 127 def test_passing_vars_as_list(opp): """Test passing variables as list.""" assert template.render_complex( template.Template("{{ hello }}", opp), {"hello": ["foo", "bar"]} ) == ["foo", "bar"] def test_passing_vars_as_list_element(opp): """Test passing variables as list.""" assert ( template.render_complex( template.Template("{{ hello[1] }}", opp), {"hello": ["foo", "bar"]} ) == "bar" ) def test_passing_vars_as_dict_element(opp): """Test passing variables as list.""" assert ( template.render_complex( template.Template("{{ hello.foo }}", opp), {"hello": {"foo": "bar"}} ) == "bar" ) def test_passing_vars_as_dict(opp): """Test passing variables as list.""" assert template.render_complex( template.Template("{{ hello }}", opp), {"hello": {"foo": "bar"}} ) == {"foo": "bar"} def test_render_with_possible_json_value_with_valid_json(opp): """Render with possible JSON value with valid JSON.""" tpl = template.Template("{{ value_json.hello }}", opp) assert tpl.async_render_with_possible_json_value('{"hello": "world"}') == "world" def test_render_with_possible_json_value_with_invalid_json(opp): """Render with possible JSON value with invalid JSON.""" tpl = template.Template("{{ value_json }}", opp) assert tpl.async_render_with_possible_json_value("{ I AM NOT JSON }") == "" def test_render_with_possible_json_value_with_template_error_value(opp): """Render with possible JSON value with template error value.""" tpl = template.Template("{{ non_existing.variable }}", opp) assert tpl.async_render_with_possible_json_value("hello", "-") == "-" def test_render_with_possible_json_value_with_missing_json_value(opp): """Render with possible JSON value with unknown JSON object.""" tpl = template.Template("{{ value_json.goodbye }}", opp) assert tpl.async_render_with_possible_json_value('{"hello": "world"}') == "" def test_render_with_possible_json_value_valid_with_is_defined(opp): """Render with possible JSON value with known JSON object.""" tpl = template.Template("{{ value_json.hello|is_defined }}", opp) assert tpl.async_render_with_possible_json_value('{"hello": "world"}') == "world" def test_render_with_possible_json_value_undefined_json(opp): """Render with possible JSON value with unknown JSON object.""" tpl = template.Template("{{ value_json.bye|is_defined }}", opp) assert ( tpl.async_render_with_possible_json_value('{"hello": "world"}') == '{"hello": "world"}' ) def test_render_with_possible_json_value_undefined_json_error_value(opp): """Render with possible JSON value with unknown JSON object.""" tpl = template.Template("{{ value_json.bye|is_defined }}", opp) assert tpl.async_render_with_possible_json_value('{"hello": "world"}', "") == "" def test_render_with_possible_json_value_non_string_value(opp): """Render with possible JSON value with non-string value.""" tpl = template.Template( """ {{ strptime(value~'+0000', '%Y-%m-%d %H:%M:%S%z') }} """, opp, ) value = datetime(2019, 1, 18, 12, 13, 14) expected = str(value.replace(tzinfo=dt_util.UTC)) assert tpl.async_render_with_possible_json_value(value) == expected def test_if_state_exists(opp): """Test if state exists works.""" opp.states.async_set("test.object", "available") tpl = template.Template( "{% if states.test.object %}exists{% else %}not exists{% endif %}", opp ) assert tpl.async_render() == "exists" def test_is_state(opp): """Test is_state method.""" opp.states.async_set("test.object", "available") tpl = template.Template( """ {% if is_state("test.object", "available") %}yes{% else %}no{% endif %} """, opp, ) assert tpl.async_render() == "yes" tpl = template.Template( """ {{ is_state("test.noobject", "available") }} """, opp, ) assert tpl.async_render() is False def test_is_state_attr(opp): """Test is_state_attr method.""" opp.states.async_set("test.object", "available", {"mode": "on"}) tpl = template.Template( """ {% if is_state_attr("test.object", "mode", "on") %}yes{% else %}no{% endif %} """, opp, ) assert tpl.async_render() == "yes" tpl = template.Template( """ {{ is_state_attr("test.noobject", "mode", "on") }} """, opp, ) assert tpl.async_render() is False def test_state_attr(opp): """Test state_attr method.""" opp.states.async_set("test.object", "available", {"mode": "on"}) tpl = template.Template( """ {% if state_attr("test.object", "mode") == "on" %}yes{% else %}no{% endif %} """, opp, ) assert tpl.async_render() == "yes" tpl = template.Template( """ {{ state_attr("test.noobject", "mode") == None }} """, opp, ) assert tpl.async_render() is True def test_states_function(opp): """Test using states as a function.""" opp.states.async_set("test.object", "available") tpl = template.Template('{{ states("test.object") }}', opp) assert tpl.async_render() == "available" tpl2 = template.Template('{{ states("test.object2") }}', opp) assert tpl2.async_render() == "unknown" @patch( "openpeerpower.helpers.template.TemplateEnvironment.is_safe_callable", return_value=True, ) def test_now(mock_is_safe, opp): """Test now method.""" now = dt_util.now() with patch("openpeerpower.util.dt.now", return_value=now): info = template.Template("{{ now().isoformat() }}", opp).async_render_to_info() assert now.isoformat() == info.result() assert info.has_time is True @patch( "openpeerpower.helpers.template.TemplateEnvironment.is_safe_callable", return_value=True, ) def test_utcnow(mock_is_safe, opp): """Test now method.""" utcnow = dt_util.utcnow() with patch("openpeerpower.util.dt.utcnow", return_value=utcnow): info = template.Template( "{{ utcnow().isoformat() }}", opp ).async_render_to_info() assert utcnow.isoformat() == info.result() assert info.has_time is True @patch( "openpeerpower.helpers.template.TemplateEnvironment.is_safe_callable", return_value=True, ) def test_relative_time(mock_is_safe, opp): """Test relative_time method.""" now = datetime.strptime("2000-01-01 10:00:00 +00:00", "%Y-%m-%d %H:%M:%S %z") with patch("openpeerpower.util.dt.now", return_value=now): result = template.Template( '{{relative_time(strptime("2000-01-01 09:00:00", "%Y-%m-%d %H:%M:%S"))}}', opp, ).async_render() assert result == "1 hour" result = template.Template( '{{relative_time(strptime("2000-01-01 09:00:00 +01:00", "%Y-%m-%d %H:%M:%S %z"))}}', opp, ).async_render() assert result == "2 hours" result = template.Template( '{{relative_time(strptime("2000-01-01 03:00:00 -06:00", "%Y-%m-%d %H:%M:%S %z"))}}', opp, ).async_render() assert result == "1 hour" result1 = str( template.strptime("2000-01-01 11:00:00 +00:00", "%Y-%m-%d %H:%M:%S %z") ) result2 = template.Template( '{{relative_time(strptime("2000-01-01 11:00:00 +00:00", "%Y-%m-%d %H:%M:%S %z"))}}', opp, ).async_render() assert result1 == result2 result = template.Template( '{{relative_time("string")}}', opp, ).async_render() assert result == "string" @patch( "openpeerpower.helpers.template.TemplateEnvironment.is_safe_callable", return_value=True, ) def test_timedelta(mock_is_safe, opp): """Test relative_time method.""" now = datetime.strptime("2000-01-01 10:00:00 +00:00", "%Y-%m-%d %H:%M:%S %z") with patch("openpeerpower.util.dt.now", return_value=now): result = template.Template( "{{timedelta(seconds=120)}}", opp, ).async_render() assert result == "0:02:00" result = template.Template( "{{timedelta(seconds=86400)}}", opp, ).async_render() assert result == "1 day, 0:00:00" result = template.Template("{{timedelta(days=1, hours=4)}}", opp).async_render() assert result == "1 day, 4:00:00" result = template.Template( "{{relative_time(now() - timedelta(seconds=3600))}}", opp, ).async_render() assert result == "1 hour" result = template.Template( "{{relative_time(now() - timedelta(seconds=86400))}}", opp, ).async_render() assert result == "1 day" result = template.Template( "{{relative_time(now() - timedelta(seconds=86401))}}", opp, ).async_render() assert result == "1 day" result = template.Template( "{{relative_time(now() - timedelta(weeks=2, days=1))}}", opp, ).async_render() assert result == "15 days" def test_regex_match(opp): """Test regex_match method.""" tpl = template.Template( r""" {{ '123-456-7890' | regex_match('(\\d{3})-(\\d{3})-(\\d{4})') }} """, opp, ) assert tpl.async_render() is True tpl = template.Template( """ {{ 'Open Peer Power test' | regex_match('Open', True) }} """, opp, ) assert tpl.async_render() is True tpl = template.Template( """ {{ 'Another Open Peer Power test' | regex_match('Open') }} """, opp, ) assert tpl.async_render() is False tpl = template.Template( """ {{ ['Open Peer Power test'] | regex_match('.*Peer') }} """, opp, ) assert tpl.async_render() is True def test_match_test(opp): """Test match test.""" tpl = template.Template( r""" {{ '123-456-7890' is match('(\\d{3})-(\\d{3})-(\\d{4})') }} """, opp, ) assert tpl.async_render() is True def test_regex_search(opp): """Test regex_search method.""" tpl = template.Template( r""" {{ '123-456-7890' | regex_search('(\\d{3})-(\\d{3})-(\\d{4})') }} """, opp, ) assert tpl.async_render() is True tpl = template.Template( """ {{ 'Open Peer Power test' | regex_search('Open', True) }} """, opp, ) assert tpl.async_render() is True tpl = template.Template( """ {{ 'Another Open Peer Power test' | regex_search('Open') }} """, opp, ) assert tpl.async_render() is True tpl = template.Template( """ {{ ['Open Peer Power test'] | regex_search('Peer') }} """, opp, ) assert tpl.async_render() is True def test_search_test(opp): """Test search test.""" tpl = template.Template( r""" {{ '123-456-7890' is search('(\\d{3})-(\\d{3})-(\\d{4})') }} """, opp, ) assert tpl.async_render() is True def test_regex_replace(opp): """Test regex_replace method.""" tpl = template.Template( r""" {{ 'Hello World' | regex_replace('(Hello\\s)',) }} """, opp, ) assert tpl.async_render() == "World" tpl = template.Template( """ {{ ['Open Peer ponderant test'] | regex_replace('ponderant', 'Power') }} """, opp, ) assert tpl.async_render() == ["Open Peer Power test"] def test_regex_findall_index(opp): """Test regex_findall_index method.""" tpl = template.Template( """ {{ 'Flight from JFK to LHR' | regex_findall_index('([A-Z]{3})', 0) }} """, opp, ) assert tpl.async_render() == "JFK" tpl = template.Template( """ {{ 'Flight from JFK to LHR' | regex_findall_index('([A-Z]{3})', 1) }} """, opp, ) assert tpl.async_render() == "LHR" tpl = template.Template( """ {{ ['JFK', 'LHR'] | regex_findall_index('([A-Z]{3})', 1) }} """, opp, ) assert tpl.async_render() == "LHR" def test_bitwise_and(opp): """Test bitwise_and method.""" tpl = template.Template( """ {{ 8 | bitwise_and(8) }} """, opp, ) assert tpl.async_render() == 8 & 8 tpl = template.Template( """ {{ 10 | bitwise_and(2) }} """, opp, ) assert tpl.async_render() == 10 & 2 tpl = template.Template( """ {{ 8 | bitwise_and(2) }} """, opp, ) assert tpl.async_render() == 8 & 2 def test_bitwise_or(opp): """Test bitwise_or method.""" tpl = template.Template( """ {{ 8 | bitwise_or(8) }} """, opp, ) assert tpl.async_render() == 8 | 8 tpl = template.Template( """ {{ 10 | bitwise_or(2) }} """, opp, ) assert tpl.async_render() == 10 | 2 tpl = template.Template( """ {{ 8 | bitwise_or(2) }} """, opp, ) assert tpl.async_render() == 8 | 2 def test_distance_function_with_1_state(opp): """Test distance function with 1 state.""" _set_up_units(opp) opp.states.async_set( "test.object", "happy", {"latitude": 32.87336, "longitude": -117.22943} ) tpl = template.Template("{{ distance(states.test.object) | round }}", opp) assert tpl.async_render() == 187 def test_distance_function_with_2_states(opp): """Test distance function with 2 states.""" _set_up_units(opp) opp.states.async_set( "test.object", "happy", {"latitude": 32.87336, "longitude": -117.22943} ) opp.states.async_set( "test.object_2", "happy", {"latitude": opp.config.latitude, "longitude": opp.config.longitude}, ) tpl = template.Template( "{{ distance(states.test.object, states.test.object_2) | round }}", opp ) assert tpl.async_render() == 187 def test_distance_function_with_1_coord(opp): """Test distance function with 1 coord.""" _set_up_units(opp) tpl = template.Template('{{ distance("32.87336", "-117.22943") | round }}', opp) assert tpl.async_render() == 187 def test_distance_function_with_2_coords(opp): """Test distance function with 2 coords.""" _set_up_units(opp) assert ( template.Template( '{{ distance("32.87336", "-117.22943", %s, %s) | round }}' % (opp.config.latitude, opp.config.longitude), opp, ).async_render() == 187 ) def test_distance_function_with_1_state_1_coord(opp): """Test distance function with 1 state 1 coord.""" _set_up_units(opp) opp.states.async_set( "test.object_2", "happy", {"latitude": opp.config.latitude, "longitude": opp.config.longitude}, ) tpl = template.Template( '{{ distance("32.87336", "-117.22943", states.test.object_2) ' "| round }}", opp, ) assert tpl.async_render() == 187 tpl2 = template.Template( '{{ distance(states.test.object_2, "32.87336", "-117.22943") ' "| round }}", opp, ) assert tpl2.async_render() == 187 def test_distance_function_return_none_if_invalid_state(opp): """Test distance function return None if invalid state.""" opp.states.async_set("test.object_2", "happy", {"latitude": 10}) tpl = template.Template("{{ distance(states.test.object_2) | round }}", opp) assert tpl.async_render() is None def test_distance_function_return_none_if_invalid_coord(opp): """Test distance function return None if invalid coord.""" assert template.Template('{{ distance("123", "abc") }}', opp).async_render() is None assert template.Template('{{ distance("123") }}', opp).async_render() is None opp.states.async_set( "test.object_2", "happy", {"latitude": opp.config.latitude, "longitude": opp.config.longitude}, ) tpl = template.Template('{{ distance("123", states.test_object_2) }}', opp) assert tpl.async_render() is None def test_distance_function_with_2_entity_ids(opp): """Test distance function with 2 entity ids.""" _set_up_units(opp) opp.states.async_set( "test.object", "happy", {"latitude": 32.87336, "longitude": -117.22943} ) opp.states.async_set( "test.object_2", "happy", {"latitude": opp.config.latitude, "longitude": opp.config.longitude}, ) tpl = template.Template( '{{ distance("test.object", "test.object_2") | round }}', opp ) assert tpl.async_render() == 187 def test_distance_function_with_1_entity_1_coord(opp): """Test distance function with 1 entity_id and 1 coord.""" _set_up_units(opp) opp.states.async_set( "test.object", "happy", {"latitude": opp.config.latitude, "longitude": opp.config.longitude}, ) tpl = template.Template( '{{ distance("test.object", "32.87336", "-117.22943") | round }}', opp ) assert tpl.async_render() == 187 def test_closest_function_home_vs_domain(opp): """Test closest function home vs domain.""" opp.states.async_set( "test_domain.object", "happy", { "latitude": opp.config.latitude + 0.1, "longitude": opp.config.longitude + 0.1, }, ) opp.states.async_set( "not_test_domain.but_closer", "happy", {"latitude": opp.config.latitude, "longitude": opp.config.longitude}, ) assert ( template.Template( "{{ closest(states.test_domain).entity_id }}", opp ).async_render() == "test_domain.object" ) assert ( template.Template( "{{ (states.test_domain | closest).entity_id }}", opp ).async_render() == "test_domain.object" ) def test_closest_function_home_vs_all_states(opp): """Test closest function home vs all states.""" opp.states.async_set( "test_domain.object", "happy", { "latitude": opp.config.latitude + 0.1, "longitude": opp.config.longitude + 0.1, }, ) opp.states.async_set( "test_domain_2.and_closer", "happy", {"latitude": opp.config.latitude, "longitude": opp.config.longitude}, ) assert ( template.Template("{{ closest(states).entity_id }}", opp).async_render() == "test_domain_2.and_closer" ) assert ( template.Template("{{ (states | closest).entity_id }}", opp).async_render() == "test_domain_2.and_closer" ) async def test_closest_function_home_vs_group_entity_id(opp): """Test closest function home vs group entity id.""" opp.states.async_set( "test_domain.object", "happy", { "latitude": opp.config.latitude + 0.1, "longitude": opp.config.longitude + 0.1, }, ) opp.states.async_set( "not_in_group.but_closer", "happy", {"latitude": opp.config.latitude, "longitude": opp.config.longitude}, ) assert await async_setup_component(opp, "group", {}) await opp.async_block_till_done() await group.Group.async_create_group(opp, "location group", ["test_domain.object"]) info = render_to_info(opp, '{{ closest("group.location_group").entity_id }}') assert_result_info( info, "test_domain.object", {"group.location_group", "test_domain.object"} ) assert info.rate_limit is None async def test_closest_function_home_vs_group_state(opp): """Test closest function home vs group state.""" opp.states.async_set( "test_domain.object", "happy", { "latitude": opp.config.latitude + 0.1, "longitude": opp.config.longitude + 0.1, }, ) opp.states.async_set( "not_in_group.but_closer", "happy", {"latitude": opp.config.latitude, "longitude": opp.config.longitude}, ) assert await async_setup_component(opp, "group", {}) await opp.async_block_till_done() await group.Group.async_create_group(opp, "location group", ["test_domain.object"]) info = render_to_info(opp, '{{ closest("group.location_group").entity_id }}') assert_result_info( info, "test_domain.object", {"group.location_group", "test_domain.object"} ) assert info.rate_limit is None info = render_to_info(opp, "{{ closest(states.group.location_group).entity_id }}") assert_result_info( info, "test_domain.object", {"test_domain.object", "group.location_group"} ) assert info.rate_limit is None async def test_expand(opp): """Test expand function.""" info = render_to_info(opp, "{{ expand('test.object') }}") assert_result_info(info, [], ["test.object"]) assert info.rate_limit is None info = render_to_info(opp, "{{ expand(56) }}") assert_result_info(info, []) assert info.rate_limit is None opp.states.async_set("test.object", "happy") info = render_to_info( opp, "{{ expand('test.object') | map(attribute='entity_id') | join(', ') }}" ) assert_result_info(info, "test.object", ["test.object"]) assert info.rate_limit is None info = render_to_info( opp, "{{ expand('group.new_group') | map(attribute='entity_id') | join(', ') }}", ) assert_result_info(info, "", ["group.new_group"]) assert info.rate_limit is None info = render_to_info( opp, "{{ expand(states.group) | map(attribute='entity_id') | join(', ') }}" ) assert_result_info(info, "", [], ["group"]) assert info.rate_limit == template.DOMAIN_STATES_RATE_LIMIT assert await async_setup_component(opp, "group", {}) await opp.async_block_till_done() await group.Group.async_create_group(opp, "new group", ["test.object"]) info = render_to_info( opp, "{{ expand('group.new_group') | map(attribute='entity_id') | join(', ') }}", ) assert_result_info(info, "test.object", {"group.new_group", "test.object"}) assert info.rate_limit is None info = render_to_info( opp, "{{ expand(states.group) | map(attribute='entity_id') | join(', ') }}" ) assert_result_info(info, "test.object", {"test.object"}, ["group"]) assert info.rate_limit == template.DOMAIN_STATES_RATE_LIMIT info = render_to_info( opp, "{{ expand('group.new_group', 'test.object')" " | map(attribute='entity_id') | join(', ') }}", ) assert_result_info(info, "test.object", {"test.object", "group.new_group"}) info = render_to_info( opp, "{{ ['group.new_group', 'test.object'] | expand" " | map(attribute='entity_id') | join(', ') }}", ) assert_result_info(info, "test.object", {"test.object", "group.new_group"}) assert info.rate_limit is None opp.states.async_set("sensor.power_1", 0) opp.states.async_set("sensor.power_2", 200.2) opp.states.async_set("sensor.power_3", 400.4) assert await async_setup_component(opp, "group", {}) await opp.async_block_till_done() await group.Group.async_create_group( opp, "power sensors", ["sensor.power_1", "sensor.power_2", "sensor.power_3"] ) info = render_to_info( opp, "{{ states.group.power_sensors.attributes.entity_id | expand | map(attribute='state')|map('float')|sum }}", ) assert_result_info( info, 200.2 + 400.4, {"group.power_sensors", "sensor.power_1", "sensor.power_2", "sensor.power_3"}, ) assert info.rate_limit is None async def test_device_entities(opp): """Test expand function.""" config_entry = MockConfigEntry(domain="light") device_registry = mock_device_registry(opp) entity_registry = mock_registry(opp) # Test non existing device ids info = render_to_info(opp, "{{ device_entities('abc123') }}") assert_result_info(info, []) assert info.rate_limit is None info = render_to_info(opp, "{{ device_entities(56) }}") assert_result_info(info, []) assert info.rate_limit is None # Test device without entities device_entry = device_registry.async_get_or_create( config_entry_id=config_entry.entry_id, connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, ) info = render_to_info(opp, f"{{{{ device_entities("{device_entry.id}") }}}}") assert_result_info(info, []) assert info.rate_limit is None # Test device with single entity, which has no state entity_registry.async_get_or_create( "light", "hue", "5678", config_entry=config_entry, device_id=device_entry.id, ) info = render_to_info(opp, f"{{{{ device_entities("{device_entry.id}") }}}}") assert_result_info(info, ["light.hue_5678"], []) assert info.rate_limit is None info = render_to_info( opp, f"{{{{ device_entities("{device_entry.id}") | expand | map(attribute="entity_id") | join(", ") }}}}", ) assert_result_info(info, "", ["light.hue_5678"]) assert info.rate_limit is None # Test device with single entity, with state opp.states.async_set("light.hue_5678", "happy") info = render_to_info( opp, f"{{{{ device_entities("{device_entry.id}") | expand | map(attribute="entity_id") | join(", ") }}}}", ) assert_result_info(info, "light.hue_5678", ["light.hue_5678"]) assert info.rate_limit is None # Test device with multiple entities, which have a state entity_registry.async_get_or_create( "light", "hue", "ABCD", config_entry=config_entry, device_id=device_entry.id, ) opp.states.async_set("light.hue_abcd", "camper") info = render_to_info(opp, f"{{{{ device_entities("{device_entry.id}") }}}}") assert_result_info(info, ["light.hue_5678", "light.hue_abcd"], []) assert info.rate_limit is None info = render_to_info( opp, f"{{{{ device_entities("{device_entry.id}") | expand | map(attribute="entity_id") | join(", ") }}}}", ) assert_result_info( info, "light.hue_5678, light.hue_abcd", ["light.hue_5678", "light.hue_abcd"] ) assert info.rate_limit is None def test_closest_function_to_coord(opp): """Test closest function to coord.""" opp.states.async_set( "test_domain.closest_home", "happy", { "latitude": opp.config.latitude + 0.1, "longitude": opp.config.longitude + 0.1, }, ) opp.states.async_set( "test_domain.closest_zone", "happy", { "latitude": opp.config.latitude + 0.2, "longitude": opp.config.longitude + 0.2, }, ) opp.states.async_set( "zone.far_away", "zoning", { "latitude": opp.config.latitude + 0.3, "longitude": opp.config.longitude + 0.3, }, ) tpl = template.Template( '{{ closest("%s", %s, states.test_domain).entity_id }}' % (opp.config.latitude + 0.3, opp.config.longitude + 0.3), opp, ) assert tpl.async_render() == "test_domain.closest_zone" tpl = template.Template( '{{ (states.test_domain | closest("%s", %s)).entity_id }}' % (opp.config.latitude + 0.3, opp.config.longitude + 0.3), opp, ) assert tpl.async_render() == "test_domain.closest_zone" def test_async_render_to_info_with_branching(opp): """Test async_render_to_info function by domain.""" opp.states.async_set("light.a", "off") opp.states.async_set("light.b", "on") opp.states.async_set("light.c", "off") info = render_to_info( opp, """ {% if states.light.a == "on" %} {{ states.light.b.state }} {% else %} {{ states.light.c.state }} {% endif %} """, ) assert_result_info(info, "off", {"light.a", "light.c"}) assert info.rate_limit is None info = render_to_info( opp, """ {% if states.light.a.state == "off" %} {% set domain = "light" %} {{ states[domain].b.state }} {% endif %} """, ) assert_result_info(info, "on", {"light.a", "light.b"}) assert info.rate_limit is None def test_async_render_to_info_with_complex_branching(opp): """Test async_render_to_info function by domain.""" opp.states.async_set("light.a", "off") opp.states.async_set("light.b", "on") opp.states.async_set("light.c", "off") opp.states.async_set("vacuum.a", "off") opp.states.async_set("device_tracker.a", "off") opp.states.async_set("device_tracker.b", "off") opp.states.async_set("lock.a", "off") opp.states.async_set("sensor.a", "off") opp.states.async_set("binary_sensor.a", "off") info = render_to_info( opp, """ {% set domain = "vacuum" %} {% if states.light.a == "on" %} {{ states.light.b.state }} {% elif states.light.a == "on" %} {{ states.device_tracker }} {% elif states.light.a == "on" %} {{ states[domain] | list }} {% elif states('light.b') == "on" %} {{ states[otherdomain] | map(attribute='entity_id') | list }} {% elif states.light.a == "on" %} {{ states["nonexist"] | list }} {% else %} else {% endif %} """, {"otherdomain": "sensor"}, ) assert_result_info(info, ["sensor.a"], {"light.a", "light.b"}, {"sensor"}) assert info.rate_limit == template.DOMAIN_STATES_RATE_LIMIT async def test_async_render_to_info_with_wildcard_matching_entity_id(opp): """Test tracking template with a wildcard.""" template_complex_str = r""" {% for state in states.cover %} {% if state.entity_id | regex_match('.*\.office_') %} {{ state.entity_id }}={{ state.state }} {% endif %} {% endfor %} """ opp.states.async_set("cover.office_drapes", "closed") opp.states.async_set("cover.office_window", "closed") opp.states.async_set("cover.office_skylight", "open") info = render_to_info(opp, template_complex_str) assert info.domains == {"cover"} assert info.entities == set() assert info.all_states is False assert info.rate_limit == template.DOMAIN_STATES_RATE_LIMIT async def test_async_render_to_info_with_wildcard_matching_state(opp): """Test tracking template with a wildcard.""" template_complex_str = """ {% for state in states %} {% if state.state | regex_match('ope.*') %} {{ state.entity_id }}={{ state.state }} {% endif %} {% endfor %} """ opp.states.async_set("cover.office_drapes", "closed") opp.states.async_set("cover.office_window", "closed") opp.states.async_set("cover.office_skylight", "open") opp.states.async_set("cover.x_skylight", "open") opp.states.async_set("binary_sensor.door", "open") await opp.async_block_till_done() info = render_to_info(opp, template_complex_str) assert not info.domains assert info.entities == set() assert info.all_states is True assert info.rate_limit == template.ALL_STATES_RATE_LIMIT opp.states.async_set("binary_sensor.door", "closed") info = render_to_info(opp, template_complex_str) assert not info.domains assert info.entities == set() assert info.all_states is True assert info.rate_limit == template.ALL_STATES_RATE_LIMIT template_cover_str = """ {% for state in states.cover %} {% if state.state | regex_match('ope.*') %} {{ state.entity_id }}={{ state.state }} {% endif %} {% endfor %} """ opp.states.async_set("cover.x_skylight", "closed") info = render_to_info(opp, template_cover_str) assert info.domains == {"cover"} assert info.entities == set() assert info.all_states is False assert info.rate_limit == template.DOMAIN_STATES_RATE_LIMIT def test_nested_async_render_to_info_case(opp): """Test a deeply nested state with async_render_to_info.""" opp.states.async_set("input_select.picker", "vacuum.a") opp.states.async_set("vacuum.a", "off") info = render_to_info( opp, "{{ states[states['input_select.picker'].state].state }}", {} ) assert_result_info(info, "off", {"input_select.picker", "vacuum.a"}) assert info.rate_limit is None def test_result_as_boolean(opp): """Test converting a template result to a boolean.""" assert template.result_as_boolean(True) is True assert template.result_as_boolean(" 1 ") is True assert template.result_as_boolean(" true ") is True assert template.result_as_boolean(" TrUE ") is True assert template.result_as_boolean(" YeS ") is True assert template.result_as_boolean(" On ") is True assert template.result_as_boolean(" Enable ") is True assert template.result_as_boolean(1) is True assert template.result_as_boolean(-1) is True assert template.result_as_boolean(500) is True assert template.result_as_boolean(0.5) is True assert template.result_as_boolean(0.389) is True assert template.result_as_boolean(35) is True assert template.result_as_boolean(False) is False assert template.result_as_boolean(" 0 ") is False assert template.result_as_boolean(" false ") is False assert template.result_as_boolean(" FaLsE ") is False assert template.result_as_boolean(" no ") is False assert template.result_as_boolean(" off ") is False assert template.result_as_boolean(" disable ") is False assert template.result_as_boolean(0) is False assert template.result_as_boolean(0.0) is False assert template.result_as_boolean("0.00") is False assert template.result_as_boolean(None) is False def test_closest_function_to_entity_id(opp): """Test closest function to entity id.""" opp.states.async_set( "test_domain.closest_home", "happy", { "latitude": opp.config.latitude + 0.1, "longitude": opp.config.longitude + 0.1, }, ) opp.states.async_set( "test_domain.closest_zone", "happy", { "latitude": opp.config.latitude + 0.2, "longitude": opp.config.longitude + 0.2, }, ) opp.states.async_set( "zone.far_away", "zoning", { "latitude": opp.config.latitude + 0.3, "longitude": opp.config.longitude + 0.3, }, ) info = render_to_info( opp, "{{ closest(zone, states.test_domain).entity_id }}", {"zone": "zone.far_away"}, ) assert_result_info( info, "test_domain.closest_zone", ["test_domain.closest_home", "test_domain.closest_zone", "zone.far_away"], ["test_domain"], ) info = render_to_info( opp, "{{ ([states.test_domain, 'test_domain.closest_zone'] " "| closest(zone)).entity_id }}", {"zone": "zone.far_away"}, ) assert_result_info( info, "test_domain.closest_zone", ["test_domain.closest_home", "test_domain.closest_zone", "zone.far_away"], ["test_domain"], ) def test_closest_function_to_state(opp): """Test closest function to state.""" opp.states.async_set( "test_domain.closest_home", "happy", { "latitude": opp.config.latitude + 0.1, "longitude": opp.config.longitude + 0.1, }, ) opp.states.async_set( "test_domain.closest_zone", "happy", { "latitude": opp.config.latitude + 0.2, "longitude": opp.config.longitude + 0.2, }, ) opp.states.async_set( "zone.far_away", "zoning", { "latitude": opp.config.latitude + 0.3, "longitude": opp.config.longitude + 0.3, }, ) assert ( template.Template( "{{ closest(states.zone.far_away, states.test_domain).entity_id }}", opp ).async_render() == "test_domain.closest_zone" ) def test_closest_function_invalid_state(opp): """Test closest function invalid state.""" opp.states.async_set( "test_domain.closest_home", "happy", { "latitude": opp.config.latitude + 0.1, "longitude": opp.config.longitude + 0.1, }, ) for state in ("states.zone.non_existing", '"zone.non_existing"'): assert ( template.Template("{{ closest(%s, states) }}" % state, opp).async_render() is None ) def test_closest_function_state_with_invalid_location(opp): """Test closest function state with invalid location.""" opp.states.async_set( "test_domain.closest_home", "happy", {"latitude": "invalid latitude", "longitude": opp.config.longitude + 0.1}, ) assert ( template.Template( "{{ closest(states.test_domain.closest_home, states) }}", opp ).async_render() is None ) def test_closest_function_invalid_coordinates(opp): """Test closest function invalid coordinates.""" opp.states.async_set( "test_domain.closest_home", "happy", { "latitude": opp.config.latitude + 0.1, "longitude": opp.config.longitude + 0.1, }, ) assert ( template.Template( '{{ closest("invalid", "coord", states) }}', opp ).async_render() is None ) assert ( template.Template( '{{ states | closest("invalid", "coord") }}', opp ).async_render() is None ) def test_closest_function_no_location_states(opp): """Test closest function without location states.""" assert ( template.Template("{{ closest(states).entity_id }}", opp).async_render() == "" ) def test_generate_filter_iterators(opp): """Test extract entities function with none entities stuff.""" info = render_to_info( opp, """ {% for state in states %} {{ state.entity_id }} {% endfor %} """, ) assert_result_info(info, "", all_states=True) info = render_to_info( opp, """ {% for state in states.sensor %} {{ state.entity_id }} {% endfor %} """, ) assert_result_info(info, "", domains=["sensor"]) opp.states.async_set("sensor.test_sensor", "off", {"attr": "value"}) # Don't need the entity because the state is not accessed info = render_to_info( opp, """ {% for state in states.sensor %} {{ state.entity_id }} {% endfor %} """, ) assert_result_info(info, "sensor.test_sensor", domains=["sensor"]) # But we do here because the state gets accessed info = render_to_info( opp, """ {% for state in states.sensor %} {{ state.entity_id }}={{ state.state }}, {% endfor %} """, ) assert_result_info(info, "sensor.test_sensor=off,", [], ["sensor"]) info = render_to_info( opp, """ {% for state in states.sensor %} {{ state.entity_id }}={{ state.attributes.attr }}, {% endfor %} """, ) assert_result_info(info, "sensor.test_sensor=value,", [], ["sensor"]) def test_generate_select(opp): """Test extract entities function with none entities stuff.""" template_str = """ {{ states.sensor|selectattr("state","equalto","off") |join(",", attribute="entity_id") }} """ tmp = template.Template(template_str, opp) info = tmp.async_render_to_info() assert_result_info(info, "", [], []) assert info.domains_lifecycle == {"sensor"} opp.states.async_set("sensor.test_sensor", "off", {"attr": "value"}) opp.states.async_set("sensor.test_sensor_on", "on") info = tmp.async_render_to_info() assert_result_info( info, "sensor.test_sensor", [], ["sensor"], ) assert info.domains_lifecycle == {"sensor"} async def test_async_render_to_info_in_conditional(opp): """Test extract entities function with none entities stuff.""" template_str = """ {{ states("sensor.xyz") == "dog" }} """ tmp = template.Template(template_str, opp) info = tmp.async_render_to_info() assert_result_info(info, False, ["sensor.xyz"], []) opp.states.async_set("sensor.xyz", "dog") opp.states.async_set("sensor.cow", "True") await opp.async_block_till_done() template_str = """ {% if states("sensor.xyz") == "dog" %} {{ states("sensor.cow") }} {% else %} {{ states("sensor.pig") }} {% endif %} """ tmp = template.Template(template_str, opp) info = tmp.async_render_to_info() assert_result_info(info, True, ["sensor.xyz", "sensor.cow"], []) opp.states.async_set("sensor.xyz", "sheep") opp.states.async_set("sensor.pig", "oink") await opp.async_block_till_done() tmp = template.Template(template_str, opp) info = tmp.async_render_to_info() assert_result_info(info, "oink", ["sensor.xyz", "sensor.pig"], []) def test_jinja_namespace(opp): """Test Jinja's namespace command can be used.""" test_template = template.Template( ( "{% set ns = namespace(a_key='') %}" "{% set ns.a_key = states.sensor.dummy.state %}" "{{ ns.a_key }}" ), opp, ) opp.states.async_set("sensor.dummy", "a value") assert test_template.async_render() == "a value" opp.states.async_set("sensor.dummy", "another value") assert test_template.async_render() == "another value" def test_state_with_unit(opp): """Test the state_with_unit property helper.""" opp.states.async_set("sensor.test", "23", {ATTR_UNIT_OF_MEASUREMENT: "beers"}) opp.states.async_set("sensor.test2", "wow") tpl = template.Template("{{ states.sensor.test.state_with_unit }}", opp) assert tpl.async_render() == "23 beers" tpl = template.Template("{{ states.sensor.test2.state_with_unit }}", opp) assert tpl.async_render() == "wow" tpl = template.Template( "{% for state in states %}{{ state.state_with_unit }} {% endfor %}", opp ) assert tpl.async_render() == "23 beers wow" tpl = template.Template("{{ states.sensor.non_existing.state_with_unit }}", opp) assert tpl.async_render() == "" def test_length_of_states(opp): """Test fetching the length of states.""" opp.states.async_set("sensor.test", "23") opp.states.async_set("sensor.test2", "wow") opp.states.async_set("climate.test2", "cooling") tpl = template.Template("{{ states | length }}", opp) assert tpl.async_render() == 3 tpl = template.Template("{{ states.sensor | length }}", opp) assert tpl.async_render() == 2 def test_render_complex_handling_non_template_values(opp): """Test that we can render non-template fields.""" assert template.render_complex( {True: 1, False: template.Template("{{ hello }}", opp)}, {"hello": 2} ) == {True: 1, False: 2} def test_urlencode(opp): """Test the urlencode method.""" tpl = template.Template( ("{% set dict = {'foo': 'x&y', 'bar': 42} %}" "{{ dict | urlencode }}"), opp, ) assert tpl.async_render() == "foo=x%26y&bar=42" tpl = template.Template( ("{% set string = 'the quick brown fox = true' %}" "{{ string | urlencode }}"), opp, ) assert tpl.async_render() == "the%20quick%20brown%20fox%20%3D%20true" async def test_cache_garbage_collection(): """Test caching a template.""" template_string = ( "{% set dict = {'foo': 'x&y', 'bar': 42} %} {{ dict | urlencode }}" ) tpl = template.Template( (template_string), ) tpl.ensure_valid() assert template._NO_OPP_ENV.template_cache.get( template_string ) # pylint: disable=protected-access tpl2 = template.Template( (template_string), ) tpl2.ensure_valid() assert template._NO_OPP_ENV.template_cache.get( template_string ) # pylint: disable=protected-access del tpl assert template._NO_OPP_ENV.template_cache.get( template_string ) # pylint: disable=protected-access del tpl2 assert not template._NO_OPP_ENV.template_cache.get( template_string ) # pylint: disable=protected-access def test_is_template_string(): """Test is template string.""" assert template.is_template_string("{{ x }}") is True assert template.is_template_string("{% if x == 2 %}1{% else %}0{%end if %}") is True assert template.is_template_string("{# a comment #} Hey") is True assert template.is_template_string("1") is False assert template.is_template_string("Some Text") is False async def test_protected_blocked(opp): """Test accessing __getattr__ produces a template error.""" tmp = template.Template('{{ states.__getattr__("any") }}', opp) with pytest.raises(TemplateError): tmp.async_render() tmp = template.Template('{{ states.sensor.__getattr__("any") }}', opp) with pytest.raises(TemplateError): tmp.async_render() tmp = template.Template('{{ states.sensor.any.__getattr__("any") }}', opp) with pytest.raises(TemplateError): tmp.async_render() async def test_demo_template(opp): """Test the demo template works as expected.""" opp.states.async_set("sun.sun", "above", {"elevation": 50, "next_rising": "later"}) for i in range(2): opp.states.async_set(f"sensor.sensor{i}", "on") demo_template_str = """ {## Imitate available variables: ##} {% set my_test_json = { "temperature": 25, "unit": "°C" } %} The temperature is {{ my_test_json.temperature }} {{ my_test_json.unit }}. {% if is_state("sun.sun", "above_horizon") -%} The sun rose {{ relative_time(states.sun.sun.last_changed) }} ago. {%- else -%} The sun will rise at {{ as_timestamp(strptime(state_attr("sun.sun", "next_rising"), "")) | timestamp_local }}. {%- endif %} For loop example getting 3 entity values: {% for states in states | slice(3) -%} {% set state = states | first %} {%- if loop.first %}The {% elif loop.last %} and the {% else %}, the {% endif -%} {{ state.name | lower }} is {{state.state_with_unit}} {%- endfor %}. """ tmp = template.Template(demo_template_str, opp) result = tmp.async_render() assert "The temperature is 25" in result assert "is on" in result assert "sensor0" in result assert "sensor1" in result assert "sun" in result async def test_slice_states(opp): """Test iterating states with a slice.""" opp.states.async_set("sensor.test", "23") tpl = template.Template( "{% for states in states | slice(1) -%}{% set state = states | first %}{{ state.entity_id }}{%- endfor %}", opp, ) assert tpl.async_render() == "sensor.test" async def test_lifecycle(opp): """Test that we limit template render info for lifecycle events.""" opp.states.async_set("sun.sun", "above", {"elevation": 50, "next_rising": "later"}) for i in range(2): opp.states.async_set(f"sensor.sensor{i}", "on") opp.states.async_set("sensor.removed", "off") await opp.async_block_till_done() opp.states.async_set("sun.sun", "below", {"elevation": 60, "next_rising": "later"}) for i in range(2): opp.states.async_set(f"sensor.sensor{i}", "off") opp.states.async_set("sensor.new", "off") opp.states.async_remove("sensor.removed") await opp.async_block_till_done() tmp = template.Template("{{ states | count }}", opp) info = tmp.async_render_to_info() assert info.all_states is False assert info.all_states_lifecycle is True assert info.rate_limit is None assert info.has_time is False assert info.entities == set() assert info.domains == set() assert info.domains_lifecycle == set() assert info.filter("sun.sun") is False assert info.filter("sensor.sensor1") is False assert info.filter_lifecycle("sensor.new") is True assert info.filter_lifecycle("sensor.removed") is True async def test_template_timeout(opp): """Test to see if a template will timeout.""" for i in range(2): opp.states.async_set(f"sensor.sensor{i}", "on") tmp = template.Template("{{ states | count }}", opp) assert await tmp.async_render_will_timeout(3) is False tmp3 = template.Template("static", opp) assert await tmp3.async_render_will_timeout(3) is False tmp4 = template.Template("{{ var1 }}", opp) assert await tmp4.async_render_will_timeout(3, {"var1": "ok"}) is False slow_template_str = """ {% for var in range(1000) -%} {% for var in range(1000) -%} {{ var }} {%- endfor %} {%- endfor %} """ tmp5 = template.Template(slow_template_str, opp) assert await tmp5.async_render_will_timeout(0.000001) is True async def test_template_timeout_raise(opp): """Test we can raise from.""" tmp2 = template.Template("{{ error_invalid + 1 }}", opp) with pytest.raises(TemplateError): assert await tmp2.async_render_will_timeout(3) is False async def test_lights(opp): """Test we can sort lights.""" tmpl = """ {% set lights_on = states.light|selectattr('state','eq','on')|map(attribute='name')|list %} {% if lights_on|length == 0 %} No lights on. Sleep well.. {% elif lights_on|length == 1 %} The {{lights_on[0]}} light is on. {% elif lights_on|length == 2 %} The {{lights_on[0]}} and {{lights_on[1]}} lights are on. {% else %} The {{lights_on[:-1]|join(', ')}}, and {{lights_on[-1]}} lights are on. {% endif %} """ states = [] for i in range(10): states.append(f"light.sensor{i}") opp.states.async_set(f"light.sensor{i}", "on") tmp = template.Template(tmpl, opp) info = tmp.async_render_to_info() assert info.entities == set() assert info.domains == {"light"} assert "lights are on" in info.result() for i in range(10): assert f"sensor{i}" in info.result() async def test_template_errors(opp): """Test template rendering wraps exceptions with TemplateError.""" with pytest.raises(TemplateError): template.Template("{{ now() | rando }}", opp).async_render() with pytest.raises(TemplateError): template.Template("{{ utcnow() | rando }}", opp).async_render() with pytest.raises(TemplateError): template.Template("{{ now() | random }}", opp).async_render() with pytest.raises(TemplateError): template.Template("{{ utcnow() | random }}", opp).async_render() async def test_state_attributes(opp): """Test state attributes.""" opp.states.async_set("sensor.test", "23") tpl = template.Template( "{{ states.sensor.test.last_changed }}", opp, ) assert tpl.async_render() == str(opp.states.get("sensor.test").last_changed) tpl = template.Template( "{{ states.sensor.test.object_id }}", opp, ) assert tpl.async_render() == opp.states.get("sensor.test").object_id tpl = template.Template( "{{ states.sensor.test.domain }}", opp, ) assert tpl.async_render() == opp.states.get("sensor.test").domain tpl = template.Template( "{{ states.sensor.test.context.id }}", opp, ) assert tpl.async_render() == opp.states.get("sensor.test").context.id tpl = template.Template( "{{ states.sensor.test.state_with_unit }}", opp, ) assert tpl.async_render() == 23 tpl = template.Template( "{{ states.sensor.test.invalid_prop }}", opp, ) assert tpl.async_render() == "" tpl = template.Template( "{{ states.sensor.test.invalid_prop.xx }}", opp, ) with pytest.raises(TemplateError): tpl.async_render() async def test_unavailable_states(opp): """Test watching unavailable states.""" for i in range(10): opp.states.async_set(f"light.sensor{i}", "on") opp.states.async_set("light.unavailable", "unavailable") opp.states.async_set("light.unknown", "unknown") opp.states.async_set("light.none", "none") tpl = template.Template( "{{ states | selectattr('state', 'in', ['unavailable','unknown','none']) | map(attribute='entity_id') | list | join(', ') }}", opp, ) assert tpl.async_render() == "light.none, light.unavailable, light.unknown" tpl = template.Template( "{{ states.light | selectattr('state', 'in', ['unavailable','unknown','none']) | map(attribute='entity_id') | list | join(', ') }}", opp, ) assert tpl.async_render() == "light.none, light.unavailable, light.unknown" async def test_legacy_templates(opp): """Test if old template behavior works when legacy templates are enabled.""" opp.states.async_set("sensor.temperature", "12") assert ( template.Template("{{ states.sensor.temperature.state }}", opp).async_render() == 12 ) await async_process_op_core_config(opp, {"legacy_templates": True}) assert ( template.Template("{{ states.sensor.temperature.state }}", opp).async_render() == "12" ) async def test_no_result_parsing(opp): """Test if templates results are not parsed.""" opp.states.async_set("sensor.temperature", "12") assert ( template.Template("{{ states.sensor.temperature.state }}", opp).async_render( parse_result=False ) == "12" ) assert ( template.Template("{{ false }}", opp).async_render(parse_result=False) == "False" ) assert ( template.Template("{{ [1, 2, 3] }}", opp).async_render(parse_result=False) == "[1, 2, 3]" ) async def test_is_static_still_ast_evals(opp): """Test is_static still convers to native type.""" tpl = template.Template("[1, 2]", opp) assert tpl.is_static assert tpl.async_render() == [1, 2] async def test_result_wrappers(opp): """Test result wrappers.""" for text, native, orig_type, schema in ( ("[1, 2]", [1, 2], list, vol.Schema([int])), ("{1, 2}", {1, 2}, set, vol.Schema({int})), ("(1, 2)", (1, 2), tuple, vol.ExactSequence([int, int])), ('{"hello": True}', {"hello": True}, dict, vol.Schema({"hello": bool})), ): tpl = template.Template(text, opp) result = tpl.async_render() assert isinstance(result, orig_type) assert isinstance(result, template.ResultWrapper) assert result == native assert result.render_result == text schema(result) # should not raise # Result with render text stringifies to original text assert str(result) == text # Result without render text stringifies same as original type assert str(template.RESULT_WRAPPERS[orig_type](native)) == str( orig_type(native) ) async def test_parse_result(opp): """Test parse result.""" for tpl, result in ( ('{{ "{{}}" }}', "{{}}"), ("not-something", "not-something"), ("2a", "2a"), ("123E5", "123E5"), ("1j", "1j"), ("1e+100", "1e+100"), ("0xface", "0xface"), ("123", 123), ("10", 10), ("123.0", 123.0), (".5", 0.5), ("0.5", 0.5), ("-1", -1), ("-1.0", -1.0), ("+1", 1), ("5.", 5.0), ("123_123_123", "123_123_123"), # ("+48100200300", "+48100200300"), # phone number ("010", "010"), ("0011101.00100001010001", "0011101.00100001010001"), ): assert template.Template(tpl, opp).async_render() == result async def test_undefined_variable(opp, caplog): """Test a warning is logged on undefined variables.""" tpl = template.Template("{{ no_such_variable }}", opp) assert tpl.async_render() == "" assert ( "Template variable warning: 'no_such_variable' is undefined when rendering '{{ no_such_variable }}'" in caplog.text )
"""Test Open Peer Power template helper methods.""" from datetime import datetime import math import random from unittest.mock import patch import pytest import voluptuous as vol from openpeerpower.components import group from openpeerpower.config import async_process_op_core_config from openpeerpower.const import ( ATTR_UNIT_OF_MEASUREMENT, LENGTH_METERS, MASS_GRAMS, PRESSURE_PA, TEMP_CELSIUS, VOLUME_LITERS, ) from openpeerpower.exceptions import TemplateError from openpeerpower.helpers import device_registry as dr, template from openpeerpower.setup import async_setup_component import openpeerpower.util.dt as dt_util from openpeerpower.util.unit_system import UnitSystem from tests.common import MockConfigEntry, mock_device_registry, mock_registry def _set_up_units(opp): """Set up the tests.""" opp.config.units = UnitSystem( "custom", TEMP_CELSIUS, LENGTH_METERS, VOLUME_LITERS, MASS_GRAMS, PRESSURE_PA ) def render_to_info(opp, template_str, variables=None): """Create render info from template.""" tmp = template.Template(template_str, opp) return tmp.async_render_to_info(variables) def extract_entities(opp, template_str, variables=None): """Extract entities from a template.""" info = render_to_info(opp, template_str, variables) return info.entities def assert_result_info(info, result, entities=None, domains=None, all_states=False): """Check result info.""" assert info.result() == result assert info.all_states == all_states assert info.filter("invalid_entity_name.somewhere") == all_states if entities is not None: assert info.entities == frozenset(entities) assert all([info.filter(entity) for entity in entities]) if not all_states: assert not info.filter("invalid_entity_name.somewhere") else: assert not info.entities if domains is not None: assert info.domains == frozenset(domains) assert all([info.filter(domain + ".entity") for domain in domains]) else: assert not hasattr(info, "_domains") def test_template_equality(): """Test template comparison and hashing.""" template_one = template.Template("{{ template_one }}") template_one_1 = template.Template("{{ template_one }}") template_two = template.Template("{{ template_two }}") assert template_one == template_one_1 assert template_one != template_two assert hash(template_one) == hash(template_one_1) assert hash(template_one) != hash(template_two) assert str(template_one_1) == 'Template("{{ template_one }}")' with pytest.raises(TypeError): template.Template(["{{ template_one }}"]) def test_invalid_template(opp): """Invalid template raises error.""" tmpl = template.Template("{{", opp) with pytest.raises(TemplateError): tmpl.ensure_valid() with pytest.raises(TemplateError): tmpl.async_render() info = tmpl.async_render_to_info() with pytest.raises(TemplateError): assert info.result() == "impossible" tmpl = template.Template("{{states(keyword)}}", opp) tmpl.ensure_valid() with pytest.raises(TemplateError): tmpl.async_render() def test_referring_states_by_entity_id(opp): """Test referring states by entity id.""" opp.states.async_set("test.object", "happy") assert ( template.Template("{{ states.test.object.state }}", opp).async_render() == "happy" ) assert ( template.Template('{{ states["test.object"].state }}', opp).async_render() == "happy" ) assert ( template.Template('{{ states("test.object") }}', opp).async_render() == "happy" ) def test_invalid_entity_id(opp): """Test referring states by entity id.""" with pytest.raises(TemplateError): template.Template('{{ states["big.fat..."] }}', opp).async_render() with pytest.raises(TemplateError): template.Template('{{ states.test["big.fat..."] }}', opp).async_render() with pytest.raises(TemplateError): template.Template('{{ states["invalid/domain"] }}', opp).async_render() def test_raise_exception_on_error(opp): """Test raising an exception on error.""" with pytest.raises(TemplateError): template.Template("{{ invalid_syntax").ensure_valid() def test_iterating_all_states(opp): """Test iterating all states.""" tmpl_str = "{% for state in states %}{{ state.state }}{% endfor %}" info = render_to_info(opp, tmpl_str) assert_result_info(info, "", all_states=True) assert info.rate_limit == template.ALL_STATES_RATE_LIMIT opp.states.async_set("test.object", "happy") opp.states.async_set("sensor.temperature", 10) info = render_to_info(opp, tmpl_str) assert_result_info(info, "10happy", entities=[], all_states=True) def test_iterating_all_states_unavailable(opp): """Test iterating all states unavailable.""" opp.states.async_set("test.object", "on") tmpl_str = "{{ states | selectattr('state', 'in', ['unavailable', 'unknown', 'none']) | list | count }}" info = render_to_info(opp, tmpl_str) assert info.all_states is True assert info.rate_limit == template.ALL_STATES_RATE_LIMIT opp.states.async_set("test.object", "unknown") opp.states.async_set("sensor.temperature", 10) info = render_to_info(opp, tmpl_str) assert_result_info(info, 1, entities=[], all_states=True) def test_iterating_domain_states(opp): """Test iterating domain states.""" tmpl_str = "{% for state in states.sensor %}{{ state.state }}{% endfor %}" info = render_to_info(opp, tmpl_str) assert_result_info(info, "", domains=["sensor"]) assert info.rate_limit == template.DOMAIN_STATES_RATE_LIMIT opp.states.async_set("test.object", "happy") opp.states.async_set("sensor.back_door", "open") opp.states.async_set("sensor.temperature", 10) info = render_to_info(opp, tmpl_str) assert_result_info( info, "open10", entities=[], domains=["sensor"], ) def test_float(opp): """Test float.""" opp.states.async_set("sensor.temperature", "12") assert ( template.Template( "{{ float(states.sensor.temperature.state) }}", opp ).async_render() == 12.0 ) assert ( template.Template( "{{ float(states.sensor.temperature.state) > 11 }}", opp ).async_render() is True ) assert ( template.Template("{{ float('forgiving') }}", opp).async_render() == "forgiving" ) def test_rounding_value(opp): """Test rounding value.""" opp.states.async_set("sensor.temperature", 12.78) assert ( template.Template( "{{ states.sensor.temperature.state | round(1) }}", opp ).async_render() == 12.8 ) assert ( template.Template( "{{ states.sensor.temperature.state | multiply(10) | round }}", opp ).async_render() == 128 ) assert ( template.Template( '{{ states.sensor.temperature.state | round(1, "floor") }}', opp ).async_render() == 12.7 ) assert ( template.Template( '{{ states.sensor.temperature.state | round(1, "ceil") }}', opp ).async_render() == 12.8 ) assert ( template.Template( '{{ states.sensor.temperature.state | round(1, "half") }}', opp ).async_render() == 13.0 ) def test_rounding_value_get_original_value_on_error(opp): """Test rounding value get original value on error.""" assert template.Template("{{ None | round }}", opp).async_render() is None assert ( template.Template('{{ "no_number" | round }}', opp).async_render() == "no_number" ) def test_multiply(opp): """Test multiply.""" tests = {None: None, 10: 100, '"abcd"': "abcd"} for inp, out in tests.items(): assert ( template.Template( "{{ %s | multiply(10) | round }}" % inp, opp ).async_render() == out ) def test_logarithm(opp): """Test logarithm.""" tests = [ (4, 2, 2.0), (1000, 10, 3.0), (math.e, "", 1.0), ('"invalid"', "_", "invalid"), (10, '"invalid"', 10.0), ] for value, base, expected in tests: assert ( template.Template( f"{{{{ {value} | log({base}) | round(1) }}}}", opp ).async_render() == expected ) assert ( template.Template( f"{{{{ log({value}, {base}) | round(1) }}}}", opp ).async_render() == expected ) def test_sine(opp): """Test sine.""" tests = [ (0, 0.0), (math.pi / 2, 1.0), (math.pi, 0.0), (math.pi * 1.5, -1.0), (math.pi / 10, 0.309), ('"duck"', "duck"), ] for value, expected in tests: assert ( template.Template("{{ %s | sin | round(3) }}" % value, opp).async_render() == expected ) def test_cos(opp): """Test cosine.""" tests = [ (0, 1.0), (math.pi / 2, 0.0), (math.pi, -1.0), (math.pi * 1.5, -0.0), (math.pi / 10, 0.951), ("'error'", "error"), ] for value, expected in tests: assert ( template.Template("{{ %s | cos | round(3) }}" % value, opp).async_render() == expected ) def test_tan(opp): """Test tangent.""" tests = [ (0, 0.0), (math.pi, -0.0), (math.pi / 180 * 45, 1.0), (math.pi / 180 * 90, "1.633123935319537e+16"), (math.pi / 180 * 135, -1.0), ("'error'", "error"), ] for value, expected in tests: assert ( template.Template("{{ %s | tan | round(3) }}" % value, opp).async_render() == expected ) def test_sqrt(opp): """Test square root.""" tests = [ (0, 0.0), (1, 1.0), (2, 1.414), (10, 3.162), (100, 10.0), ("'error'", "error"), ] for value, expected in tests: assert ( template.Template("{{ %s | sqrt | round(3) }}" % value, opp).async_render() == expected ) def test_arc_sine(opp): """Test arcus sine.""" tests = [ (-2.0, -2.0), # value error (-1.0, -1.571), (-0.5, -0.524), (0.0, 0.0), (0.5, 0.524), (1.0, 1.571), (2.0, 2.0), # value error ('"error"', "error"), ] for value, expected in tests: assert ( template.Template("{{ %s | asin | round(3) }}" % value, opp).async_render() == expected ) def test_arc_cos(opp): """Test arcus cosine.""" tests = [ (-2.0, -2.0), # value error (-1.0, 3.142), (-0.5, 2.094), (0.0, 1.571), (0.5, 1.047), (1.0, 0.0), (2.0, 2.0), # value error ('"error"', "error"), ] for value, expected in tests: assert ( template.Template("{{ %s | acos | round(3) }}" % value, opp).async_render() == expected ) def test_arc_tan(opp): """Test arcus tangent.""" tests = [ (-10.0, -1.471), (-2.0, -1.107), (-1.0, -0.785), (-0.5, -0.464), (0.0, 0.0), (0.5, 0.464), (1.0, 0.785), (2.0, 1.107), (10.0, 1.471), ('"error"', "error"), ] for value, expected in tests: assert ( template.Template("{{ %s | atan | round(3) }}" % value, opp).async_render() == expected ) def test_arc_tan2(opp): """Test two parameter version of arcus tangent.""" tests = [ (-10.0, -10.0, -2.356), (-10.0, 0.0, -1.571), (-10.0, 10.0, -0.785), (0.0, -10.0, 3.142), (0.0, 0.0, 0.0), (0.0, 10.0, 0.0), (10.0, -10.0, 2.356), (10.0, 0.0, 1.571), (10.0, 10.0, 0.785), (-4.0, 3.0, -0.927), (-1.0, 2.0, -0.464), (2.0, 1.0, 1.107), ('"duck"', '"goose"', ("duck", "goose")), ] for y, x, expected in tests: assert ( template.Template( f"{{{{ ({y}, {x}) | atan2 | round(3) }}}}", opp ).async_render() == expected ) assert ( template.Template( f"{{{{ atan2({y}, {x}) | round(3) }}}}", opp ).async_render() == expected ) def test_strptime(opp): """Test the parse timestamp method.""" tests = [ ("2016-10-19 15:22:05.588122 UTC", "%Y-%m-%d %H:%M:%S.%f %Z", None), ("2016-10-19 15:22:05.588122+0100", "%Y-%m-%d %H:%M:%S.%f%z", None), ("2016-10-19 15:22:05.588122", "%Y-%m-%d %H:%M:%S.%f", None), ("2016-10-19", "%Y-%m-%d", None), ("2016", "%Y", None), ("15:22:05", "%H:%M:%S", None), ("1469119144", "%Y", 1469119144), ("invalid", "%Y", "invalid"), ] for inp, fmt, expected in tests: if expected is None: expected = str(datetime.strptime(inp, fmt)) temp = f"{{{{ strptime('{inp}', '{fmt}') }}}}" assert template.Template(temp, opp).async_render() == expected def test_timestamp_custom(opp): """Test the timestamps to custom filter.""" now = dt_util.utcnow() tests = [ (None, None, None, None), (1469119144, None, True, "2016-07-21 16:39:04"), (1469119144, "%Y", True, 2016), (1469119144, "invalid", True, "invalid"), (dt_util.as_timestamp(now), None, False, now.strftime("%Y-%m-%d %H:%M:%S")), ] for inp, fmt, local, out in tests: if fmt: fil = f"timestamp_custom('{fmt}')" elif fmt and local: fil = f"timestamp_custom('{fmt}', {local})" else: fil = "timestamp_custom" assert template.Template(f"{{{{ {inp} | {fil} }}}}", opp).async_render() == out def test_timestamp_local(opp): """Test the timestamps to local filter.""" tests = {None: None, 1469119144: "2016-07-21 16:39:04"} for inp, out in tests.items(): assert ( template.Template("{{ %s | timestamp_local }}" % inp, opp).async_render() == out ) def test_as_local(opp): """Test converting time to local.""" opp.states.async_set("test.object", "available") last_updated = opp.states.get("test.object").last_updated assert template.Template( "{{ as_local(states.test.object.last_updated) }}", opp ).async_render() == str(dt_util.as_local(last_updated)) assert template.Template( "{{ states.test.object.last_updated | as_local }}", opp ).async_render() == str(dt_util.as_local(last_updated)) def test_to_json(opp): """Test the object to JSON string filter.""" # Note that we're not testing the actual json.loads and json.dumps methods, # only the filters, so we don't need to be exhaustive with our sample JSON. expected_result = {"Foo": "Bar"} actual_result = template.Template( "{{ {'Foo': 'Bar'} | to_json }}", opp ).async_render() assert actual_result == expected_result def test_from_json(opp): """Test the JSON string to object filter.""" # Note that we're not testing the actual json.loads and json.dumps methods, # only the filters, so we don't need to be exhaustive with our sample JSON. expected_result = "Bar" actual_result = template.Template( '{{ (\'{"Foo": "Bar"}\' | from_json).Foo }}', opp ).async_render() assert actual_result == expected_result def test_min(opp): """Test the min filter.""" assert template.Template("{{ [1, 2, 3] | min }}", opp).async_render() == 1 assert template.Template("{{ min([1, 2, 3]) }}", opp).async_render() == 1 assert template.Template("{{ min(1, 2, 3) }}", opp).async_render() == 1 def test_max(opp): """Test the max filter.""" assert template.Template("{{ [1, 2, 3] | max }}", opp).async_render() == 3 assert template.Template("{{ max([1, 2, 3]) }}", opp).async_render() == 3 assert template.Template("{{ max(1, 2, 3) }}", opp).async_render() == 3 def test_ord(opp): """Test the ord filter.""" assert template.Template('{{ "d" | ord }}', opp).async_render() == 100 def test_base64_encode(opp): """Test the base64_encode filter.""" assert ( template.Template('{{ "openpeerpower" | base64_encode }}', opp).async_render() == "b3BlbnBlZXJwb3dlcg==" ) def test_base64_decode(opp): """Test the base64_decode filter.""" assert ( template.Template( '{{ "b3BlbnBlZXJwb3dlcg==" | base64_decode }}', opp ).async_render() == "openpeerpower" ) def test_ordinal(opp): """Test the ordinal filter.""" tests = [ (1, "1st"), (2, "2nd"), (3, "3rd"), (4, "4th"), (5, "5th"), (12, "12th"), (100, "100th"), (101, "101st"), ] for value, expected in tests: assert ( template.Template("{{ %s | ordinal }}" % value, opp).async_render() == expected ) def test_timestamp_utc(opp): """Test the timestamps to local filter.""" now = dt_util.utcnow() tests = { None: None, 1469119144: "2016-07-21 16:39:04", dt_util.as_timestamp(now): now.strftime("%Y-%m-%d %H:%M:%S"), } for inp, out in tests.items(): assert ( template.Template("{{ %s | timestamp_utc }}" % inp, opp).async_render() == out ) def test_as_timestamp(opp): """Test the as_timestamp function.""" assert ( template.Template('{{ as_timestamp("invalid") }}', opp).async_render() is None ) opp.mock = None assert ( template.Template("{{ as_timestamp(states.mock) }}", opp).async_render() is None ) tpl = ( '{{ as_timestamp(strptime("2024-02-03T09:10:24+0000", ' '"%Y-%m-%dT%H:%M:%S%z")) }}' ) assert template.Template(tpl, opp).async_render() == 1706951424.0 @patch.object(random, "choice") def test_random_every_time(test_choice, opp): """Ensure the random filter runs every time, not just once.""" tpl = template.Template("{{ [1,2] | random }}", opp) test_choice.return_value = "foo" assert tpl.async_render() == "foo" test_choice.return_value = "bar" assert tpl.async_render() == "bar" def test_passing_vars_as_keywords(opp): """Test passing variables as keywords.""" assert template.Template("{{ hello }}", opp).async_render(hello=127) == 127 def test_passing_vars_as_vars(opp): """Test passing variables as variables.""" assert template.Template("{{ hello }}", opp).async_render({"hello": 127}) == 127 def test_passing_vars_as_list(opp): """Test passing variables as list.""" assert template.render_complex( template.Template("{{ hello }}", opp), {"hello": ["foo", "bar"]} ) == ["foo", "bar"] def test_passing_vars_as_list_element(opp): """Test passing variables as list.""" assert ( template.render_complex( template.Template("{{ hello[1] }}", opp), {"hello": ["foo", "bar"]} ) == "bar" ) def test_passing_vars_as_dict_element(opp): """Test passing variables as list.""" assert ( template.render_complex( template.Template("{{ hello.foo }}", opp), {"hello": {"foo": "bar"}} ) == "bar" ) def test_passing_vars_as_dict(opp): """Test passing variables as list.""" assert template.render_complex( template.Template("{{ hello }}", opp), {"hello": {"foo": "bar"}} ) == {"foo": "bar"} def test_render_with_possible_json_value_with_valid_json(opp): """Render with possible JSON value with valid JSON.""" tpl = template.Template("{{ value_json.hello }}", opp) assert tpl.async_render_with_possible_json_value('{"hello": "world"}') == "world" def test_render_with_possible_json_value_with_invalid_json(opp): """Render with possible JSON value with invalid JSON.""" tpl = template.Template("{{ value_json }}", opp) assert tpl.async_render_with_possible_json_value("{ I AM NOT JSON }") == "" def test_render_with_possible_json_value_with_template_error_value(opp): """Render with possible JSON value with template error value.""" tpl = template.Template("{{ non_existing.variable }}", opp) assert tpl.async_render_with_possible_json_value("hello", "-") == "-" def test_render_with_possible_json_value_with_missing_json_value(opp): """Render with possible JSON value with unknown JSON object.""" tpl = template.Template("{{ value_json.goodbye }}", opp) assert tpl.async_render_with_possible_json_value('{"hello": "world"}') == "" def test_render_with_possible_json_value_valid_with_is_defined(opp): """Render with possible JSON value with known JSON object.""" tpl = template.Template("{{ value_json.hello|is_defined }}", opp) assert tpl.async_render_with_possible_json_value('{"hello": "world"}') == "world" def test_render_with_possible_json_value_undefined_json(opp): """Render with possible JSON value with unknown JSON object.""" tpl = template.Template("{{ value_json.bye|is_defined }}", opp) assert ( tpl.async_render_with_possible_json_value('{"hello": "world"}') == '{"hello": "world"}' ) def test_render_with_possible_json_value_undefined_json_error_value(opp): """Render with possible JSON value with unknown JSON object.""" tpl = template.Template("{{ value_json.bye|is_defined }}", opp) assert tpl.async_render_with_possible_json_value('{"hello": "world"}', "") == "" def test_render_with_possible_json_value_non_string_value(opp): """Render with possible JSON value with non-string value.""" tpl = template.Template( """ {{ strptime(value~'+0000', '%Y-%m-%d %H:%M:%S%z') }} """, opp, ) value = datetime(2019, 1, 18, 12, 13, 14) expected = str(value.replace(tzinfo=dt_util.UTC)) assert tpl.async_render_with_possible_json_value(value) == expected def test_if_state_exists(opp): """Test if state exists works.""" opp.states.async_set("test.object", "available") tpl = template.Template( "{% if states.test.object %}exists{% else %}not exists{% endif %}", opp ) assert tpl.async_render() == "exists" def test_is_state(opp): """Test is_state method.""" opp.states.async_set("test.object", "available") tpl = template.Template( """ {% if is_state("test.object", "available") %}yes{% else %}no{% endif %} """, opp, ) assert tpl.async_render() == "yes" tpl = template.Template( """ {{ is_state("test.noobject", "available") }} """, opp, ) assert tpl.async_render() is False def test_is_state_attr(opp): """Test is_state_attr method.""" opp.states.async_set("test.object", "available", {"mode": "on"}) tpl = template.Template( """ {% if is_state_attr("test.object", "mode", "on") %}yes{% else %}no{% endif %} """, opp, ) assert tpl.async_render() == "yes" tpl = template.Template( """ {{ is_state_attr("test.noobject", "mode", "on") }} """, opp, ) assert tpl.async_render() is False def test_state_attr(opp): """Test state_attr method.""" opp.states.async_set("test.object", "available", {"mode": "on"}) tpl = template.Template( """ {% if state_attr("test.object", "mode") == "on" %}yes{% else %}no{% endif %} """, opp, ) assert tpl.async_render() == "yes" tpl = template.Template( """ {{ state_attr("test.noobject", "mode") == None }} """, opp, ) assert tpl.async_render() is True def test_states_function(opp): """Test using states as a function.""" opp.states.async_set("test.object", "available") tpl = template.Template('{{ states("test.object") }}', opp) assert tpl.async_render() == "available" tpl2 = template.Template('{{ states("test.object2") }}', opp) assert tpl2.async_render() == "unknown" @patch( "openpeerpower.helpers.template.TemplateEnvironment.is_safe_callable", return_value=True, ) def test_now(mock_is_safe, opp): """Test now method.""" now = dt_util.now() with patch("openpeerpower.util.dt.now", return_value=now): info = template.Template("{{ now().isoformat() }}", opp).async_render_to_info() assert now.isoformat() == info.result() assert info.has_time is True @patch( "openpeerpower.helpers.template.TemplateEnvironment.is_safe_callable", return_value=True, ) def test_utcnow(mock_is_safe, opp): """Test now method.""" utcnow = dt_util.utcnow() with patch("openpeerpower.util.dt.utcnow", return_value=utcnow): info = template.Template( "{{ utcnow().isoformat() }}", opp ).async_render_to_info() assert utcnow.isoformat() == info.result() assert info.has_time is True @patch( "openpeerpower.helpers.template.TemplateEnvironment.is_safe_callable", return_value=True, ) def test_relative_time(mock_is_safe, opp): """Test relative_time method.""" now = datetime.strptime("2000-01-01 10:00:00 +00:00", "%Y-%m-%d %H:%M:%S %z") with patch("openpeerpower.util.dt.now", return_value=now): result = template.Template( '{{relative_time(strptime("2000-01-01 09:00:00", "%Y-%m-%d %H:%M:%S"))}}', opp, ).async_render() assert result == "1 hour" result = template.Template( '{{relative_time(strptime("2000-01-01 09:00:00 +01:00", "%Y-%m-%d %H:%M:%S %z"))}}', opp, ).async_render() assert result == "2 hours" result = template.Template( '{{relative_time(strptime("2000-01-01 03:00:00 -06:00", "%Y-%m-%d %H:%M:%S %z"))}}', opp, ).async_render() assert result == "1 hour" result1 = str( template.strptime("2000-01-01 11:00:00 +00:00", "%Y-%m-%d %H:%M:%S %z") ) result2 = template.Template( '{{relative_time(strptime("2000-01-01 11:00:00 +00:00", "%Y-%m-%d %H:%M:%S %z"))}}', opp, ).async_render() assert result1 == result2 result = template.Template( '{{relative_time("string")}}', opp, ).async_render() assert result == "string" @patch( "openpeerpower.helpers.template.TemplateEnvironment.is_safe_callable", return_value=True, ) def test_timedelta(mock_is_safe, opp): """Test relative_time method.""" now = datetime.strptime("2000-01-01 10:00:00 +00:00", "%Y-%m-%d %H:%M:%S %z") with patch("openpeerpower.util.dt.now", return_value=now): result = template.Template( "{{timedelta(seconds=120)}}", opp, ).async_render() assert result == "0:02:00" result = template.Template( "{{timedelta(seconds=86400)}}", opp, ).async_render() assert result == "1 day, 0:00:00" result = template.Template("{{timedelta(days=1, hours=4)}}", opp).async_render() assert result == "1 day, 4:00:00" result = template.Template( "{{relative_time(now() - timedelta(seconds=3600))}}", opp, ).async_render() assert result == "1 hour" result = template.Template( "{{relative_time(now() - timedelta(seconds=86400))}}", opp, ).async_render() assert result == "1 day" result = template.Template( "{{relative_time(now() - timedelta(seconds=86401))}}", opp, ).async_render() assert result == "1 day" result = template.Template( "{{relative_time(now() - timedelta(weeks=2, days=1))}}", opp, ).async_render() assert result == "15 days" def test_regex_match(opp): """Test regex_match method.""" tpl = template.Template( r""" {{ '123-456-7890' | regex_match('(\\d{3})-(\\d{3})-(\\d{4})') }} """, opp, ) assert tpl.async_render() is True tpl = template.Template( """ {{ 'Open Peer Power test' | regex_match('Open', True) }} """, opp, ) assert tpl.async_render() is True tpl = template.Template( """ {{ 'Another Open Peer Power test' | regex_match('Open') }} """, opp, ) assert tpl.async_render() is False tpl = template.Template( """ {{ ['Open Peer Power test'] | regex_match('.*Peer') }} """, opp, ) assert tpl.async_render() is True def test_match_test(opp): """Test match test.""" tpl = template.Template( r""" {{ '123-456-7890' is match('(\\d{3})-(\\d{3})-(\\d{4})') }} """, opp, ) assert tpl.async_render() is True def test_regex_search(opp): """Test regex_search method.""" tpl = template.Template( r""" {{ '123-456-7890' | regex_search('(\\d{3})-(\\d{3})-(\\d{4})') }} """, opp, ) assert tpl.async_render() is True tpl = template.Template( """ {{ 'Open Peer Power test' | regex_search('Open', True) }} """, opp, ) assert tpl.async_render() is True tpl = template.Template( """ {{ 'Another Open Peer Power test' | regex_search('Open') }} """, opp, ) assert tpl.async_render() is True tpl = template.Template( """ {{ ['Open Peer Power test'] | regex_search('Peer') }} """, opp, ) assert tpl.async_render() is True def test_search_test(opp): """Test search test.""" tpl = template.Template( r""" {{ '123-456-7890' is search('(\\d{3})-(\\d{3})-(\\d{4})') }} """, opp, ) assert tpl.async_render() is True def test_regex_replace(opp): """Test regex_replace method.""" tpl = template.Template( r""" {{ 'Hello World' | regex_replace('(Hello\\s)',) }} """, opp, ) assert tpl.async_render() == "World" tpl = template.Template( """ {{ ['Open Peer ponderant test'] | regex_replace('ponderant', 'Power') }} """, opp, ) assert tpl.async_render() == ["Open Peer Power test"] def test_regex_findall_index(opp): """Test regex_findall_index method.""" tpl = template.Template( """ {{ 'Flight from JFK to LHR' | regex_findall_index('([A-Z]{3})', 0) }} """, opp, ) assert tpl.async_render() == "JFK" tpl = template.Template( """ {{ 'Flight from JFK to LHR' | regex_findall_index('([A-Z]{3})', 1) }} """, opp, ) assert tpl.async_render() == "LHR" tpl = template.Template( """ {{ ['JFK', 'LHR'] | regex_findall_index('([A-Z]{3})', 1) }} """, opp, ) assert tpl.async_render() == "LHR" def test_bitwise_and(opp): """Test bitwise_and method.""" tpl = template.Template( """ {{ 8 | bitwise_and(8) }} """, opp, ) assert tpl.async_render() == 8 & 8 tpl = template.Template( """ {{ 10 | bitwise_and(2) }} """, opp, ) assert tpl.async_render() == 10 & 2 tpl = template.Template( """ {{ 8 | bitwise_and(2) }} """, opp, ) assert tpl.async_render() == 8 & 2 def test_bitwise_or(opp): """Test bitwise_or method.""" tpl = template.Template( """ {{ 8 | bitwise_or(8) }} """, opp, ) assert tpl.async_render() == 8 | 8 tpl = template.Template( """ {{ 10 | bitwise_or(2) }} """, opp, ) assert tpl.async_render() == 10 | 2 tpl = template.Template( """ {{ 8 | bitwise_or(2) }} """, opp, ) assert tpl.async_render() == 8 | 2 def test_distance_function_with_1_state(opp): """Test distance function with 1 state.""" _set_up_units(opp) opp.states.async_set( "test.object", "happy", {"latitude": 32.87336, "longitude": -117.22943} ) tpl = template.Template("{{ distance(states.test.object) | round }}", opp) assert tpl.async_render() == 187 def test_distance_function_with_2_states(opp): """Test distance function with 2 states.""" _set_up_units(opp) opp.states.async_set( "test.object", "happy", {"latitude": 32.87336, "longitude": -117.22943} ) opp.states.async_set( "test.object_2", "happy", {"latitude": opp.config.latitude, "longitude": opp.config.longitude}, ) tpl = template.Template( "{{ distance(states.test.object, states.test.object_2) | round }}", opp ) assert tpl.async_render() == 187 def test_distance_function_with_1_coord(opp): """Test distance function with 1 coord.""" _set_up_units(opp) tpl = template.Template('{{ distance("32.87336", "-117.22943") | round }}', opp) assert tpl.async_render() == 187 def test_distance_function_with_2_coords(opp): """Test distance function with 2 coords.""" _set_up_units(opp) assert ( template.Template( '{{ distance("32.87336", "-117.22943", %s, %s) | round }}' % (opp.config.latitude, opp.config.longitude), opp, ).async_render() == 187 ) def test_distance_function_with_1_state_1_coord(opp): """Test distance function with 1 state 1 coord.""" _set_up_units(opp) opp.states.async_set( "test.object_2", "happy", {"latitude": opp.config.latitude, "longitude": opp.config.longitude}, ) tpl = template.Template( '{{ distance("32.87336", "-117.22943", states.test.object_2) ' "| round }}", opp, ) assert tpl.async_render() == 187 tpl2 = template.Template( '{{ distance(states.test.object_2, "32.87336", "-117.22943") ' "| round }}", opp, ) assert tpl2.async_render() == 187 def test_distance_function_return_none_if_invalid_state(opp): """Test distance function return None if invalid state.""" opp.states.async_set("test.object_2", "happy", {"latitude": 10}) tpl = template.Template("{{ distance(states.test.object_2) | round }}", opp) assert tpl.async_render() is None def test_distance_function_return_none_if_invalid_coord(opp): """Test distance function return None if invalid coord.""" assert template.Template('{{ distance("123", "abc") }}', opp).async_render() is None assert template.Template('{{ distance("123") }}', opp).async_render() is None opp.states.async_set( "test.object_2", "happy", {"latitude": opp.config.latitude, "longitude": opp.config.longitude}, ) tpl = template.Template('{{ distance("123", states.test_object_2) }}', opp) assert tpl.async_render() is None def test_distance_function_with_2_entity_ids(opp): """Test distance function with 2 entity ids.""" _set_up_units(opp) opp.states.async_set( "test.object", "happy", {"latitude": 32.87336, "longitude": -117.22943} ) opp.states.async_set( "test.object_2", "happy", {"latitude": opp.config.latitude, "longitude": opp.config.longitude}, ) tpl = template.Template( '{{ distance("test.object", "test.object_2") | round }}', opp ) assert tpl.async_render() == 187 def test_distance_function_with_1_entity_1_coord(opp): """Test distance function with 1 entity_id and 1 coord.""" _set_up_units(opp) opp.states.async_set( "test.object", "happy", {"latitude": opp.config.latitude, "longitude": opp.config.longitude}, ) tpl = template.Template( '{{ distance("test.object", "32.87336", "-117.22943") | round }}', opp ) assert tpl.async_render() == 187 def test_closest_function_home_vs_domain(opp): """Test closest function home vs domain.""" opp.states.async_set( "test_domain.object", "happy", { "latitude": opp.config.latitude + 0.1, "longitude": opp.config.longitude + 0.1, }, ) opp.states.async_set( "not_test_domain.but_closer", "happy", {"latitude": opp.config.latitude, "longitude": opp.config.longitude}, ) assert ( template.Template( "{{ closest(states.test_domain).entity_id }}", opp ).async_render() == "test_domain.object" ) assert ( template.Template( "{{ (states.test_domain | closest).entity_id }}", opp ).async_render() == "test_domain.object" ) def test_closest_function_home_vs_all_states(opp): """Test closest function home vs all states.""" opp.states.async_set( "test_domain.object", "happy", { "latitude": opp.config.latitude + 0.1, "longitude": opp.config.longitude + 0.1, }, ) opp.states.async_set( "test_domain_2.and_closer", "happy", {"latitude": opp.config.latitude, "longitude": opp.config.longitude}, ) assert ( template.Template("{{ closest(states).entity_id }}", opp).async_render() == "test_domain_2.and_closer" ) assert ( template.Template("{{ (states | closest).entity_id }}", opp).async_render() == "test_domain_2.and_closer" ) async def test_closest_function_home_vs_group_entity_id(opp): """Test closest function home vs group entity id.""" opp.states.async_set( "test_domain.object", "happy", { "latitude": opp.config.latitude + 0.1, "longitude": opp.config.longitude + 0.1, }, ) opp.states.async_set( "not_in_group.but_closer", "happy", {"latitude": opp.config.latitude, "longitude": opp.config.longitude}, ) assert await async_setup_component(opp, "group", {}) await opp.async_block_till_done() await group.Group.async_create_group(opp, "location group", ["test_domain.object"]) info = render_to_info(opp, '{{ closest("group.location_group").entity_id }}') assert_result_info( info, "test_domain.object", {"group.location_group", "test_domain.object"} ) assert info.rate_limit is None async def test_closest_function_home_vs_group_state(opp): """Test closest function home vs group state.""" opp.states.async_set( "test_domain.object", "happy", { "latitude": opp.config.latitude + 0.1, "longitude": opp.config.longitude + 0.1, }, ) opp.states.async_set( "not_in_group.but_closer", "happy", {"latitude": opp.config.latitude, "longitude": opp.config.longitude}, ) assert await async_setup_component(opp, "group", {}) await opp.async_block_till_done() await group.Group.async_create_group(opp, "location group", ["test_domain.object"]) info = render_to_info(opp, '{{ closest("group.location_group").entity_id }}') assert_result_info( info, "test_domain.object", {"group.location_group", "test_domain.object"} ) assert info.rate_limit is None info = render_to_info(opp, "{{ closest(states.group.location_group).entity_id }}") assert_result_info( info, "test_domain.object", {"test_domain.object", "group.location_group"} ) assert info.rate_limit is None async def test_expand(opp): """Test expand function.""" info = render_to_info(opp, "{{ expand('test.object') }}") assert_result_info(info, [], ["test.object"]) assert info.rate_limit is None info = render_to_info(opp, "{{ expand(56) }}") assert_result_info(info, []) assert info.rate_limit is None opp.states.async_set("test.object", "happy") info = render_to_info( opp, "{{ expand('test.object') | map(attribute='entity_id') | join(', ') }}" ) assert_result_info(info, "test.object", ["test.object"]) assert info.rate_limit is None info = render_to_info( opp, "{{ expand('group.new_group') | map(attribute='entity_id') | join(', ') }}", ) assert_result_info(info, "", ["group.new_group"]) assert info.rate_limit is None info = render_to_info( opp, "{{ expand(states.group) | map(attribute='entity_id') | join(', ') }}" ) assert_result_info(info, "", [], ["group"]) assert info.rate_limit == template.DOMAIN_STATES_RATE_LIMIT assert await async_setup_component(opp, "group", {}) await opp.async_block_till_done() await group.Group.async_create_group(opp, "new group", ["test.object"]) info = render_to_info( opp, "{{ expand('group.new_group') | map(attribute='entity_id') | join(', ') }}", ) assert_result_info(info, "test.object", {"group.new_group", "test.object"}) assert info.rate_limit is None info = render_to_info( opp, "{{ expand(states.group) | map(attribute='entity_id') | join(', ') }}" ) assert_result_info(info, "test.object", {"test.object"}, ["group"]) assert info.rate_limit == template.DOMAIN_STATES_RATE_LIMIT info = render_to_info( opp, "{{ expand('group.new_group', 'test.object')" " | map(attribute='entity_id') | join(', ') }}", ) assert_result_info(info, "test.object", {"test.object", "group.new_group"}) info = render_to_info( opp, "{{ ['group.new_group', 'test.object'] | expand" " | map(attribute='entity_id') | join(', ') }}", ) assert_result_info(info, "test.object", {"test.object", "group.new_group"}) assert info.rate_limit is None opp.states.async_set("sensor.power_1", 0) opp.states.async_set("sensor.power_2", 200.2) opp.states.async_set("sensor.power_3", 400.4) assert await async_setup_component(opp, "group", {}) await opp.async_block_till_done() await group.Group.async_create_group( opp, "power sensors", ["sensor.power_1", "sensor.power_2", "sensor.power_3"] ) info = render_to_info( opp, "{{ states.group.power_sensors.attributes.entity_id | expand | map(attribute='state')|map('float')|sum }}", ) assert_result_info( info, 200.2 + 400.4, {"group.power_sensors", "sensor.power_1", "sensor.power_2", "sensor.power_3"}, ) assert info.rate_limit is None async def test_device_entities(opp): """Test expand function.""" config_entry = MockConfigEntry(domain="light") device_registry = mock_device_registry(opp) entity_registry = mock_registry(opp) # Test non existing device ids info = render_to_info(opp, "{{ device_entities('abc123') }}") assert_result_info(info, []) assert info.rate_limit is None info = render_to_info(opp, "{{ device_entities(56) }}") assert_result_info(info, []) assert info.rate_limit is None # Test device without entities device_entry = device_registry.async_get_or_create( config_entry_id=config_entry.entry_id, connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, ) info = render_to_info(opp, f"{{{{ device_entities('{device_entry.id}') }}}}") assert_result_info(info, []) assert info.rate_limit is None # Test device with single entity, which has no state entity_registry.async_get_or_create( "light", "hue", "5678", config_entry=config_entry, device_id=device_entry.id, ) info = render_to_info(opp, f"{{{{ device_entities('{device_entry.id}') }}}}") assert_result_info(info, ["light.hue_5678"], []) assert info.rate_limit is None info = render_to_info( opp, f"{{{{ device_entities('{device_entry.id}') | expand | map(attribute='entity_id') | join(', ') }}}}", ) assert_result_info(info, "", ["light.hue_5678"]) assert info.rate_limit is None # Test device with single entity, with state opp.states.async_set("light.hue_5678", "happy") info = render_to_info( opp, f"{{{{ device_entities('{device_entry.id}') | expand | map(attribute='entity_id') | join(', ') }}}}", ) assert_result_info(info, "light.hue_5678", ["light.hue_5678"]) assert info.rate_limit is None # Test device with multiple entities, which have a state entity_registry.async_get_or_create( "light", "hue", "ABCD", config_entry=config_entry, device_id=device_entry.id, ) opp.states.async_set("light.hue_abcd", "camper") info = render_to_info(opp, f"{{{{ device_entities('{device_entry.id}') }}}}") assert_result_info(info, ["light.hue_5678", "light.hue_abcd"], []) assert info.rate_limit is None info = render_to_info( opp, f"{{{{ device_entities('{device_entry.id}') | expand | map(attribute='entity_id') | join(', ') }}}}", ) assert_result_info( info, "light.hue_5678, light.hue_abcd", ["light.hue_5678", "light.hue_abcd"] ) assert info.rate_limit is None def test_closest_function_to_coord(opp): """Test closest function to coord.""" opp.states.async_set( "test_domain.closest_home", "happy", { "latitude": opp.config.latitude + 0.1, "longitude": opp.config.longitude + 0.1, }, ) opp.states.async_set( "test_domain.closest_zone", "happy", { "latitude": opp.config.latitude + 0.2, "longitude": opp.config.longitude + 0.2, }, ) opp.states.async_set( "zone.far_away", "zoning", { "latitude": opp.config.latitude + 0.3, "longitude": opp.config.longitude + 0.3, }, ) tpl = template.Template( '{{ closest("%s", %s, states.test_domain).entity_id }}' % (opp.config.latitude + 0.3, opp.config.longitude + 0.3), opp, ) assert tpl.async_render() == "test_domain.closest_zone" tpl = template.Template( '{{ (states.test_domain | closest("%s", %s)).entity_id }}' % (opp.config.latitude + 0.3, opp.config.longitude + 0.3), opp, ) assert tpl.async_render() == "test_domain.closest_zone" def test_async_render_to_info_with_branching(opp): """Test async_render_to_info function by domain.""" opp.states.async_set("light.a", "off") opp.states.async_set("light.b", "on") opp.states.async_set("light.c", "off") info = render_to_info( opp, """ {% if states.light.a == "on" %} {{ states.light.b.state }} {% else %} {{ states.light.c.state }} {% endif %} """, ) assert_result_info(info, "off", {"light.a", "light.c"}) assert info.rate_limit is None info = render_to_info( opp, """ {% if states.light.a.state == "off" %} {% set domain = "light" %} {{ states[domain].b.state }} {% endif %} """, ) assert_result_info(info, "on", {"light.a", "light.b"}) assert info.rate_limit is None def test_async_render_to_info_with_complex_branching(opp): """Test async_render_to_info function by domain.""" opp.states.async_set("light.a", "off") opp.states.async_set("light.b", "on") opp.states.async_set("light.c", "off") opp.states.async_set("vacuum.a", "off") opp.states.async_set("device_tracker.a", "off") opp.states.async_set("device_tracker.b", "off") opp.states.async_set("lock.a", "off") opp.states.async_set("sensor.a", "off") opp.states.async_set("binary_sensor.a", "off") info = render_to_info( opp, """ {% set domain = "vacuum" %} {% if states.light.a == "on" %} {{ states.light.b.state }} {% elif states.light.a == "on" %} {{ states.device_tracker }} {% elif states.light.a == "on" %} {{ states[domain] | list }} {% elif states('light.b') == "on" %} {{ states[otherdomain] | map(attribute='entity_id') | list }} {% elif states.light.a == "on" %} {{ states["nonexist"] | list }} {% else %} else {% endif %} """, {"otherdomain": "sensor"}, ) assert_result_info(info, ["sensor.a"], {"light.a", "light.b"}, {"sensor"}) assert info.rate_limit == template.DOMAIN_STATES_RATE_LIMIT async def test_async_render_to_info_with_wildcard_matching_entity_id(opp): """Test tracking template with a wildcard.""" template_complex_str = r""" {% for state in states.cover %} {% if state.entity_id | regex_match('.*\.office_') %} {{ state.entity_id }}={{ state.state }} {% endif %} {% endfor %} """ opp.states.async_set("cover.office_drapes", "closed") opp.states.async_set("cover.office_window", "closed") opp.states.async_set("cover.office_skylight", "open") info = render_to_info(opp, template_complex_str) assert info.domains == {"cover"} assert info.entities == set() assert info.all_states is False assert info.rate_limit == template.DOMAIN_STATES_RATE_LIMIT async def test_async_render_to_info_with_wildcard_matching_state(opp): """Test tracking template with a wildcard.""" template_complex_str = """ {% for state in states %} {% if state.state | regex_match('ope.*') %} {{ state.entity_id }}={{ state.state }} {% endif %} {% endfor %} """ opp.states.async_set("cover.office_drapes", "closed") opp.states.async_set("cover.office_window", "closed") opp.states.async_set("cover.office_skylight", "open") opp.states.async_set("cover.x_skylight", "open") opp.states.async_set("binary_sensor.door", "open") await opp.async_block_till_done() info = render_to_info(opp, template_complex_str) assert not info.domains assert info.entities == set() assert info.all_states is True assert info.rate_limit == template.ALL_STATES_RATE_LIMIT opp.states.async_set("binary_sensor.door", "closed") info = render_to_info(opp, template_complex_str) assert not info.domains assert info.entities == set() assert info.all_states is True assert info.rate_limit == template.ALL_STATES_RATE_LIMIT template_cover_str = """ {% for state in states.cover %} {% if state.state | regex_match('ope.*') %} {{ state.entity_id }}={{ state.state }} {% endif %} {% endfor %} """ opp.states.async_set("cover.x_skylight", "closed") info = render_to_info(opp, template_cover_str) assert info.domains == {"cover"} assert info.entities == set() assert info.all_states is False assert info.rate_limit == template.DOMAIN_STATES_RATE_LIMIT def test_nested_async_render_to_info_case(opp): """Test a deeply nested state with async_render_to_info.""" opp.states.async_set("input_select.picker", "vacuum.a") opp.states.async_set("vacuum.a", "off") info = render_to_info( opp, "{{ states[states['input_select.picker'].state].state }}", {} ) assert_result_info(info, "off", {"input_select.picker", "vacuum.a"}) assert info.rate_limit is None def test_result_as_boolean(opp): """Test converting a template result to a boolean.""" assert template.result_as_boolean(True) is True assert template.result_as_boolean(" 1 ") is True assert template.result_as_boolean(" true ") is True assert template.result_as_boolean(" TrUE ") is True assert template.result_as_boolean(" YeS ") is True assert template.result_as_boolean(" On ") is True assert template.result_as_boolean(" Enable ") is True assert template.result_as_boolean(1) is True assert template.result_as_boolean(-1) is True assert template.result_as_boolean(500) is True assert template.result_as_boolean(0.5) is True assert template.result_as_boolean(0.389) is True assert template.result_as_boolean(35) is True assert template.result_as_boolean(False) is False assert template.result_as_boolean(" 0 ") is False assert template.result_as_boolean(" false ") is False assert template.result_as_boolean(" FaLsE ") is False assert template.result_as_boolean(" no ") is False assert template.result_as_boolean(" off ") is False assert template.result_as_boolean(" disable ") is False assert template.result_as_boolean(0) is False assert template.result_as_boolean(0.0) is False assert template.result_as_boolean("0.00") is False assert template.result_as_boolean(None) is False def test_closest_function_to_entity_id(opp): """Test closest function to entity id.""" opp.states.async_set( "test_domain.closest_home", "happy", { "latitude": opp.config.latitude + 0.1, "longitude": opp.config.longitude + 0.1, }, ) opp.states.async_set( "test_domain.closest_zone", "happy", { "latitude": opp.config.latitude + 0.2, "longitude": opp.config.longitude + 0.2, }, ) opp.states.async_set( "zone.far_away", "zoning", { "latitude": opp.config.latitude + 0.3, "longitude": opp.config.longitude + 0.3, }, ) info = render_to_info( opp, "{{ closest(zone, states.test_domain).entity_id }}", {"zone": "zone.far_away"}, ) assert_result_info( info, "test_domain.closest_zone", ["test_domain.closest_home", "test_domain.closest_zone", "zone.far_away"], ["test_domain"], ) info = render_to_info( opp, "{{ ([states.test_domain, 'test_domain.closest_zone'] " "| closest(zone)).entity_id }}", {"zone": "zone.far_away"}, ) assert_result_info( info, "test_domain.closest_zone", ["test_domain.closest_home", "test_domain.closest_zone", "zone.far_away"], ["test_domain"], ) def test_closest_function_to_state(opp): """Test closest function to state.""" opp.states.async_set( "test_domain.closest_home", "happy", { "latitude": opp.config.latitude + 0.1, "longitude": opp.config.longitude + 0.1, }, ) opp.states.async_set( "test_domain.closest_zone", "happy", { "latitude": opp.config.latitude + 0.2, "longitude": opp.config.longitude + 0.2, }, ) opp.states.async_set( "zone.far_away", "zoning", { "latitude": opp.config.latitude + 0.3, "longitude": opp.config.longitude + 0.3, }, ) assert ( template.Template( "{{ closest(states.zone.far_away, states.test_domain).entity_id }}", opp ).async_render() == "test_domain.closest_zone" ) def test_closest_function_invalid_state(opp): """Test closest function invalid state.""" opp.states.async_set( "test_domain.closest_home", "happy", { "latitude": opp.config.latitude + 0.1, "longitude": opp.config.longitude + 0.1, }, ) for state in ("states.zone.non_existing", '"zone.non_existing"'): assert ( template.Template("{{ closest(%s, states) }}" % state, opp).async_render() is None ) def test_closest_function_state_with_invalid_location(opp): """Test closest function state with invalid location.""" opp.states.async_set( "test_domain.closest_home", "happy", {"latitude": "invalid latitude", "longitude": opp.config.longitude + 0.1}, ) assert ( template.Template( "{{ closest(states.test_domain.closest_home, states) }}", opp ).async_render() is None ) def test_closest_function_invalid_coordinates(opp): """Test closest function invalid coordinates.""" opp.states.async_set( "test_domain.closest_home", "happy", { "latitude": opp.config.latitude + 0.1, "longitude": opp.config.longitude + 0.1, }, ) assert ( template.Template( '{{ closest("invalid", "coord", states) }}', opp ).async_render() is None ) assert ( template.Template( '{{ states | closest("invalid", "coord") }}', opp ).async_render() is None ) def test_closest_function_no_location_states(opp): """Test closest function without location states.""" assert ( template.Template("{{ closest(states).entity_id }}", opp).async_render() == "" ) def test_generate_filter_iterators(opp): """Test extract entities function with none entities stuff.""" info = render_to_info( opp, """ {% for state in states %} {{ state.entity_id }} {% endfor %} """, ) assert_result_info(info, "", all_states=True) info = render_to_info( opp, """ {% for state in states.sensor %} {{ state.entity_id }} {% endfor %} """, ) assert_result_info(info, "", domains=["sensor"]) opp.states.async_set("sensor.test_sensor", "off", {"attr": "value"}) # Don't need the entity because the state is not accessed info = render_to_info( opp, """ {% for state in states.sensor %} {{ state.entity_id }} {% endfor %} """, ) assert_result_info(info, "sensor.test_sensor", domains=["sensor"]) # But we do here because the state gets accessed info = render_to_info( opp, """ {% for state in states.sensor %} {{ state.entity_id }}={{ state.state }}, {% endfor %} """, ) assert_result_info(info, "sensor.test_sensor=off,", [], ["sensor"]) info = render_to_info( opp, """ {% for state in states.sensor %} {{ state.entity_id }}={{ state.attributes.attr }}, {% endfor %} """, ) assert_result_info(info, "sensor.test_sensor=value,", [], ["sensor"]) def test_generate_select(opp): """Test extract entities function with none entities stuff.""" template_str = """ {{ states.sensor|selectattr("state","equalto","off") |join(",", attribute="entity_id") }} """ tmp = template.Template(template_str, opp) info = tmp.async_render_to_info() assert_result_info(info, "", [], []) assert info.domains_lifecycle == {"sensor"} opp.states.async_set("sensor.test_sensor", "off", {"attr": "value"}) opp.states.async_set("sensor.test_sensor_on", "on") info = tmp.async_render_to_info() assert_result_info( info, "sensor.test_sensor", [], ["sensor"], ) assert info.domains_lifecycle == {"sensor"} async def test_async_render_to_info_in_conditional(opp): """Test extract entities function with none entities stuff.""" template_str = """ {{ states("sensor.xyz") == "dog" }} """ tmp = template.Template(template_str, opp) info = tmp.async_render_to_info() assert_result_info(info, False, ["sensor.xyz"], []) opp.states.async_set("sensor.xyz", "dog") opp.states.async_set("sensor.cow", "True") await opp.async_block_till_done() template_str = """ {% if states("sensor.xyz") == "dog" %} {{ states("sensor.cow") }} {% else %} {{ states("sensor.pig") }} {% endif %} """ tmp = template.Template(template_str, opp) info = tmp.async_render_to_info() assert_result_info(info, True, ["sensor.xyz", "sensor.cow"], []) opp.states.async_set("sensor.xyz", "sheep") opp.states.async_set("sensor.pig", "oink") await opp.async_block_till_done() tmp = template.Template(template_str, opp) info = tmp.async_render_to_info() assert_result_info(info, "oink", ["sensor.xyz", "sensor.pig"], []) def test_jinja_namespace(opp): """Test Jinja's namespace command can be used.""" test_template = template.Template( ( "{% set ns = namespace(a_key='') %}" "{% set ns.a_key = states.sensor.dummy.state %}" "{{ ns.a_key }}" ), opp, ) opp.states.async_set("sensor.dummy", "a value") assert test_template.async_render() == "a value" opp.states.async_set("sensor.dummy", "another value") assert test_template.async_render() == "another value" def test_state_with_unit(opp): """Test the state_with_unit property helper.""" opp.states.async_set("sensor.test", "23", {ATTR_UNIT_OF_MEASUREMENT: "beers"}) opp.states.async_set("sensor.test2", "wow") tpl = template.Template("{{ states.sensor.test.state_with_unit }}", opp) assert tpl.async_render() == "23 beers" tpl = template.Template("{{ states.sensor.test2.state_with_unit }}", opp) assert tpl.async_render() == "wow" tpl = template.Template( "{% for state in states %}{{ state.state_with_unit }} {% endfor %}", opp ) assert tpl.async_render() == "23 beers wow" tpl = template.Template("{{ states.sensor.non_existing.state_with_unit }}", opp) assert tpl.async_render() == "" def test_length_of_states(opp): """Test fetching the length of states.""" opp.states.async_set("sensor.test", "23") opp.states.async_set("sensor.test2", "wow") opp.states.async_set("climate.test2", "cooling") tpl = template.Template("{{ states | length }}", opp) assert tpl.async_render() == 3 tpl = template.Template("{{ states.sensor | length }}", opp) assert tpl.async_render() == 2 def test_render_complex_handling_non_template_values(opp): """Test that we can render non-template fields.""" assert template.render_complex( {True: 1, False: template.Template("{{ hello }}", opp)}, {"hello": 2} ) == {True: 1, False: 2} def test_urlencode(opp): """Test the urlencode method.""" tpl = template.Template( ("{% set dict = {'foo': 'x&y', 'bar': 42} %}" "{{ dict | urlencode }}"), opp, ) assert tpl.async_render() == "foo=x%26y&bar=42" tpl = template.Template( ("{% set string = 'the quick brown fox = true' %}" "{{ string | urlencode }}"), opp, ) assert tpl.async_render() == "the%20quick%20brown%20fox%20%3D%20true" async def test_cache_garbage_collection(): """Test caching a template.""" template_string = ( "{% set dict = {'foo': 'x&y', 'bar': 42} %} {{ dict | urlencode }}" ) tpl = template.Template( (template_string), ) tpl.ensure_valid() assert template._NO_OPP_ENV.template_cache.get( template_string ) # pylint: disable=protected-access tpl2 = template.Template( (template_string), ) tpl2.ensure_valid() assert template._NO_OPP_ENV.template_cache.get( template_string ) # pylint: disable=protected-access del tpl assert template._NO_OPP_ENV.template_cache.get( template_string ) # pylint: disable=protected-access del tpl2 assert not template._NO_OPP_ENV.template_cache.get( template_string ) # pylint: disable=protected-access def test_is_template_string(): """Test is template string.""" assert template.is_template_string("{{ x }}") is True assert template.is_template_string("{% if x == 2 %}1{% else %}0{%end if %}") is True assert template.is_template_string("{# a comment #} Hey") is True assert template.is_template_string("1") is False assert template.is_template_string("Some Text") is False async def test_protected_blocked(opp): """Test accessing __getattr__ produces a template error.""" tmp = template.Template('{{ states.__getattr__("any") }}', opp) with pytest.raises(TemplateError): tmp.async_render() tmp = template.Template('{{ states.sensor.__getattr__("any") }}', opp) with pytest.raises(TemplateError): tmp.async_render() tmp = template.Template('{{ states.sensor.any.__getattr__("any") }}', opp) with pytest.raises(TemplateError): tmp.async_render() async def test_demo_template(opp): """Test the demo template works as expected.""" opp.states.async_set("sun.sun", "above", {"elevation": 50, "next_rising": "later"}) for i in range(2): opp.states.async_set(f"sensor.sensor{i}", "on") demo_template_str = """ {## Imitate available variables: ##} {% set my_test_json = { "temperature": 25, "unit": "°C" } %} The temperature is {{ my_test_json.temperature }} {{ my_test_json.unit }}. {% if is_state("sun.sun", "above_horizon") -%} The sun rose {{ relative_time(states.sun.sun.last_changed) }} ago. {%- else -%} The sun will rise at {{ as_timestamp(strptime(state_attr("sun.sun", "next_rising"), "")) | timestamp_local }}. {%- endif %} For loop example getting 3 entity values: {% for states in states | slice(3) -%} {% set state = states | first %} {%- if loop.first %}The {% elif loop.last %} and the {% else %}, the {% endif -%} {{ state.name | lower }} is {{state.state_with_unit}} {%- endfor %}. """ tmp = template.Template(demo_template_str, opp) result = tmp.async_render() assert "The temperature is 25" in result assert "is on" in result assert "sensor0" in result assert "sensor1" in result assert "sun" in result async def test_slice_states(opp): """Test iterating states with a slice.""" opp.states.async_set("sensor.test", "23") tpl = template.Template( "{% for states in states | slice(1) -%}{% set state = states | first %}{{ state.entity_id }}{%- endfor %}", opp, ) assert tpl.async_render() == "sensor.test" async def test_lifecycle(opp): """Test that we limit template render info for lifecycle events.""" opp.states.async_set("sun.sun", "above", {"elevation": 50, "next_rising": "later"}) for i in range(2): opp.states.async_set(f"sensor.sensor{i}", "on") opp.states.async_set("sensor.removed", "off") await opp.async_block_till_done() opp.states.async_set("sun.sun", "below", {"elevation": 60, "next_rising": "later"}) for i in range(2): opp.states.async_set(f"sensor.sensor{i}", "off") opp.states.async_set("sensor.new", "off") opp.states.async_remove("sensor.removed") await opp.async_block_till_done() tmp = template.Template("{{ states | count }}", opp) info = tmp.async_render_to_info() assert info.all_states is False assert info.all_states_lifecycle is True assert info.rate_limit is None assert info.has_time is False assert info.entities == set() assert info.domains == set() assert info.domains_lifecycle == set() assert info.filter("sun.sun") is False assert info.filter("sensor.sensor1") is False assert info.filter_lifecycle("sensor.new") is True assert info.filter_lifecycle("sensor.removed") is True async def test_template_timeout(opp): """Test to see if a template will timeout.""" for i in range(2): opp.states.async_set(f"sensor.sensor{i}", "on") tmp = template.Template("{{ states | count }}", opp) assert await tmp.async_render_will_timeout(3) is False tmp3 = template.Template("static", opp) assert await tmp3.async_render_will_timeout(3) is False tmp4 = template.Template("{{ var1 }}", opp) assert await tmp4.async_render_will_timeout(3, {"var1": "ok"}) is False slow_template_str = """ {% for var in range(1000) -%} {% for var in range(1000) -%} {{ var }} {%- endfor %} {%- endfor %} """ tmp5 = template.Template(slow_template_str, opp) assert await tmp5.async_render_will_timeout(0.000001) is True async def test_template_timeout_raise(opp): """Test we can raise from.""" tmp2 = template.Template("{{ error_invalid + 1 }}", opp) with pytest.raises(TemplateError): assert await tmp2.async_render_will_timeout(3) is False async def test_lights(opp): """Test we can sort lights.""" tmpl = """ {% set lights_on = states.light|selectattr('state','eq','on')|map(attribute='name')|list %} {% if lights_on|length == 0 %} No lights on. Sleep well.. {% elif lights_on|length == 1 %} The {{lights_on[0]}} light is on. {% elif lights_on|length == 2 %} The {{lights_on[0]}} and {{lights_on[1]}} lights are on. {% else %} The {{lights_on[:-1]|join(', ')}}, and {{lights_on[-1]}} lights are on. {% endif %} """ states = [] for i in range(10): states.append(f"light.sensor{i}") opp.states.async_set(f"light.sensor{i}", "on") tmp = template.Template(tmpl, opp) info = tmp.async_render_to_info() assert info.entities == set() assert info.domains == {"light"} assert "lights are on" in info.result() for i in range(10): assert f"sensor{i}" in info.result() async def test_template_errors(opp): """Test template rendering wraps exceptions with TemplateError.""" with pytest.raises(TemplateError): template.Template("{{ now() | rando }}", opp).async_render() with pytest.raises(TemplateError): template.Template("{{ utcnow() | rando }}", opp).async_render() with pytest.raises(TemplateError): template.Template("{{ now() | random }}", opp).async_render() with pytest.raises(TemplateError): template.Template("{{ utcnow() | random }}", opp).async_render() async def test_state_attributes(opp): """Test state attributes.""" opp.states.async_set("sensor.test", "23") tpl = template.Template( "{{ states.sensor.test.last_changed }}", opp, ) assert tpl.async_render() == str(opp.states.get("sensor.test").last_changed) tpl = template.Template( "{{ states.sensor.test.object_id }}", opp, ) assert tpl.async_render() == opp.states.get("sensor.test").object_id tpl = template.Template( "{{ states.sensor.test.domain }}", opp, ) assert tpl.async_render() == opp.states.get("sensor.test").domain tpl = template.Template( "{{ states.sensor.test.context.id }}", opp, ) assert tpl.async_render() == opp.states.get("sensor.test").context.id tpl = template.Template( "{{ states.sensor.test.state_with_unit }}", opp, ) assert tpl.async_render() == 23 tpl = template.Template( "{{ states.sensor.test.invalid_prop }}", opp, ) assert tpl.async_render() == "" tpl = template.Template( "{{ states.sensor.test.invalid_prop.xx }}", opp, ) with pytest.raises(TemplateError): tpl.async_render() async def test_unavailable_states(opp): """Test watching unavailable states.""" for i in range(10): opp.states.async_set(f"light.sensor{i}", "on") opp.states.async_set("light.unavailable", "unavailable") opp.states.async_set("light.unknown", "unknown") opp.states.async_set("light.none", "none") tpl = template.Template( "{{ states | selectattr('state', 'in', ['unavailable','unknown','none']) | map(attribute='entity_id') | list | join(', ') }}", opp, ) assert tpl.async_render() == "light.none, light.unavailable, light.unknown" tpl = template.Template( "{{ states.light | selectattr('state', 'in', ['unavailable','unknown','none']) | map(attribute='entity_id') | list | join(', ') }}", opp, ) assert tpl.async_render() == "light.none, light.unavailable, light.unknown" async def test_legacy_templates(opp): """Test if old template behavior works when legacy templates are enabled.""" opp.states.async_set("sensor.temperature", "12") assert ( template.Template("{{ states.sensor.temperature.state }}", opp).async_render() == 12 ) await async_process_op_core_config(opp, {"legacy_templates": True}) assert ( template.Template("{{ states.sensor.temperature.state }}", opp).async_render() == "12" ) async def test_no_result_parsing(opp): """Test if templates results are not parsed.""" opp.states.async_set("sensor.temperature", "12") assert ( template.Template("{{ states.sensor.temperature.state }}", opp).async_render( parse_result=False ) == "12" ) assert ( template.Template("{{ false }}", opp).async_render(parse_result=False) == "False" ) assert ( template.Template("{{ [1, 2, 3] }}", opp).async_render(parse_result=False) == "[1, 2, 3]" ) async def test_is_static_still_ast_evals(opp): """Test is_static still convers to native type.""" tpl = template.Template("[1, 2]", opp) assert tpl.is_static assert tpl.async_render() == [1, 2] async def test_result_wrappers(opp): """Test result wrappers.""" for text, native, orig_type, schema in ( ("[1, 2]", [1, 2], list, vol.Schema([int])), ("{1, 2}", {1, 2}, set, vol.Schema({int})), ("(1, 2)", (1, 2), tuple, vol.ExactSequence([int, int])), ('{"hello": True}', {"hello": True}, dict, vol.Schema({"hello": bool})), ): tpl = template.Template(text, opp) result = tpl.async_render() assert isinstance(result, orig_type) assert isinstance(result, template.ResultWrapper) assert result == native assert result.render_result == text schema(result) # should not raise # Result with render text stringifies to original text assert str(result) == text # Result without render text stringifies same as original type assert str(template.RESULT_WRAPPERS[orig_type](native)) == str( orig_type(native) ) async def test_parse_result(opp): """Test parse result.""" for tpl, result in ( ('{{ "{{}}" }}', "{{}}"), ("not-something", "not-something"), ("2a", "2a"), ("123E5", "123E5"), ("1j", "1j"), ("1e+100", "1e+100"), ("0xface", "0xface"), ("123", 123), ("10", 10), ("123.0", 123.0), (".5", 0.5), ("0.5", 0.5), ("-1", -1), ("-1.0", -1.0), ("+1", 1), ("5.", 5.0), ("123_123_123", "123_123_123"), # ("+48100200300", "+48100200300"), # phone number ("010", "010"), ("0011101.00100001010001", "0011101.00100001010001"), ): assert template.Template(tpl, opp).async_render() == result async def test_undefined_variable(opp, caplog): """Test a warning is logged on undefined variables.""" tpl = template.Template("{{ no_such_variable }}", opp) assert tpl.async_render() == "" assert ( "Template variable warning: 'no_such_variable' is undefined when rendering '{{ no_such_variable }}'" in caplog.text )
# views.py - views for comments # # This file is part of debexpo # https://salsa.debian.org/mentors.debian.net-team/debexpo # # Copyright © 2019 Baptiste Beauplat <lyknode@cilg.org> # # 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. from logging import getLogger from django.conf import settings from django.shortcuts import render, get_object_or_404 from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect, HttpResponseNotAllowed from django.urls import reverse from .forms import SubscriptionForm, CommentForm from .models import PackageSubscription from debexpo.packages.models import Package, PackageUpload log = getLogger(__name__) @login_required def subscriptions(request): if request.method == 'POST': return HttpResponseRedirect(reverse('subscribe_package', args=[request.POST.get('package')])) return render(request, 'subscriptions.html', { 'settings': settings, 'subscriptions': PackageSubscription.objects.filter(user=request.user) .all() }) @login_required def unsubscribe(request, name): if request.method != 'POST': return HttpResponseNotAllowed(['POST']) sub = get_object_or_404(PackageSubscription, user=request.user, package=name) sub.delete() return HttpResponseRedirect(reverse('subscriptions')) @login_required def subscribe(request, name): sub = PackageSubscription.objects.filter(user=request.user, package=name) instance = None if sub.exists(): instance = sub.get() if request.method == 'POST': form = SubscriptionForm(request.POST, instance=instance) package = request.POST.get('next') if form.is_valid(): subscription = form.save(commit=False) subscription.user = request.user subscription.package = name subscription.save() if subscription.can_delete(): log.info(f'Unsubscribe {request.user.email} for package {name}') subscription.delete() else: log.info(f'Updating subscription for {request.user.email} on ' f'{name}: ' f'{', '.join(subscription.get_subscriptions())}') if package: return HttpResponseRedirect(reverse('package', args=[package])) else: return HttpResponseRedirect(reverse('subscriptions')) else: form = SubscriptionForm(instance=instance) package = request.GET.get('next') return render(request, 'subscribe.html', { 'settings': settings, 'package': name, 'next': package, 'form': form, }) @login_required def comment(request, name): if request.method != 'POST': return HttpResponseNotAllowed(['POST']) upload_id = request.POST.get('upload_id') package = get_object_or_404(Package, name=name) upload = get_object_or_404(PackageUpload, package=package, pk=upload_id) redirect_url = reverse('package', args=[name]) index = upload.get_index() form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.user = request.user comment.upload = upload comment.save() comment.notify(request) return HttpResponseRedirect(f"{redirect_url}#upload-{index}")
# views.py - views for comments # # This file is part of debexpo # https://salsa.debian.org/mentors.debian.net-team/debexpo # # Copyright © 2019 Baptiste Beauplat <lyknode@cilg.org> # # 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. from logging import getLogger from django.conf import settings from django.shortcuts import render, get_object_or_404 from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect, HttpResponseNotAllowed from django.urls import reverse from .forms import SubscriptionForm, CommentForm from .models import PackageSubscription from debexpo.packages.models import Package, PackageUpload log = getLogger(__name__) @login_required def subscriptions(request): if request.method == 'POST': return HttpResponseRedirect(reverse('subscribe_package', args=[request.POST.get('package')])) return render(request, 'subscriptions.html', { 'settings': settings, 'subscriptions': PackageSubscription.objects.filter(user=request.user) .all() }) @login_required def unsubscribe(request, name): if request.method != 'POST': return HttpResponseNotAllowed(['POST']) sub = get_object_or_404(PackageSubscription, user=request.user, package=name) sub.delete() return HttpResponseRedirect(reverse('subscriptions')) @login_required def subscribe(request, name): sub = PackageSubscription.objects.filter(user=request.user, package=name) instance = None if sub.exists(): instance = sub.get() if request.method == 'POST': form = SubscriptionForm(request.POST, instance=instance) package = request.POST.get('next') if form.is_valid(): subscription = form.save(commit=False) subscription.user = request.user subscription.package = name subscription.save() if subscription.can_delete(): log.info(f'Unsubscribe {request.user.email} for package {name}') subscription.delete() else: log.info(f'Updating subscription for {request.user.email} on ' f'{name}: ' f'{", ".join(subscription.get_subscriptions())}') if package: return HttpResponseRedirect(reverse('package', args=[package])) else: return HttpResponseRedirect(reverse('subscriptions')) else: form = SubscriptionForm(instance=instance) package = request.GET.get('next') return render(request, 'subscribe.html', { 'settings': settings, 'package': name, 'next': package, 'form': form, }) @login_required def comment(request, name): if request.method != 'POST': return HttpResponseNotAllowed(['POST']) upload_id = request.POST.get('upload_id') package = get_object_or_404(Package, name=name) upload = get_object_or_404(PackageUpload, package=package, pk=upload_id) redirect_url = reverse('package', args=[name]) index = upload.get_index() form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.user = request.user comment.upload = upload comment.save() comment.notify(request) return HttpResponseRedirect(f"{redirect_url}#upload-{index}")
import json from pathlib import Path import pytest SCOPES = ("global", "host", "environment", "os", "appliance") # Need this because load can touch filesystem files. @pytest.mark.usefixtures("revert_etc") class TestLoad: """A test case to hold all the tests for `stack load`""" @pytest.mark.parametrize("scope", SCOPES) def test_load_processing_attr(self, host, stack_load, test_file, scope): """Test that load added expected attr values at every scope.""" # get the file path to use in load. file_path = Path(test_file("load/json/attr.json")).resolve(strict = True) # Load all of the test data into the database. Some commands output have the potential to fail, # such as removing existing storage partitions before loading new ones, and that is OK. result = stack_load(file_path) # Run the list command to get the results for the global scope. result = host.run(f"stack list {scope if scope != "global" else ""} attr output-format=json") assert result.rc == 0 listed_results = json.loads(result.stdout) # Load the expected result. expected_result = json.loads(Path(test_file(f"load/json/expected_attr_{scope}.json")).read_text()) # Since scope collapsing can cause more objects to be listed for a scope than was set at that scope, # we just look for the entry we expect to be in the list an call that a success. assert any( listed_result == expected_result for listed_result in listed_results ), f"Missing expected attribute {expected_result} at {scope} scope.\n\nListed attributes were:\n\n{listed_results}" @pytest.mark.parametrize("scope", SCOPES) def test_load_processing_controller(self, host, stack_load, test_file, scope): """Test that load added expected storage controller values at every scope.""" # get the file path to use in load. file_path = Path(test_file("load/json/controller.json")).resolve(strict = True) # Load all of the test data into the database. Some commands output have the potential to fail, # such as removing existing storage partitions before loading new ones, and that is OK. result = stack_load(file_path) # Run the list command to get the results for the global scope. result = host.run(f"stack list {scope if scope != "global" else ""} storage controller output-format=json") assert result.rc == 0 listed_results = json.loads(result.stdout) # Load the expected result. expected_result = json.loads(Path(test_file(f"load/json/expected_controller_{scope}.json")).read_text()) # Since scope collapsing can cause more objects to be listed for a scope than was set at that scope, # we just look for the entry we expect to be in the list an call that a success. assert any( listed_result == expected_result for listed_result in listed_results ), f"Missing expected storage controller {expected_result} at {scope} scope.\n\nListed storage controllers were:\n\n{listed_results}" @pytest.mark.parametrize("scope", SCOPES) def test_load_processing_firewall(self, host, stack_load, test_file, scope): """Test that load added expected firewall values at every scope.""" # get the file path to use in load. file_path = Path(test_file("load/json/firewall.json")).resolve(strict = True) # Load all of the test data into the database. Some commands output have the potential to fail, # such as removing existing storage partitions before loading new ones, and that is OK. result = stack_load(file_path) # Run the list command to get the results for the global scope. result = host.run(f"stack list {scope if scope != "global" else ""} firewall output-format=json") assert result.rc == 0 listed_results = json.loads(result.stdout) # Load the expected result. expected_result = json.loads(Path(test_file(f"load/json/expected_firewall_{scope}.json")).read_text()) # Since scope collapsing can cause more objects to be listed for a scope than was set at that scope, # we just look for the entry we expect to be in the list an call that a success. assert any( listed_result == expected_result for listed_result in listed_results ), f"Missing expected firewall {expected_result} at {scope} scope.\n\nListed firewalls were:\n\n{listed_results}" @pytest.mark.parametrize("scope", SCOPES) def test_load_processing_partition(self, host, stack_load, test_file, scope): """Test that load added expected storage partition values at every scope.""" # get the file path to use in load. file_path = Path(test_file("load/json/partition.json")).resolve(strict = True) # Load all of the test data into the database. Some commands output have the potential to fail, # such as removing existing storage partitions before loading new ones, and that is OK. result = stack_load(file_path) # Run the list command to get the results for the global scope. result = host.run(f"stack list {scope if scope != "global" else ""} storage partition output-format=json") assert result.rc == 0 listed_results = json.loads(result.stdout) # Load the expected result. expected_result = json.loads(Path(test_file(f"load/json/expected_partition_{scope}.json")).read_text()) # Since scope collapsing can cause more objects to be listed for a scope than was set at that scope, # we just look for the entry we expect to be in the list an call that a success. assert any( listed_result == expected_result for listed_result in listed_results ), f"Missing expected storage partition {expected_result} at {scope} scope.\n\nListed storage partitions were:\n\n{listed_results}" @pytest.mark.parametrize("scope", SCOPES) def test_load_processing_route(self, host, stack_load, test_file, scope): """Test that load added expected route values at every scope.""" # get the file path to use in load. file_path = Path(test_file("load/json/route.json")).resolve(strict = True) # Load all of the test data into the database. Some commands output have the potential to fail, # such as removing existing storage partitions before loading new ones, and that is OK. result = stack_load(file_path) # Run the list command to get the results for the global scope. result = host.run(f"stack list {scope if scope != "global" else ""} route output-format=json") assert result.rc == 0 listed_results = json.loads(result.stdout) # Load the expected result. expected_result = json.loads(Path(test_file(f"load/json/expected_route_{scope}.json")).read_text()) # Since scope collapsing can cause more objects to be listed for a scope than was set at that scope, # we just look for the entry we expect to be in the list an call that a success. assert any( listed_result == expected_result for listed_result in listed_results ), f"Missing expected route {expected_result} at {scope} scope.\n\nListed storage routes were:\n\n{listed_results}" @pytest.mark.parametrize("scope", SCOPES) def test_load_multiple_partitions(self, host, stack_load, test_file, scope): """Ensure that loading partitions twice removes the previously set partitioning at that scope before adding the new partitioning.""" # get the file path to use in load. real_partition_file_path = Path(test_file("load/json/partition.json")).resolve(strict = True) secondary_partition_file_path = Path(test_file("load/json/partition2.json")).resolve(strict = True) # Load the secondary partitioning first, and then load the real partitioning stack_load(secondary_partition_file_path) result = stack_load(real_partition_file_path) # Run the list command to get the results for the appliance scope. result = host.run(f"stack list {scope if scope != "global" else ""} storage partition output-format=json") assert result.rc == 0 listed_results = json.loads(result.stdout) # Load the expected result. expected_result = json.loads(Path(test_file(f"load/json/expected_partition_{scope}.json")).read_text()) # Since scope collapsing can cause more objects to be listed for a scope than was set at that scope, # we just look for the entry we expect to be in the list an call that a success. assert any( listed_result == expected_result for listed_result in listed_results ), f"Missing expected storage partition {expected_result} at {scope} scope.\n\nListed storage partitions were:\n\n{listed_results}"
import json from pathlib import Path import pytest SCOPES = ("global", "host", "environment", "os", "appliance") # Need this because load can touch filesystem files. @pytest.mark.usefixtures("revert_etc") class TestLoad: """A test case to hold all the tests for `stack load`""" @pytest.mark.parametrize("scope", SCOPES) def test_load_processing_attr(self, host, stack_load, test_file, scope): """Test that load added expected attr values at every scope.""" # get the file path to use in load. file_path = Path(test_file("load/json/attr.json")).resolve(strict = True) # Load all of the test data into the database. Some commands output have the potential to fail, # such as removing existing storage partitions before loading new ones, and that is OK. result = stack_load(file_path) # Run the list command to get the results for the global scope. result = host.run(f"stack list {scope if scope != 'global' else ''} attr output-format=json") assert result.rc == 0 listed_results = json.loads(result.stdout) # Load the expected result. expected_result = json.loads(Path(test_file(f"load/json/expected_attr_{scope}.json")).read_text()) # Since scope collapsing can cause more objects to be listed for a scope than was set at that scope, # we just look for the entry we expect to be in the list an call that a success. assert any( listed_result == expected_result for listed_result in listed_results ), f"Missing expected attribute {expected_result} at {scope} scope.\n\nListed attributes were:\n\n{listed_results}" @pytest.mark.parametrize("scope", SCOPES) def test_load_processing_controller(self, host, stack_load, test_file, scope): """Test that load added expected storage controller values at every scope.""" # get the file path to use in load. file_path = Path(test_file("load/json/controller.json")).resolve(strict = True) # Load all of the test data into the database. Some commands output have the potential to fail, # such as removing existing storage partitions before loading new ones, and that is OK. result = stack_load(file_path) # Run the list command to get the results for the global scope. result = host.run(f"stack list {scope if scope != 'global' else ''} storage controller output-format=json") assert result.rc == 0 listed_results = json.loads(result.stdout) # Load the expected result. expected_result = json.loads(Path(test_file(f"load/json/expected_controller_{scope}.json")).read_text()) # Since scope collapsing can cause more objects to be listed for a scope than was set at that scope, # we just look for the entry we expect to be in the list an call that a success. assert any( listed_result == expected_result for listed_result in listed_results ), f"Missing expected storage controller {expected_result} at {scope} scope.\n\nListed storage controllers were:\n\n{listed_results}" @pytest.mark.parametrize("scope", SCOPES) def test_load_processing_firewall(self, host, stack_load, test_file, scope): """Test that load added expected firewall values at every scope.""" # get the file path to use in load. file_path = Path(test_file("load/json/firewall.json")).resolve(strict = True) # Load all of the test data into the database. Some commands output have the potential to fail, # such as removing existing storage partitions before loading new ones, and that is OK. result = stack_load(file_path) # Run the list command to get the results for the global scope. result = host.run(f"stack list {scope if scope != 'global' else ''} firewall output-format=json") assert result.rc == 0 listed_results = json.loads(result.stdout) # Load the expected result. expected_result = json.loads(Path(test_file(f"load/json/expected_firewall_{scope}.json")).read_text()) # Since scope collapsing can cause more objects to be listed for a scope than was set at that scope, # we just look for the entry we expect to be in the list an call that a success. assert any( listed_result == expected_result for listed_result in listed_results ), f"Missing expected firewall {expected_result} at {scope} scope.\n\nListed firewalls were:\n\n{listed_results}" @pytest.mark.parametrize("scope", SCOPES) def test_load_processing_partition(self, host, stack_load, test_file, scope): """Test that load added expected storage partition values at every scope.""" # get the file path to use in load. file_path = Path(test_file("load/json/partition.json")).resolve(strict = True) # Load all of the test data into the database. Some commands output have the potential to fail, # such as removing existing storage partitions before loading new ones, and that is OK. result = stack_load(file_path) # Run the list command to get the results for the global scope. result = host.run(f"stack list {scope if scope != 'global' else ''} storage partition output-format=json") assert result.rc == 0 listed_results = json.loads(result.stdout) # Load the expected result. expected_result = json.loads(Path(test_file(f"load/json/expected_partition_{scope}.json")).read_text()) # Since scope collapsing can cause more objects to be listed for a scope than was set at that scope, # we just look for the entry we expect to be in the list an call that a success. assert any( listed_result == expected_result for listed_result in listed_results ), f"Missing expected storage partition {expected_result} at {scope} scope.\n\nListed storage partitions were:\n\n{listed_results}" @pytest.mark.parametrize("scope", SCOPES) def test_load_processing_route(self, host, stack_load, test_file, scope): """Test that load added expected route values at every scope.""" # get the file path to use in load. file_path = Path(test_file("load/json/route.json")).resolve(strict = True) # Load all of the test data into the database. Some commands output have the potential to fail, # such as removing existing storage partitions before loading new ones, and that is OK. result = stack_load(file_path) # Run the list command to get the results for the global scope. result = host.run(f"stack list {scope if scope != 'global' else ''} route output-format=json") assert result.rc == 0 listed_results = json.loads(result.stdout) # Load the expected result. expected_result = json.loads(Path(test_file(f"load/json/expected_route_{scope}.json")).read_text()) # Since scope collapsing can cause more objects to be listed for a scope than was set at that scope, # we just look for the entry we expect to be in the list an call that a success. assert any( listed_result == expected_result for listed_result in listed_results ), f"Missing expected route {expected_result} at {scope} scope.\n\nListed storage routes were:\n\n{listed_results}" @pytest.mark.parametrize("scope", SCOPES) def test_load_multiple_partitions(self, host, stack_load, test_file, scope): """Ensure that loading partitions twice removes the previously set partitioning at that scope before adding the new partitioning.""" # get the file path to use in load. real_partition_file_path = Path(test_file("load/json/partition.json")).resolve(strict = True) secondary_partition_file_path = Path(test_file("load/json/partition2.json")).resolve(strict = True) # Load the secondary partitioning first, and then load the real partitioning stack_load(secondary_partition_file_path) result = stack_load(real_partition_file_path) # Run the list command to get the results for the appliance scope. result = host.run(f"stack list {scope if scope != 'global' else ''} storage partition output-format=json") assert result.rc == 0 listed_results = json.loads(result.stdout) # Load the expected result. expected_result = json.loads(Path(test_file(f"load/json/expected_partition_{scope}.json")).read_text()) # Since scope collapsing can cause more objects to be listed for a scope than was set at that scope, # we just look for the entry we expect to be in the list an call that a success. assert any( listed_result == expected_result for listed_result in listed_results ), f"Missing expected storage partition {expected_result} at {scope} scope.\n\nListed storage partitions were:\n\n{listed_results}"
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import json from asyncio import get_event_loop, ensure_future, gather, sleep from datetime import datetime, timedelta from pprint import pprint from anticens import anticens from imgcry import encrypt_image from pixiv import PixivApi, JP_TZ from weibo import WeiboApi class Pixiv2Weibo: CONFIG_PATH = 'config.json' CACHE_PATH = 'cache.json' WEIBO_COOKIE_PATH = 'weibo_cookie.pickle' def __init__(self): self._config = self._load_json(self.CONFIG_PATH, { 'pixiv_cookie': '', 'pixiv_proxy': '', 'weibo_username': '', 'weibo_password': '' }) self._pixiv = PixivApi(self._config['pixiv_cookie'], self._config['pixiv_proxy']) self._weibo = WeiboApi() try: self._weibo.load_cookie(self.WEIBO_COOKIE_PATH) except FileNotFoundError: pass async def close(self): await gather(self._pixiv.close(), self._weibo.close()) @staticmethod def _load_json(path, default=None): try: with open(path) as f: return json.load(f) except FileNotFoundError: return default async def start(self): # 登录微博 login_future = ensure_future(self._weibo.login_if_need( self._config['weibo_username'], self._config['weibo_password'] )) # 取要发的图信息 cache = await self._load_cache() try: image_info = cache['image_info'][cache['next_index']] except IndexError: print('没图了') return cache['next_index'] += 1 with open(self.CACHE_PATH, 'w') as f: json.dump(cache, f) print('图片信息:') pprint(image_info) # 爬图 image_data = await self._pixiv.get_image_data(image_info) image_data = map(encrypt_image, filter(lambda x: x, image_data)) # for index, data in enumerate(image_data): # with open(str(index) + '.jpg', 'wb') as f: # f.write(data) await login_future self._weibo.save_cookie(self.WEIBO_COOKIE_PATH) # 上传 print('正在上传图片') futures = [] for data in image_data: futures.append(ensure_future(self._weibo.upload_image(data))) # 加密同时上传,而不是全部加密后再全部上传 await sleep(0) image_ids = await gather(*futures) image_ids = list(filter(lambda x: x, image_ids)) print('image_ids:') pprint(image_ids) # 发微博 text = ( f'{image_info['rank_cate']} #{image_info['rank']} {image_info['title']}\n' f'作者:{image_info['user_name']}\n' f'标签:{','.join(image_info['tags'])}\n' f'https://www.pixiv.net/member_illust.php?mode=medium&illust_id={image_info['illust_id']}' ) await self._weibo.post_weibo(text, image_ids) print('OK') async def _load_cache(self): # 日本时间中午12点更新 date = (datetime.now(JP_TZ) - timedelta(hours=12, minutes=10)).strftime('%Y-%m-%d') cache = self._load_json(self.CACHE_PATH) if cache and cache['date'] == date: return cache cache = { 'date': date, 'next_index': 0, 'image_info': await self._pixiv.get_image_info() } with open(self.CACHE_PATH, 'w') as f: json.dump(cache, f) return cache async def main(): anticens.add_hosts([ 'www.pixiv.net', 'i.pximg.net' ]) anticens.enable() p2w = Pixiv2Weibo() await p2w.start() await p2w.close() if __name__ == '__main__': get_event_loop().run_until_complete(main())
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import json from asyncio import get_event_loop, ensure_future, gather, sleep from datetime import datetime, timedelta from pprint import pprint from anticens import anticens from imgcry import encrypt_image from pixiv import PixivApi, JP_TZ from weibo import WeiboApi class Pixiv2Weibo: CONFIG_PATH = 'config.json' CACHE_PATH = 'cache.json' WEIBO_COOKIE_PATH = 'weibo_cookie.pickle' def __init__(self): self._config = self._load_json(self.CONFIG_PATH, { 'pixiv_cookie': '', 'pixiv_proxy': '', 'weibo_username': '', 'weibo_password': '' }) self._pixiv = PixivApi(self._config['pixiv_cookie'], self._config['pixiv_proxy']) self._weibo = WeiboApi() try: self._weibo.load_cookie(self.WEIBO_COOKIE_PATH) except FileNotFoundError: pass async def close(self): await gather(self._pixiv.close(), self._weibo.close()) @staticmethod def _load_json(path, default=None): try: with open(path) as f: return json.load(f) except FileNotFoundError: return default async def start(self): # 登录微博 login_future = ensure_future(self._weibo.login_if_need( self._config['weibo_username'], self._config['weibo_password'] )) # 取要发的图信息 cache = await self._load_cache() try: image_info = cache['image_info'][cache['next_index']] except IndexError: print('没图了') return cache['next_index'] += 1 with open(self.CACHE_PATH, 'w') as f: json.dump(cache, f) print('图片信息:') pprint(image_info) # 爬图 image_data = await self._pixiv.get_image_data(image_info) image_data = map(encrypt_image, filter(lambda x: x, image_data)) # for index, data in enumerate(image_data): # with open(str(index) + '.jpg', 'wb') as f: # f.write(data) await login_future self._weibo.save_cookie(self.WEIBO_COOKIE_PATH) # 上传 print('正在上传图片') futures = [] for data in image_data: futures.append(ensure_future(self._weibo.upload_image(data))) # 加密同时上传,而不是全部加密后再全部上传 await sleep(0) image_ids = await gather(*futures) image_ids = list(filter(lambda x: x, image_ids)) print('image_ids:') pprint(image_ids) # 发微博 text = ( f'{image_info["rank_cate"]} #{image_info["rank"]} {image_info["title"]}\n' f'作者:{image_info["user_name"]}\n' f'标签:{",".join(image_info["tags"])}\n' f'https://www.pixiv.net/member_illust.php?mode=medium&illust_id={image_info["illust_id"]}' ) await self._weibo.post_weibo(text, image_ids) print('OK') async def _load_cache(self): # 日本时间中午12点更新 date = (datetime.now(JP_TZ) - timedelta(hours=12, minutes=10)).strftime('%Y-%m-%d') cache = self._load_json(self.CACHE_PATH) if cache and cache['date'] == date: return cache cache = { 'date': date, 'next_index': 0, 'image_info': await self._pixiv.get_image_info() } with open(self.CACHE_PATH, 'w') as f: json.dump(cache, f) return cache async def main(): anticens.add_hosts([ 'www.pixiv.net', 'i.pximg.net' ]) anticens.enable() p2w = Pixiv2Weibo() await p2w.start() await p2w.close() if __name__ == '__main__': get_event_loop().run_until_complete(main())
import logging import textwrap from collections import ChainMap from io import StringIO from typing import Union import discord from discord import Color, Embed, Member, PartialMessage, RawReactionActionEvent, User from discord.ext.commands import Cog, Context, group, has_any_role from bot.api import ResponseCodeError from bot.bot import Bot from bot.constants import Channels, Emojis, Guild, MODERATION_ROLES, STAFF_ROLES, Webhooks from bot.converters import FetchedMember from bot.exts.moderation.watchchannels._watchchannel import WatchChannel from bot.exts.recruitment.talentpool._review import Reviewer from bot.pagination import LinePaginator from bot.utils import time REASON_MAX_CHARS = 1000 log = logging.getLogger(__name__) class TalentPool(WatchChannel, Cog, name="Talentpool"): """Relays messages of helper candidates to a watch channel to observe them.""" def __init__(self, bot: Bot) -> None: super().__init__( bot, destination=Channels.talent_pool, webhook_id=Webhooks.talent_pool, api_endpoint='bot/nominations', api_default_params={'active': 'true', 'ordering': '-inserted_at'}, logger=log, disable_header=True, ) self.reviewer = Reviewer(self.__class__.__name__, bot, self) self.bot.loop.create_task(self.reviewer.reschedule_reviews()) @group(name='talentpool', aliases=('tp', 'talent', 'nomination', 'n'), invoke_without_command=True) @has_any_role(*MODERATION_ROLES) async def nomination_group(self, ctx: Context) -> None: """Highlights the activity of helper nominees by relaying their messages to the talent pool channel.""" await ctx.send_help(ctx.command) @nomination_group.command(name='watched', aliases=('all', 'list'), root_aliases=("nominees",)) @has_any_role(*MODERATION_ROLES) async def watched_command( self, ctx: Context, oldest_first: bool = False, update_cache: bool = True ) -> None: """ Shows the users that are currently being monitored in the talent pool. The optional kwarg `oldest_first` can be used to order the list by oldest nomination. The optional kwarg `update_cache` can be used to update the user cache using the API before listing the users. """ await self.list_watched_users(ctx, oldest_first=oldest_first, update_cache=update_cache) async def list_watched_users( self, ctx: Context, oldest_first: bool = False, update_cache: bool = True ) -> None: """ Gives an overview of the nominated users list. It specifies the users' mention, name, how long ago they were nominated, and whether their review was scheduled or already posted. The optional kwarg `oldest_first` orders the list by oldest entry. The optional kwarg `update_cache` specifies whether the cache should be refreshed by polling the API. """ # TODO Once the watch channel is removed, this can be done in a smarter way, without splitting and overriding # the list_watched_users function. watched_data = await self.prepare_watched_users_data(ctx, oldest_first, update_cache) if update_cache and not watched_data["updated"]: await ctx.send(f":x: Failed to update {self.__class__.__name__} user cache, serving from cache") lines = [] for user_id, line in watched_data["info"].items(): if self.watched_users[user_id]['reviewed']: line += " *(reviewed)*" elif user_id in self.reviewer: line += " *(scheduled)*" lines.append(line) if not lines: lines = ("There's nothing here yet.",) embed = Embed( title=watched_data["title"], color=Color.blue() ) await LinePaginator.paginate(lines, ctx, embed, empty=False) @nomination_group.command(name='oldest') @has_any_role(*MODERATION_ROLES) async def oldest_command(self, ctx: Context, update_cache: bool = True) -> None: """ Shows talent pool monitored users ordered by oldest nomination. The optional kwarg `update_cache` can be used to update the user cache using the API before listing the users. """ await ctx.invoke(self.watched_command, oldest_first=True, update_cache=update_cache) @nomination_group.command(name='forcewatch', aliases=('fw', 'forceadd', 'fa'), root_aliases=("forcenominate",)) @has_any_role(*MODERATION_ROLES) async def force_watch_command(self, ctx: Context, user: FetchedMember, *, reason: str = '') -> None: """ Adds the given `user` to the talent pool, from any channel. A `reason` for adding the user to the talent pool is optional. """ await self._watch_user(ctx, user, reason) @nomination_group.command(name='watch', aliases=('w', 'add', 'a'), root_aliases=("nominate",)) @has_any_role(*STAFF_ROLES) async def watch_command(self, ctx: Context, user: FetchedMember, *, reason: str = '') -> None: """ Adds the given `user` to the talent pool. A `reason` for adding the user to the talent pool is optional. This command can only be used in the `#nominations` channel. """ if ctx.channel.id != Channels.nominations: if any(role.id in MODERATION_ROLES for role in ctx.author.roles): await ctx.send( f":x: Nominations should be run in the <#{Channels.nominations}> channel. " "Use `!tp forcewatch` to override this check." ) else: await ctx.send(f":x: Nominations must be run in the <#{Channels.nominations}> channel") return await self._watch_user(ctx, user, reason) async def _watch_user(self, ctx: Context, user: FetchedMember, reason: str) -> None: """Adds the given user to the talent pool.""" if user.bot: await ctx.send(f":x: I'm sorry {ctx.author}, I'm afraid I can't do that. I only watch humans.") return if isinstance(user, Member) and any(role.id in STAFF_ROLES for role in user.roles): await ctx.send(":x: Nominating staff members, eh? Here's a cookie :cookie:") return if not await self.fetch_user_cache(): await ctx.send(f":x: Failed to update the user cache; can't add {user}") return if len(reason) > REASON_MAX_CHARS: await ctx.send(f":x: Maxiumum allowed characters for the reason is {REASON_MAX_CHARS}.") return # Manual request with `raise_for_status` as False because we want the actual response session = self.bot.api_client.session url = self.bot.api_client._url_for(self.api_endpoint) kwargs = { 'json': { 'actor': ctx.author.id, 'reason': reason, 'user': user.id }, 'raise_for_status': False, } async with session.post(url, **kwargs) as resp: response_data = await resp.json() if resp.status == 400: if response_data.get('user', False): await ctx.send(":x: The specified user can't be found in the database tables") elif response_data.get('actor', False): await ctx.send(":x: You have already nominated this user") return else: resp.raise_for_status() self.watched_users[user.id] = response_data if user.id not in self.reviewer: self.reviewer.schedule_review(user.id) history = await self.bot.api_client.get( self.api_endpoint, params={ "user__id": str(user.id), "active": "false", "ordering": "-inserted_at" } ) msg = f"✅ The nomination for {user} has been added to the talent pool" if history: msg += f"\n\n({len(history)} previous nominations in total)" await ctx.send(msg) @nomination_group.command(name='history', aliases=('info', 'search')) @has_any_role(*MODERATION_ROLES) async def history_command(self, ctx: Context, user: FetchedMember) -> None: """Shows the specified user's nomination history.""" result = await self.bot.api_client.get( self.api_endpoint, params={ 'user__id': str(user.id), 'ordering': "-active,-inserted_at" } ) if not result: await ctx.send(":warning: This user has never been nominated") return embed = Embed( title=f"Nominations for {user.display_name} `({user.id})`", color=Color.blue() ) lines = [self._nomination_to_string(nomination) for nomination in result] await LinePaginator.paginate( lines, ctx=ctx, embed=embed, empty=True, max_lines=3, max_size=1000 ) @nomination_group.command(name='unwatch', aliases=('end', ), root_aliases=("unnominate",)) @has_any_role(*MODERATION_ROLES) async def unwatch_command(self, ctx: Context, user: FetchedMember, *, reason: str) -> None: """ Ends the active nomination of the specified user with the given reason. Providing a `reason` is required. """ if len(reason) > REASON_MAX_CHARS: await ctx.send(f":x: Maxiumum allowed characters for the end reason is {REASON_MAX_CHARS}.") return if await self.unwatch(user.id, reason): await ctx.send(f":white_check_mark: Messages sent by {user} will no longer be relayed") else: await ctx.send(":x: The specified user does not have an active nomination") @nomination_group.group(name='edit', aliases=('e',), invoke_without_command=True) @has_any_role(*MODERATION_ROLES) async def nomination_edit_group(self, ctx: Context) -> None: """Commands to edit nominations.""" await ctx.send_help(ctx.command) @nomination_edit_group.command(name='reason') @has_any_role(*MODERATION_ROLES) async def edit_reason_command(self, ctx: Context, nomination_id: int, actor: FetchedMember, *, reason: str) -> None: """Edits the reason of a specific nominator in a specific active nomination.""" if len(reason) > REASON_MAX_CHARS: await ctx.send(f":x: Maxiumum allowed characters for the reason is {REASON_MAX_CHARS}.") return try: nomination = await self.bot.api_client.get(f"{self.api_endpoint}/{nomination_id}") except ResponseCodeError as e: if e.response.status == 404: self.log.trace(f"Nomination API 404: Can't find a nomination with id {nomination_id}") await ctx.send(f":x: Can't find a nomination with id `{nomination_id}`") return else: raise if not nomination["active"]: await ctx.send(":x: Can't edit the reason of an inactive nomination.") return if not any(entry["actor"] == actor.id for entry in nomination["entries"]): await ctx.send(f":x: {actor} doesn't have an entry in this nomination.") return self.log.trace(f"Changing reason for nomination with id {nomination_id} of actor {actor} to {repr(reason)}") await self.bot.api_client.patch( f"{self.api_endpoint}/{nomination_id}", json={"actor": actor.id, "reason": reason} ) await self.fetch_user_cache() # Update cache await ctx.send(":white_check_mark: Successfully updated nomination reason.") @nomination_edit_group.command(name='end_reason') @has_any_role(*MODERATION_ROLES) async def edit_end_reason_command(self, ctx: Context, nomination_id: int, *, reason: str) -> None: """Edits the unnominate reason for the nomination with the given `id`.""" if len(reason) > REASON_MAX_CHARS: await ctx.send(f":x: Maxiumum allowed characters for the end reason is {REASON_MAX_CHARS}.") return try: nomination = await self.bot.api_client.get(f"{self.api_endpoint}/{nomination_id}") except ResponseCodeError as e: if e.response.status == 404: self.log.trace(f"Nomination API 404: Can't find a nomination with id {nomination_id}") await ctx.send(f":x: Can't find a nomination with id `{nomination_id}`") return else: raise if nomination["active"]: await ctx.send(":x: Can't edit the end reason of an active nomination.") return self.log.trace(f"Changing end reason for nomination with id {nomination_id} to {repr(reason)}") await self.bot.api_client.patch( f"{self.api_endpoint}/{nomination_id}", json={"end_reason": reason} ) await self.fetch_user_cache() # Update cache. await ctx.send(":white_check_mark: Updated the end reason of the nomination!") @nomination_group.command(aliases=('mr',)) @has_any_role(*MODERATION_ROLES) async def mark_reviewed(self, ctx: Context, user_id: int) -> None: """Mark a user's nomination as reviewed and cancel the review task.""" if not await self.reviewer.mark_reviewed(ctx, user_id): return await ctx.send(f"{Emojis.check_mark} The user with ID `{user_id}` was marked as reviewed.") @nomination_group.command(aliases=('gr',)) @has_any_role(*MODERATION_ROLES) async def get_review(self, ctx: Context, user_id: int) -> None: """Get the user's review as a markdown file.""" review = (await self.reviewer.make_review(user_id))[0] if review: file = discord.File(StringIO(review), f"{user_id}_review.md") await ctx.send(file=file) else: await ctx.send(f"There doesn't appear to be an active nomination for {user_id}") @nomination_group.command(aliases=('review',)) @has_any_role(*MODERATION_ROLES) async def post_review(self, ctx: Context, user_id: int) -> None: """Post the automatic review for the user ahead of time.""" if not await self.reviewer.mark_reviewed(ctx, user_id): return await self.reviewer.post_review(user_id, update_database=False) await ctx.message.add_reaction(Emojis.check_mark) @Cog.listener() async def on_member_ban(self, guild: Guild, user: Union[User, Member]) -> None: """Remove `user` from the talent pool after they are banned.""" await self.unwatch(user.id, "User was banned.") @Cog.listener() async def on_raw_reaction_add(self, payload: RawReactionActionEvent) -> None: """ Watch for reactions in the #nomination-voting channel to automate it. Adding a ticket emoji will unpin the message. Adding an incident reaction will archive the message. """ if payload.channel_id != Channels.nomination_voting: return message: PartialMessage = self.bot.get_channel(payload.channel_id).get_partial_message(payload.message_id) emoji = str(payload.emoji) if emoji == "\N{TICKET}": await message.unpin(reason="Admin task created.") elif emoji in {Emojis.incident_actioned, Emojis.incident_unactioned}: log.info(f"Archiving nomination {message.id}") await self.reviewer.archive_vote(message, emoji == Emojis.incident_actioned) async def unwatch(self, user_id: int, reason: str) -> bool: """End the active nomination of a user with the given reason and return True on success.""" active_nomination = await self.bot.api_client.get( self.api_endpoint, params=ChainMap( {"user__id": str(user_id)}, self.api_default_params, ) ) if not active_nomination: log.debug(f"No active nominate exists for {user_id=}") return False log.info(f"Ending nomination: {user_id=} {reason=}") nomination = active_nomination[0] await self.bot.api_client.patch( f"{self.api_endpoint}/{nomination["id"]}", json={'end_reason': reason, 'active': False} ) self._remove_user(user_id) self.reviewer.cancel(user_id) return True def _nomination_to_string(self, nomination_object: dict) -> str: """Creates a string representation of a nomination.""" guild = self.bot.get_guild(Guild.id) entries = [] for site_entry in nomination_object["entries"]: actor_id = site_entry["actor"] actor = guild.get_member(actor_id) reason = site_entry["reason"] or "*None*" created = time.format_infraction(site_entry["inserted_at"]) entries.append( f"Actor: {actor.mention if actor else actor_id}\nCreated: {created}\nReason: {reason}" ) entries_string = "\n\n".join(entries) active = nomination_object["active"] start_date = time.format_infraction(nomination_object["inserted_at"]) if active: lines = textwrap.dedent( f""" =============== Status: **Active** Date: {start_date} Nomination ID: `{nomination_object["id"]}` {entries_string} =============== """ ) else: end_date = time.format_infraction(nomination_object["ended_at"]) lines = textwrap.dedent( f""" =============== Status: Inactive Date: {start_date} Nomination ID: `{nomination_object["id"]}` {entries_string} End date: {end_date} Unwatch reason: {nomination_object["end_reason"]} =============== """ ) return lines.strip() def cog_unload(self) -> None: """Cancels all review tasks on cog unload.""" super().cog_unload() self.reviewer.cancel_all()
import logging import textwrap from collections import ChainMap from io import StringIO from typing import Union import discord from discord import Color, Embed, Member, PartialMessage, RawReactionActionEvent, User from discord.ext.commands import Cog, Context, group, has_any_role from bot.api import ResponseCodeError from bot.bot import Bot from bot.constants import Channels, Emojis, Guild, MODERATION_ROLES, STAFF_ROLES, Webhooks from bot.converters import FetchedMember from bot.exts.moderation.watchchannels._watchchannel import WatchChannel from bot.exts.recruitment.talentpool._review import Reviewer from bot.pagination import LinePaginator from bot.utils import time REASON_MAX_CHARS = 1000 log = logging.getLogger(__name__) class TalentPool(WatchChannel, Cog, name="Talentpool"): """Relays messages of helper candidates to a watch channel to observe them.""" def __init__(self, bot: Bot) -> None: super().__init__( bot, destination=Channels.talent_pool, webhook_id=Webhooks.talent_pool, api_endpoint='bot/nominations', api_default_params={'active': 'true', 'ordering': '-inserted_at'}, logger=log, disable_header=True, ) self.reviewer = Reviewer(self.__class__.__name__, bot, self) self.bot.loop.create_task(self.reviewer.reschedule_reviews()) @group(name='talentpool', aliases=('tp', 'talent', 'nomination', 'n'), invoke_without_command=True) @has_any_role(*MODERATION_ROLES) async def nomination_group(self, ctx: Context) -> None: """Highlights the activity of helper nominees by relaying their messages to the talent pool channel.""" await ctx.send_help(ctx.command) @nomination_group.command(name='watched', aliases=('all', 'list'), root_aliases=("nominees",)) @has_any_role(*MODERATION_ROLES) async def watched_command( self, ctx: Context, oldest_first: bool = False, update_cache: bool = True ) -> None: """ Shows the users that are currently being monitored in the talent pool. The optional kwarg `oldest_first` can be used to order the list by oldest nomination. The optional kwarg `update_cache` can be used to update the user cache using the API before listing the users. """ await self.list_watched_users(ctx, oldest_first=oldest_first, update_cache=update_cache) async def list_watched_users( self, ctx: Context, oldest_first: bool = False, update_cache: bool = True ) -> None: """ Gives an overview of the nominated users list. It specifies the users' mention, name, how long ago they were nominated, and whether their review was scheduled or already posted. The optional kwarg `oldest_first` orders the list by oldest entry. The optional kwarg `update_cache` specifies whether the cache should be refreshed by polling the API. """ # TODO Once the watch channel is removed, this can be done in a smarter way, without splitting and overriding # the list_watched_users function. watched_data = await self.prepare_watched_users_data(ctx, oldest_first, update_cache) if update_cache and not watched_data["updated"]: await ctx.send(f":x: Failed to update {self.__class__.__name__} user cache, serving from cache") lines = [] for user_id, line in watched_data["info"].items(): if self.watched_users[user_id]['reviewed']: line += " *(reviewed)*" elif user_id in self.reviewer: line += " *(scheduled)*" lines.append(line) if not lines: lines = ("There's nothing here yet.",) embed = Embed( title=watched_data["title"], color=Color.blue() ) await LinePaginator.paginate(lines, ctx, embed, empty=False) @nomination_group.command(name='oldest') @has_any_role(*MODERATION_ROLES) async def oldest_command(self, ctx: Context, update_cache: bool = True) -> None: """ Shows talent pool monitored users ordered by oldest nomination. The optional kwarg `update_cache` can be used to update the user cache using the API before listing the users. """ await ctx.invoke(self.watched_command, oldest_first=True, update_cache=update_cache) @nomination_group.command(name='forcewatch', aliases=('fw', 'forceadd', 'fa'), root_aliases=("forcenominate",)) @has_any_role(*MODERATION_ROLES) async def force_watch_command(self, ctx: Context, user: FetchedMember, *, reason: str = '') -> None: """ Adds the given `user` to the talent pool, from any channel. A `reason` for adding the user to the talent pool is optional. """ await self._watch_user(ctx, user, reason) @nomination_group.command(name='watch', aliases=('w', 'add', 'a'), root_aliases=("nominate",)) @has_any_role(*STAFF_ROLES) async def watch_command(self, ctx: Context, user: FetchedMember, *, reason: str = '') -> None: """ Adds the given `user` to the talent pool. A `reason` for adding the user to the talent pool is optional. This command can only be used in the `#nominations` channel. """ if ctx.channel.id != Channels.nominations: if any(role.id in MODERATION_ROLES for role in ctx.author.roles): await ctx.send( f":x: Nominations should be run in the <#{Channels.nominations}> channel. " "Use `!tp forcewatch` to override this check." ) else: await ctx.send(f":x: Nominations must be run in the <#{Channels.nominations}> channel") return await self._watch_user(ctx, user, reason) async def _watch_user(self, ctx: Context, user: FetchedMember, reason: str) -> None: """Adds the given user to the talent pool.""" if user.bot: await ctx.send(f":x: I'm sorry {ctx.author}, I'm afraid I can't do that. I only watch humans.") return if isinstance(user, Member) and any(role.id in STAFF_ROLES for role in user.roles): await ctx.send(":x: Nominating staff members, eh? Here's a cookie :cookie:") return if not await self.fetch_user_cache(): await ctx.send(f":x: Failed to update the user cache; can't add {user}") return if len(reason) > REASON_MAX_CHARS: await ctx.send(f":x: Maxiumum allowed characters for the reason is {REASON_MAX_CHARS}.") return # Manual request with `raise_for_status` as False because we want the actual response session = self.bot.api_client.session url = self.bot.api_client._url_for(self.api_endpoint) kwargs = { 'json': { 'actor': ctx.author.id, 'reason': reason, 'user': user.id }, 'raise_for_status': False, } async with session.post(url, **kwargs) as resp: response_data = await resp.json() if resp.status == 400: if response_data.get('user', False): await ctx.send(":x: The specified user can't be found in the database tables") elif response_data.get('actor', False): await ctx.send(":x: You have already nominated this user") return else: resp.raise_for_status() self.watched_users[user.id] = response_data if user.id not in self.reviewer: self.reviewer.schedule_review(user.id) history = await self.bot.api_client.get( self.api_endpoint, params={ "user__id": str(user.id), "active": "false", "ordering": "-inserted_at" } ) msg = f"✅ The nomination for {user} has been added to the talent pool" if history: msg += f"\n\n({len(history)} previous nominations in total)" await ctx.send(msg) @nomination_group.command(name='history', aliases=('info', 'search')) @has_any_role(*MODERATION_ROLES) async def history_command(self, ctx: Context, user: FetchedMember) -> None: """Shows the specified user's nomination history.""" result = await self.bot.api_client.get( self.api_endpoint, params={ 'user__id': str(user.id), 'ordering': "-active,-inserted_at" } ) if not result: await ctx.send(":warning: This user has never been nominated") return embed = Embed( title=f"Nominations for {user.display_name} `({user.id})`", color=Color.blue() ) lines = [self._nomination_to_string(nomination) for nomination in result] await LinePaginator.paginate( lines, ctx=ctx, embed=embed, empty=True, max_lines=3, max_size=1000 ) @nomination_group.command(name='unwatch', aliases=('end', ), root_aliases=("unnominate",)) @has_any_role(*MODERATION_ROLES) async def unwatch_command(self, ctx: Context, user: FetchedMember, *, reason: str) -> None: """ Ends the active nomination of the specified user with the given reason. Providing a `reason` is required. """ if len(reason) > REASON_MAX_CHARS: await ctx.send(f":x: Maxiumum allowed characters for the end reason is {REASON_MAX_CHARS}.") return if await self.unwatch(user.id, reason): await ctx.send(f":white_check_mark: Messages sent by {user} will no longer be relayed") else: await ctx.send(":x: The specified user does not have an active nomination") @nomination_group.group(name='edit', aliases=('e',), invoke_without_command=True) @has_any_role(*MODERATION_ROLES) async def nomination_edit_group(self, ctx: Context) -> None: """Commands to edit nominations.""" await ctx.send_help(ctx.command) @nomination_edit_group.command(name='reason') @has_any_role(*MODERATION_ROLES) async def edit_reason_command(self, ctx: Context, nomination_id: int, actor: FetchedMember, *, reason: str) -> None: """Edits the reason of a specific nominator in a specific active nomination.""" if len(reason) > REASON_MAX_CHARS: await ctx.send(f":x: Maxiumum allowed characters for the reason is {REASON_MAX_CHARS}.") return try: nomination = await self.bot.api_client.get(f"{self.api_endpoint}/{nomination_id}") except ResponseCodeError as e: if e.response.status == 404: self.log.trace(f"Nomination API 404: Can't find a nomination with id {nomination_id}") await ctx.send(f":x: Can't find a nomination with id `{nomination_id}`") return else: raise if not nomination["active"]: await ctx.send(":x: Can't edit the reason of an inactive nomination.") return if not any(entry["actor"] == actor.id for entry in nomination["entries"]): await ctx.send(f":x: {actor} doesn't have an entry in this nomination.") return self.log.trace(f"Changing reason for nomination with id {nomination_id} of actor {actor} to {repr(reason)}") await self.bot.api_client.patch( f"{self.api_endpoint}/{nomination_id}", json={"actor": actor.id, "reason": reason} ) await self.fetch_user_cache() # Update cache await ctx.send(":white_check_mark: Successfully updated nomination reason.") @nomination_edit_group.command(name='end_reason') @has_any_role(*MODERATION_ROLES) async def edit_end_reason_command(self, ctx: Context, nomination_id: int, *, reason: str) -> None: """Edits the unnominate reason for the nomination with the given `id`.""" if len(reason) > REASON_MAX_CHARS: await ctx.send(f":x: Maxiumum allowed characters for the end reason is {REASON_MAX_CHARS}.") return try: nomination = await self.bot.api_client.get(f"{self.api_endpoint}/{nomination_id}") except ResponseCodeError as e: if e.response.status == 404: self.log.trace(f"Nomination API 404: Can't find a nomination with id {nomination_id}") await ctx.send(f":x: Can't find a nomination with id `{nomination_id}`") return else: raise if nomination["active"]: await ctx.send(":x: Can't edit the end reason of an active nomination.") return self.log.trace(f"Changing end reason for nomination with id {nomination_id} to {repr(reason)}") await self.bot.api_client.patch( f"{self.api_endpoint}/{nomination_id}", json={"end_reason": reason} ) await self.fetch_user_cache() # Update cache. await ctx.send(":white_check_mark: Updated the end reason of the nomination!") @nomination_group.command(aliases=('mr',)) @has_any_role(*MODERATION_ROLES) async def mark_reviewed(self, ctx: Context, user_id: int) -> None: """Mark a user's nomination as reviewed and cancel the review task.""" if not await self.reviewer.mark_reviewed(ctx, user_id): return await ctx.send(f"{Emojis.check_mark} The user with ID `{user_id}` was marked as reviewed.") @nomination_group.command(aliases=('gr',)) @has_any_role(*MODERATION_ROLES) async def get_review(self, ctx: Context, user_id: int) -> None: """Get the user's review as a markdown file.""" review = (await self.reviewer.make_review(user_id))[0] if review: file = discord.File(StringIO(review), f"{user_id}_review.md") await ctx.send(file=file) else: await ctx.send(f"There doesn't appear to be an active nomination for {user_id}") @nomination_group.command(aliases=('review',)) @has_any_role(*MODERATION_ROLES) async def post_review(self, ctx: Context, user_id: int) -> None: """Post the automatic review for the user ahead of time.""" if not await self.reviewer.mark_reviewed(ctx, user_id): return await self.reviewer.post_review(user_id, update_database=False) await ctx.message.add_reaction(Emojis.check_mark) @Cog.listener() async def on_member_ban(self, guild: Guild, user: Union[User, Member]) -> None: """Remove `user` from the talent pool after they are banned.""" await self.unwatch(user.id, "User was banned.") @Cog.listener() async def on_raw_reaction_add(self, payload: RawReactionActionEvent) -> None: """ Watch for reactions in the #nomination-voting channel to automate it. Adding a ticket emoji will unpin the message. Adding an incident reaction will archive the message. """ if payload.channel_id != Channels.nomination_voting: return message: PartialMessage = self.bot.get_channel(payload.channel_id).get_partial_message(payload.message_id) emoji = str(payload.emoji) if emoji == "\N{TICKET}": await message.unpin(reason="Admin task created.") elif emoji in {Emojis.incident_actioned, Emojis.incident_unactioned}: log.info(f"Archiving nomination {message.id}") await self.reviewer.archive_vote(message, emoji == Emojis.incident_actioned) async def unwatch(self, user_id: int, reason: str) -> bool: """End the active nomination of a user with the given reason and return True on success.""" active_nomination = await self.bot.api_client.get( self.api_endpoint, params=ChainMap( {"user__id": str(user_id)}, self.api_default_params, ) ) if not active_nomination: log.debug(f"No active nominate exists for {user_id=}") return False log.info(f"Ending nomination: {user_id=} {reason=}") nomination = active_nomination[0] await self.bot.api_client.patch( f"{self.api_endpoint}/{nomination['id']}", json={'end_reason': reason, 'active': False} ) self._remove_user(user_id) self.reviewer.cancel(user_id) return True def _nomination_to_string(self, nomination_object: dict) -> str: """Creates a string representation of a nomination.""" guild = self.bot.get_guild(Guild.id) entries = [] for site_entry in nomination_object["entries"]: actor_id = site_entry["actor"] actor = guild.get_member(actor_id) reason = site_entry["reason"] or "*None*" created = time.format_infraction(site_entry["inserted_at"]) entries.append( f"Actor: {actor.mention if actor else actor_id}\nCreated: {created}\nReason: {reason}" ) entries_string = "\n\n".join(entries) active = nomination_object["active"] start_date = time.format_infraction(nomination_object["inserted_at"]) if active: lines = textwrap.dedent( f""" =============== Status: **Active** Date: {start_date} Nomination ID: `{nomination_object["id"]}` {entries_string} =============== """ ) else: end_date = time.format_infraction(nomination_object["ended_at"]) lines = textwrap.dedent( f""" =============== Status: Inactive Date: {start_date} Nomination ID: `{nomination_object["id"]}` {entries_string} End date: {end_date} Unwatch reason: {nomination_object["end_reason"]} =============== """ ) return lines.strip() def cog_unload(self) -> None: """Cancels all review tasks on cog unload.""" super().cog_unload() self.reviewer.cancel_all()
from turtle import pos import browser import page import re import json PAGE_URL = 'https://www.facebook.com/groups/j2team.community/' TOR_PATH = browser.TOR_PATH.NONE BROWSER_OPTIONS = browser.BROWSER_OPTIONS.CHROME USE_PROXY = False PRIVATE = True SPEED_UP = True HEADLESS = False SCROLL_DOWN = 1 FILTER_CMTS_BY = page.FILTER_CMTS.ALL_COMMENTS VIEW_MORE_CMTS = 0 VIEW_MORE_REPLIES = 2 def get_child_attribute(element, selector, attr): try: element = element.find_element_by_css_selector(selector) return str(element.get_attribute(attr)) except: return '' def get_child_text(element, selector): try: element = element.find_element_by_css_selector(selector) return element.text except: return '' def get_comment_info(comment): cmt_url = get_child_attribute(comment, '._3mf5', 'href') utime = get_child_attribute(comment, 'abbr', 'data-utime') text = get_child_attribute(comment, '._3l3x ', 'textContent') cmt_id = cmt_url.split('=')[-1] if cmt_id == None: cmt_id = comment.get_attribute('data-ft').split(':"')[-1][:-2] user_url = user_id = user_name = 'Acc clone' else: user_url = cmt_url.split('?')[0] user_id = user_url.split('https://www.facebook.com/')[-1].replace('/', '') user_name = get_child_attribute(comment, '._6qw4', 'innerText') return { 'id': cmt_id, 'utime': utime, 'user_url': user_url, 'user_id': user_id, 'user_name': user_name, 'text': text, } while True: driver = browser.setup_driver(PAGE_URL, TOR_PATH, BROWSER_OPTIONS, USE_PROXY, PRIVATE, SPEED_UP, HEADLESS) if driver.current_url in PAGE_URL: if page.load(driver, PAGE_URL, SCROLL_DOWN, FILTER_CMTS_BY, VIEW_MORE_CMTS, VIEW_MORE_REPLIES): break else: print(f"Redirect detected => {"Rerun" if USE_PROXY else "Please use proxy"}\n") driver.close() html_posts = driver.find_elements_by_css_selector(page.POSTS_SELECTOR) file_name = re.findall('\.com/(.*)', PAGE_URL)[0] if ("groups" == file_name.split("/")[0]): file_name = file_name.split("/")[1] html_posts = html_posts[2:-3] else: file_name = file_name.split("/")[0] # print("file name: ", file_name) # debug # import time # time.sleep(5) total = 0 i = 0 post_id = None print('Start crawling', len(html_posts), 'posts...') with open(f'data/{file_name}.json', 'w', encoding='utf-8') as f: for post_index, post in enumerate(html_posts): i += 1 # print(i) if post.text == "": continue # print(post.text) post_url = get_child_attribute(post, 'span.j5wam9gi > span > span > span > a', 'href').split('?')[0] # debug if post_url == "": continue post_id = post_url.split('/')[-2] # print(post_id) utime = get_child_attribute(post, 'abbr', 'data-utime') post_text = get_child_text(post, '.d2edcug0.hpfvmrgz.qv66sw1b.c1et5uql.lr9zc1uh.a8c37x1j.fe6kdd0r.mau55g9w.c8b282yb.keod5gw0.nxhoafnm.aigsh9s9.d3f4x2em.iv3no6db.jq4qci2q.a3bd9o3v.b1v8xokw.oo9gr5id') # print(post_text) cmt_share = post.find_elements_by_css_selector('.d2edcug0.hpfvmrgz.qv66sw1b.c1et5uql.lr9zc1uh.a8c37x1j.fe6kdd0r.mau55g9w.c8b282yb.keod5gw0.nxhoafnm.aigsh9s9.d3f4x2em.iv3no6db.jq4qci2q.a3bd9o3v.b1v8xokw.m9osqain') if len(cmt_share) == 3: total_shares = cmt_share[2].text.split(" ")[0] total_cmts = cmt_share[1].text.split(" ")[0] elif len(cmt_share) == 2: if "bình luận" in cmt_share[1].text: total_shares = 0 total_cmts = cmt_share[1].text.split(" ")[0] else: total_cmts = 0 total_shares = cmt_share[1].text.split(" ")[0] else: total_shares = 0 total_cmts = 0 json_cmts = [] html_cmts = post.find_elements_by_css_selector('.monazrh9 > div > div > ul > li') num_of_cmts = len(html_cmts) total += num_of_cmts if num_of_cmts > 0: print(f'{post_index}. Crawling {num_of_cmts} comments of post {post_id}') for comment in html_cmts: comment_owner = comment.find_element_by_css_selector('div') comment_info = get_comment_info(comment_owner) json_replies = [] html_replies = comment.find_elements_by_css_selector('._7a9g') num_of_replies = len(html_replies) total += num_of_replies if num_of_replies > 0: print(f"|-- Crawling {num_of_replies} replies of {comment_info["user_name"]}'s comment") for reply in html_replies: reply_info = get_comment_info(reply) json_replies.append(reply_info) comment_info.update({'replies': json_replies}) json_cmts.append(comment_info) json_reacts = [] html_reacts = post.find_elements_by_css_selector('._1n9l') for react in html_reacts: react_text = react.get_attribute('aria-label') json_reacts.append(react_text) json.dump({ 'url': post_url, 'id': post_id, 'utime': utime, 'text': post_text, 'reactions': json_reacts, 'total_shares': total_shares, 'total_cmts': total_cmts, 'crawled_cmts': json_cmts, }, f, ensure_ascii=False) del json_cmts f.write('\n') del html_posts print('Total comments and replies crawled:', total) # browser.close()
from turtle import pos import browser import page import re import json PAGE_URL = 'https://www.facebook.com/groups/j2team.community/' TOR_PATH = browser.TOR_PATH.NONE BROWSER_OPTIONS = browser.BROWSER_OPTIONS.CHROME USE_PROXY = False PRIVATE = True SPEED_UP = True HEADLESS = False SCROLL_DOWN = 1 FILTER_CMTS_BY = page.FILTER_CMTS.ALL_COMMENTS VIEW_MORE_CMTS = 0 VIEW_MORE_REPLIES = 2 def get_child_attribute(element, selector, attr): try: element = element.find_element_by_css_selector(selector) return str(element.get_attribute(attr)) except: return '' def get_child_text(element, selector): try: element = element.find_element_by_css_selector(selector) return element.text except: return '' def get_comment_info(comment): cmt_url = get_child_attribute(comment, '._3mf5', 'href') utime = get_child_attribute(comment, 'abbr', 'data-utime') text = get_child_attribute(comment, '._3l3x ', 'textContent') cmt_id = cmt_url.split('=')[-1] if cmt_id == None: cmt_id = comment.get_attribute('data-ft').split(':"')[-1][:-2] user_url = user_id = user_name = 'Acc clone' else: user_url = cmt_url.split('?')[0] user_id = user_url.split('https://www.facebook.com/')[-1].replace('/', '') user_name = get_child_attribute(comment, '._6qw4', 'innerText') return { 'id': cmt_id, 'utime': utime, 'user_url': user_url, 'user_id': user_id, 'user_name': user_name, 'text': text, } while True: driver = browser.setup_driver(PAGE_URL, TOR_PATH, BROWSER_OPTIONS, USE_PROXY, PRIVATE, SPEED_UP, HEADLESS) if driver.current_url in PAGE_URL: if page.load(driver, PAGE_URL, SCROLL_DOWN, FILTER_CMTS_BY, VIEW_MORE_CMTS, VIEW_MORE_REPLIES): break else: print(f"Redirect detected => {'Rerun' if USE_PROXY else 'Please use proxy'}\n") driver.close() html_posts = driver.find_elements_by_css_selector(page.POSTS_SELECTOR) file_name = re.findall('\.com/(.*)', PAGE_URL)[0] if ("groups" == file_name.split("/")[0]): file_name = file_name.split("/")[1] html_posts = html_posts[2:-3] else: file_name = file_name.split("/")[0] # print("file name: ", file_name) # debug # import time # time.sleep(5) total = 0 i = 0 post_id = None print('Start crawling', len(html_posts), 'posts...') with open(f'data/{file_name}.json', 'w', encoding='utf-8') as f: for post_index, post in enumerate(html_posts): i += 1 # print(i) if post.text == "": continue # print(post.text) post_url = get_child_attribute(post, 'span.j5wam9gi > span > span > span > a', 'href').split('?')[0] # debug if post_url == "": continue post_id = post_url.split('/')[-2] # print(post_id) utime = get_child_attribute(post, 'abbr', 'data-utime') post_text = get_child_text(post, '.d2edcug0.hpfvmrgz.qv66sw1b.c1et5uql.lr9zc1uh.a8c37x1j.fe6kdd0r.mau55g9w.c8b282yb.keod5gw0.nxhoafnm.aigsh9s9.d3f4x2em.iv3no6db.jq4qci2q.a3bd9o3v.b1v8xokw.oo9gr5id') # print(post_text) cmt_share = post.find_elements_by_css_selector('.d2edcug0.hpfvmrgz.qv66sw1b.c1et5uql.lr9zc1uh.a8c37x1j.fe6kdd0r.mau55g9w.c8b282yb.keod5gw0.nxhoafnm.aigsh9s9.d3f4x2em.iv3no6db.jq4qci2q.a3bd9o3v.b1v8xokw.m9osqain') if len(cmt_share) == 3: total_shares = cmt_share[2].text.split(" ")[0] total_cmts = cmt_share[1].text.split(" ")[0] elif len(cmt_share) == 2: if "bình luận" in cmt_share[1].text: total_shares = 0 total_cmts = cmt_share[1].text.split(" ")[0] else: total_cmts = 0 total_shares = cmt_share[1].text.split(" ")[0] else: total_shares = 0 total_cmts = 0 json_cmts = [] html_cmts = post.find_elements_by_css_selector('.monazrh9 > div > div > ul > li') num_of_cmts = len(html_cmts) total += num_of_cmts if num_of_cmts > 0: print(f'{post_index}. Crawling {num_of_cmts} comments of post {post_id}') for comment in html_cmts: comment_owner = comment.find_element_by_css_selector('div') comment_info = get_comment_info(comment_owner) json_replies = [] html_replies = comment.find_elements_by_css_selector('._7a9g') num_of_replies = len(html_replies) total += num_of_replies if num_of_replies > 0: print(f"|-- Crawling {num_of_replies} replies of {comment_info['user_name']}'s comment") for reply in html_replies: reply_info = get_comment_info(reply) json_replies.append(reply_info) comment_info.update({'replies': json_replies}) json_cmts.append(comment_info) json_reacts = [] html_reacts = post.find_elements_by_css_selector('._1n9l') for react in html_reacts: react_text = react.get_attribute('aria-label') json_reacts.append(react_text) json.dump({ 'url': post_url, 'id': post_id, 'utime': utime, 'text': post_text, 'reactions': json_reacts, 'total_shares': total_shares, 'total_cmts': total_cmts, 'crawled_cmts': json_cmts, }, f, ensure_ascii=False) del json_cmts f.write('\n') del html_posts print('Total comments and replies crawled:', total) # browser.close()
""" Most of this code comes from the timm library. We tried to disentangle from the timm library version. Adapted from https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py """ import math import logging import warnings from functools import partial from collections import OrderedDict from copy import deepcopy import torch import torch.nn as nn import torch.nn.functional as F from timm.models.layers.helpers import to_2tuple from .helpers.vit_helpers import update_default_cfg_and_kwargs, DropPath, trunc_normal_, build_model_with_cfg _logger = logging.getLogger() IMAGENET_DEFAULT_MEAN = (0.485, 0.456, 0.406) IMAGENET_DEFAULT_STD = (0.229, 0.224, 0.225) IMAGENET_INCEPTION_MEAN = (0.5, 0.5, 0.5) IMAGENET_INCEPTION_STD = (0.5, 0.5, 0.5) def _cfg(url='', **kwargs): return { 'url': url, 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': None, 'crop_pct': .9, 'interpolation': 'bicubic', 'fixed_input_size': True, 'mean': IMAGENET_INCEPTION_MEAN, 'std': IMAGENET_INCEPTION_STD, 'first_conv': 'patch_embed.proj', 'classifier': 'head', **kwargs } default_cfgs = { # patch models (weights from official Google JAX impl) 'vit_tiny_patch16_224': _cfg( url='https://storage.googleapis.com/vit_models/augreg/' 'Ti_16-i21k-300ep-lr_0.001-aug_none-wd_0.03-do_0.0-sd_0.0--imagenet2012-steps_20k-lr_0.03-res_224.npz'), 'vit_tiny_patch16_384': _cfg( url='https://storage.googleapis.com/vit_models/augreg/' 'Ti_16-i21k-300ep-lr_0.001-aug_none-wd_0.03-do_0.0-sd_0.0--imagenet2012-steps_20k-lr_0.03-res_384.npz', input_size=(3, 384, 384), crop_pct=1.0), 'vit_small_patch32_224': _cfg( url='https://storage.googleapis.com/vit_models/augreg/' 'S_32-i21k-300ep-lr_0.001-aug_light1-wd_0.03-do_0.0-sd_0.0--imagenet2012-steps_20k-lr_0.03-res_224.npz'), 'vit_small_patch32_384': _cfg( url='https://storage.googleapis.com/vit_models/augreg/' 'S_32-i21k-300ep-lr_0.001-aug_light1-wd_0.03-do_0.0-sd_0.0--imagenet2012-steps_20k-lr_0.03-res_384.npz', input_size=(3, 384, 384), crop_pct=1.0), 'vit_small_patch16_224': _cfg( url='https://storage.googleapis.com/vit_models/augreg/' 'S_16-i21k-300ep-lr_0.001-aug_light1-wd_0.03-do_0.0-sd_0.0--imagenet2012-steps_20k-lr_0.03-res_224.npz'), 'vit_small_patch16_384': _cfg( url='https://storage.googleapis.com/vit_models/augreg/' 'S_16-i21k-300ep-lr_0.001-aug_light1-wd_0.03-do_0.0-sd_0.0--imagenet2012-steps_20k-lr_0.03-res_384.npz', input_size=(3, 384, 384), crop_pct=1.0), 'vit_base_patch32_224': _cfg( url='https://storage.googleapis.com/vit_models/augreg/' 'B_32-i21k-300ep-lr_0.001-aug_medium1-wd_0.03-do_0.0-sd_0.0--imagenet2012-steps_20k-lr_0.03-res_224.npz'), 'vit_base_patch32_384': _cfg( url='https://storage.googleapis.com/vit_models/augreg/' 'B_32-i21k-300ep-lr_0.001-aug_light1-wd_0.1-do_0.0-sd_0.0--imagenet2012-steps_20k-lr_0.03-res_384.npz', input_size=(3, 384, 384), crop_pct=1.0), 'vit_base_patch16_224': _cfg( url='https://storage.googleapis.com/vit_models/augreg/' 'B_16-i21k-300ep-lr_0.001-aug_medium1-wd_0.1-do_0.0-sd_0.0--imagenet2012-steps_20k-lr_0.01-res_224.npz'), 'vit_base_patch16_384': _cfg( url='https://storage.googleapis.com/vit_models/augreg/' 'B_16-i21k-300ep-lr_0.001-aug_medium1-wd_0.1-do_0.0-sd_0.0--imagenet2012-steps_20k-lr_0.01-res_384.npz', input_size=(3, 384, 384), crop_pct=1.0), 'vit_large_patch32_224': _cfg( url='', # no official model weights for this combo, only for in21k ), 'vit_large_patch32_384': _cfg( url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-vitjx/jx_vit_large_p32_384-9b920ba8.pth', input_size=(3, 384, 384), crop_pct=1.0), 'vit_large_patch16_224': _cfg( url='https://storage.googleapis.com/vit_models/augreg/' 'L_16-i21k-300ep-lr_0.001-aug_medium1-wd_0.1-do_0.1-sd_0.1--imagenet2012-steps_20k-lr_0.01-res_224.npz'), 'vit_large_patch16_384': _cfg( url='https://storage.googleapis.com/vit_models/augreg/' 'L_16-i21k-300ep-lr_0.001-aug_medium1-wd_0.1-do_0.1-sd_0.1--imagenet2012-steps_20k-lr_0.01-res_384.npz', input_size=(3, 384, 384), crop_pct=1.0), # patch models, imagenet21k (weights from official Google JAX impl) 'vit_tiny_patch16_224_in21k': _cfg( url='https://storage.googleapis.com/vit_models/augreg/Ti_16-i21k-300ep-lr_0.001-aug_none-wd_0.03-do_0.0-sd_0.0.npz', num_classes=21843), 'vit_small_patch32_224_in21k': _cfg( url='https://storage.googleapis.com/vit_models/augreg/S_32-i21k-300ep-lr_0.001-aug_light1-wd_0.03-do_0.0-sd_0.0.npz', num_classes=21843), 'vit_small_patch16_224_in21k': _cfg( url='https://storage.googleapis.com/vit_models/augreg/S_16-i21k-300ep-lr_0.001-aug_light1-wd_0.03-do_0.0-sd_0.0.npz', num_classes=21843), 'vit_base_patch32_224_in21k': _cfg( url='https://storage.googleapis.com/vit_models/augreg/B_32-i21k-300ep-lr_0.001-aug_medium1-wd_0.03-do_0.0-sd_0.0.npz', num_classes=21843), 'vit_base_patch16_224_in21k': _cfg( url='https://storage.googleapis.com/vit_models/augreg/B_16-i21k-300ep-lr_0.001-aug_medium1-wd_0.1-do_0.0-sd_0.0.npz', num_classes=21843), 'vit_large_patch32_224_in21k': _cfg( url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-vitjx/jx_vit_large_patch32_224_in21k-9046d2e7.pth', num_classes=21843), 'vit_large_patch16_224_in21k': _cfg( url='https://storage.googleapis.com/vit_models/augreg/L_16-i21k-300ep-lr_0.001-aug_medium1-wd_0.1-do_0.1-sd_0.1.npz', num_classes=21843), 'vit_huge_patch14_224_in21k': _cfg( url='https://storage.googleapis.com/vit_models/imagenet21k/ViT-H_14.npz', hf_hub='timm/vit_huge_patch14_224_in21k', num_classes=21843), # SAM trained models (https://arxiv.org/abs/2106.01548) 'vit_base_patch32_sam_224': _cfg( url='https://storage.googleapis.com/vit_models/sam/ViT-B_32.npz'), 'vit_base_patch16_sam_224': _cfg( url='https://storage.googleapis.com/vit_models/sam/ViT-B_16.npz'), # deit models (FB weights) 'deit_tiny_patch16_224': _cfg( url='https://dl.fbaipublicfiles.com/deit/deit_tiny_patch16_224-a1311bcf.pth', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD), 'deit_small_patch16_224': _cfg( url='https://dl.fbaipublicfiles.com/deit/deit_small_patch16_224-cd65a155.pth', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD), 'deit_base_patch16_224': _cfg( url='https://dl.fbaipublicfiles.com/deit/deit_base_patch16_224-b5f2ef4d.pth', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD), 'deit_base_patch16_384': _cfg( url='https://dl.fbaipublicfiles.com/deit/deit_base_patch16_384-8de9b5d1.pth', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, input_size=(3, 384, 384), crop_pct=1.0), 'deit_tiny_distilled_patch16_224': _cfg( url='https://dl.fbaipublicfiles.com/deit/deit_tiny_distilled_patch16_224-b40b3cf7.pth', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, classifier=('head', 'head_dist')), 'deit_small_distilled_patch16_224': _cfg( url='https://dl.fbaipublicfiles.com/deit/deit_small_distilled_patch16_224-649709d9.pth', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, classifier=('head', 'head_dist')), 'deit_base_distilled_patch16_224': _cfg( url='https://dl.fbaipublicfiles.com/deit/deit_base_distilled_patch16_224-df68dfff.pth', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, classifier=('head', 'head_dist')), 'deit_base_distilled_patch16_384': _cfg( url='https://dl.fbaipublicfiles.com/deit/deit_base_distilled_patch16_384-d0272ac0.pth', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, input_size=(3, 384, 384), crop_pct=1.0, classifier=('head', 'head_dist')), # ViT ImageNet-21K-P pretraining by MILL 'vit_base_patch16_224_miil_in21k': _cfg( url='https://miil-public-eu.oss-eu-central-1.aliyuncs.com/model-zoo/ImageNet_21K_P/models/timm/vit_base_patch16_224_in21k_miil.pth', mean=(0, 0, 0), std=(1, 1, 1), crop_pct=0.875, interpolation='bilinear', num_classes=11221, ), 'vit_base_patch16_224_miil': _cfg( url='https://miil-public-eu.oss-eu-central-1.aliyuncs.com/model-zoo/ImageNet_21K_P/models/timm' '/vit_base_patch16_224_1k_miil_84_4.pth', mean=(0, 0, 0), std=(1, 1, 1), crop_pct=0.875, interpolation='bilinear', ), # PaSST 'passt_s_swa_p16_128_ap476': _cfg( url='https://github.com/kkoutini/PaSST/releases/download/v0.0.1-audioset/passt-s-f128-p16-s10-ap.476-swa.pt', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, input_size=(1, 128, 998), crop_pct=1.0, classifier=('head.1', 'head_dist'), num_classes=527), 'passt_s_swa_p16_128_ap4761': _cfg( url='https://github.com/kkoutini/PaSST/releases/download/v0.0.2-audioset/passt-s-f128-p16-s10-ap.4761-swa.pt', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, input_size=(1, 128, 998), crop_pct=1.0, classifier=('head.1', 'head_dist'), num_classes=527), 'passt_s_p16_128_ap472': _cfg( url='https://github.com/kkoutini/PaSST/releases/download/v0.0.2-audioset/passt-s-f128-p16-s10-ap.472.pt', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, input_size=(1, 128, 998), crop_pct=1.0, classifier=('head.1', 'head_dist'), num_classes=527), 'passt_s_p16_s16_128_ap468': _cfg( url='https://github.com/kkoutini/PaSST/releases/download/v0.0.2-audioset/passt-s-f128-p16-s16-ap.468.pt', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, input_size=(1, 128, 998), crop_pct=1.0, classifier=('head.1', 'head_dist'), num_classes=527), 'passt_s_swa_p16_s16_128_ap473': _cfg( url='https://github.com/kkoutini/PaSST/releases/download/v0.0.2-audioset/passt-s-f128-p16-s16-ap.473-swa.pt', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, input_size=(1, 128, 998), crop_pct=1.0, classifier=('head.1', 'head_dist'), num_classes=527), 'passt_s_swa_p16_s14_128_ap471': _cfg( url='https://github.com/kkoutini/PaSST/releases/download/v0.0.2-audioset/passt-s-f128-p16-s14-ap.471-swa.pt', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, input_size=(1, 128, 998), crop_pct=1.0, classifier=('head.1', 'head_dist'), num_classes=527), 'passt_s_p16_s14_128_ap469': _cfg( url='https://github.com/kkoutini/PaSST/releases/download/v0.0.2-audioset/passt-s-f128-p16-s14-ap.469.pt', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, input_size=(1, 128, 998), crop_pct=1.0, classifier=('head.1', 'head_dist'), num_classes=527), 'passt_s_swa_p16_s12_128_ap473': _cfg( url='https://github.com/kkoutini/PaSST/releases/download/v0.0.2-audioset/passt-s-f128-p16-s12-ap.473-swa.pt', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, input_size=(1, 128, 998), crop_pct=1.0, classifier=('head.1', 'head_dist'), num_classes=527), 'passt_s_p16_s12_128_ap470': _cfg( url='https://github.com/kkoutini/PaSST/releases/download/v0.0.2-audioset/passt-s-f128-p16-s12-ap.470.pt', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, input_size=(1, 128, 998), crop_pct=1.0, classifier=('head.1', 'head_dist'), num_classes=527), 'passt_s_swa_f128_stfthop100_p16_s10_ap473': _cfg( url='https://github.com/kkoutini/PaSST/releases/download/v0.0.3-audioset/passt-s-f128-stfthop100-p16-s10-ap.473-swa.pt', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, input_size=(1, 128, 3200), crop_pct=1.0, classifier=('head.1', 'head_dist'), num_classes=527), 'passt_s_swa_f128_stfthop160_p16_s10_ap473': _cfg( url='https://github.com/kkoutini/PaSST/releases/download/v0.0.3-audioset/passt-s-f128-stfthop160-p16-s10-ap.473-swa.pt', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, input_size=(1, 128, 2000), crop_pct=1.0, classifier=('head.1', 'head_dist'), num_classes=527), 'passt-s-f128-20sec-p16-s10-ap474-swa': _cfg( url='https://github.com/kkoutini/PaSST/releases/download/v0.0.3-audioset/passt-s-f128-20sec-p16-s10-ap.474-swa.pt', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, input_size=(1, 128, 2000), crop_pct=1.0, classifier=('head.1', 'head_dist'), num_classes=527), 'passt-s-f128-30sec-p16-s10-ap473-swa': _cfg( url='https://github.com/kkoutini/PaSST/releases/download/v0.0.3-audioset/passt-s-f128-30sec-p16-s10-ap.473-swa.pt', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, input_size=(1, 128, 3000), crop_pct=1.0, classifier=('head.1', 'head_dist'), num_classes=527), 'openmic2008_passt_u_f128_p16_s10_ap85_swa': _cfg( url='https://github.com/kkoutini/PaSST/releases/download/v0.0.4-openmic/openmic2008.passt-u-f128-p16-s10-ap.85-swa.pt', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, input_size=(1, 128, 3200), crop_pct=1.0, classifier=('head.1', 'head_dist'), num_classes=20), 'openmic2008_passt_u_f128_p16_s10_ap85 ': _cfg( url='https://github.com/kkoutini/PaSST/releases/download/v0.0.4-openmic/openmic2008.passt-u-f128-p16-s10-ap.85.pt', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, input_size=(1, 128, 2000), crop_pct=1.0, classifier=('head.1', 'head_dist'), num_classes=20), } def adapt_input_conv(in_chans, conv_weight): conv_type = conv_weight.dtype conv_weight = conv_weight.float() # Some weights are in torch.half, ensure it's float for sum on CPU O, I, J, K = conv_weight.shape if in_chans == 1: if I > 3: assert conv_weight.shape[1] % 3 == 0 # For models with space2depth stems conv_weight = conv_weight.reshape(O, I // 3, 3, J, K) conv_weight = conv_weight.sum(dim=2, keepdim=False) else: conv_weight = conv_weight.sum(dim=1, keepdim=True) elif in_chans != 3: if I != 3: raise NotImplementedError('Weight format not supported by conversion.') else: # NOTE this strategy should be better than random init, but there could be other combinations of # the original RGB input layer weights that'd work better for specific cases. repeat = int(math.ceil(in_chans / 3)) conv_weight = conv_weight.repeat(1, repeat, 1, 1)[:, :in_chans, :, :] conv_weight *= (3 / float(in_chans)) conv_weight = conv_weight.to(conv_type) return conv_weight class Mlp(nn.Module): """ MLP as used in Vision Transformer, MLP-Mixer and related networks """ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.): super().__init__() out_features = out_features or in_features hidden_features = hidden_features or in_features self.fc1 = nn.Linear(in_features, hidden_features) self.act = act_layer() self.fc2 = nn.Linear(hidden_features, out_features) self.drop = nn.Dropout(drop) def forward(self, x): x = self.fc1(x) x = self.act(x) x = self.drop(x) x = self.fc2(x) x = self.drop(x) return x first_RUN = True class PatchEmbed(nn.Module): """ 2D Image to Patch Embedding """ def __init__(self, img_size=224, patch_size=16, stride=16, in_chans=3, embed_dim=768, norm_layer=None, flatten=True): super().__init__() img_size = to_2tuple(img_size) patch_size = to_2tuple(patch_size) stride = to_2tuple(stride) self.img_size = img_size self.patch_size = patch_size self.stride = stride self.grid_size = (img_size[0] // stride[0], img_size[1] // stride[1]) self.num_patches = self.grid_size[0] * self.grid_size[1] self.flatten = flatten self.embed_dim = embed_dim self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=stride) self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity() def forward(self, x): B, C, H, W = x.shape if not (H == self.img_size[0] and W == self.img_size[1]): warnings.warn(f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]}).") # to do maybe replace weights x = self.proj(x) if self.flatten: x = x.flatten(2).transpose(1, 2) # BCHW -> BNC x = self.norm(x) if first_RUN: print("self.norm(x)", x.size()) return x class Attention(nn.Module): def __init__(self, dim, num_heads=8, qkv_bias=False, attn_drop=0., proj_drop=0.): super().__init__() self.num_heads = num_heads head_dim = dim // num_heads self.scale = head_dim ** -0.5 self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) self.attn_drop = nn.Dropout(attn_drop) self.proj = nn.Linear(dim, dim) self.proj_drop = nn.Dropout(proj_drop) def forward(self, x): B, N, C = x.shape qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple) attn = (q @ k.transpose(-2, -1)) * self.scale attn = attn.softmax(dim=-1) attn = self.attn_drop(attn) x = (attn @ v).transpose(1, 2).reshape(B, N, C) x = self.proj(x) x = self.proj_drop(x) return x class Block(nn.Module): def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, drop=0., attn_drop=0., drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm): super().__init__() self.norm1 = norm_layer(dim) self.attn = Attention(dim, num_heads=num_heads, qkv_bias=qkv_bias, attn_drop=attn_drop, proj_drop=drop) # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() self.norm2 = norm_layer(dim) mlp_hidden_dim = int(dim * mlp_ratio) self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) def forward(self, x): x = x + self.drop_path(self.attn(self.norm1(x))) x = x + self.drop_path(self.mlp(self.norm2(x))) return x class PaSST(nn.Module): """ Based on the implementation of Vision Transformer in timm library. Take a look at the get_model function, adapting the weights of pretrained imagenet models. """ def __init__(self, u_patchout=0, s_patchout_t=0, s_patchout_f=0, img_size=(128, 998), patch_size=16, stride=16, in_chans=1, num_classes=527, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4., qkv_bias=True, representation_size=None, distilled=False, drop_rate=0., attn_drop_rate=0., drop_path_rate=0., embed_layer=PatchEmbed, norm_layer=None, act_layer=None, weight_init=''): """ Args: u_patchout: Unstructured Patchout integer, number of items to be removed from the final sequence s_patchout_t: structured Patchout time integer, number of columns to be removed from the patches grid s_patchout_f: structured Patchout Frequency integer, number of rows to be removed from the patches grid img_size (int, tuple): input image size patch_size (int, tuple): patch size in_chans (int): number of input channels num_classes (int): number of classes for classification head embed_dim (int): embedding dimension depth (int): depth of transformer num_heads (int): number of attention heads mlp_ratio (int): ratio of mlp hidden dim to embedding dim qkv_bias (bool): enable bias for qkv if True representation_size (Optional[int]): enable and set representation layer (pre-logits) to this value if set distilled (bool): model includes a distillation token and head as in DeiT models drop_rate (float): dropout rate attn_drop_rate (float): attention dropout rate drop_path_rate (float): stochastic depth rate embed_layer (nn.Module): patch embedding layer norm_layer: (nn.Module): normalization layer weight_init: (str): weight init scheme """ super().__init__() self.num_classes = num_classes self.u_patchout = u_patchout self.s_patchout_t = s_patchout_t self.s_patchout_f = s_patchout_f self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models self.num_tokens = 2 if distilled else 1 norm_layer = norm_layer or partial(nn.LayerNorm, eps=1e-6) act_layer = act_layer or nn.GELU self.patch_embed = embed_layer( img_size=img_size, patch_size=patch_size, stride=stride, in_chans=in_chans, embed_dim=embed_dim, flatten=False) num_patches = self.patch_embed.num_patches self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) self.dist_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) if distilled else None # PaSST # refer to https://arxiv.org/abs/2110.05069 Section 2 self.new_pos_embed = nn.Parameter(torch.zeros(1, self.num_tokens, embed_dim)) # for C and D tokens self.freq_new_pos_embed = nn.Parameter(torch.zeros(1, embed_dim, self.patch_embed.grid_size[0], 1)) # | f self.time_new_pos_embed = nn.Parameter(torch.zeros(1, embed_dim, 1, self.patch_embed.grid_size[1])) # __ t #### self.pos_drop = nn.Dropout(p=drop_rate) dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule self.blocks = nn.Sequential(*[ Block( dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer, act_layer=act_layer) for i in range(depth)]) self.norm = norm_layer(embed_dim) # Representation layer if representation_size and not distilled: self.num_features = representation_size self.pre_logits = nn.Sequential(OrderedDict([ ('fc', nn.Linear(embed_dim, representation_size)), ('act', nn.Tanh()) ])) else: self.pre_logits = nn.Identity() # Classifier head(s) self.head = nn.Sequential(nn.LayerNorm(self.num_features), nn.Linear(self.num_features, num_classes) if num_classes > 0 else nn.Identity()) self.head_dist = None if distilled: self.head_dist = nn.Linear(self.embed_dim, self.num_classes) if num_classes > 0 else nn.Identity() self.init_weights(weight_init) def init_weights(self, mode=''): assert mode in ('jax', 'jax_nlhb', 'nlhb', '') head_bias = -math.log(self.num_classes) if 'nlhb' in mode else 0. trunc_normal_(self.new_pos_embed, std=.02) trunc_normal_(self.freq_new_pos_embed, std=.02) trunc_normal_(self.time_new_pos_embed, std=.02) if self.dist_token is not None: trunc_normal_(self.dist_token, std=.02) if mode.startswith('jax'): # leave cls token as zeros to match jax impl raise RuntimeError("Not supported yet") else: trunc_normal_(self.cls_token, std=.02) self.apply(_init_vit_weights) def _init_weights(self, m): # this fn left here for compat with downstream users _init_vit_weights(m) @torch.jit.ignore def no_weight_decay(self): return {'new_pos_embed', 'freq_new_pos_embed', 'time_new_pos_embed', 'cls_token', 'dist_token'} def get_classifier(self): if self.dist_token is None: return self.head else: return self.head, self.head_dist def reset_classifier(self, num_classes, global_pool=''): self.num_classes = num_classes self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity() if self.num_tokens == 2: self.head_dist = nn.Linear(self.embed_dim, self.num_classes) if num_classes > 0 else nn.Identity() def forward_features(self, x): global first_RUN # not jit friendly? use trace instead x = self.patch_embed(x) # [b, e, f, t] B_dim, E_dim, F_dim, T_dim = x.shape # slow if first_RUN: print(" patch_embed : ", x.shape) # Adding Time/Freq information if first_RUN: print(" self.time_new_pos_embed.shape", self.time_new_pos_embed.shape) time_new_pos_embed = self.time_new_pos_embed if x.shape[-1] < time_new_pos_embed.shape[-1]: if self.training: toffset = torch.randint(1 + time_new_pos_embed.shape[-1] - x.shape[-1], (1,)).item() if first_RUN: print(f" CUT with randomoffset={toffset} time_new_pos_embed.shape", time_new_pos_embed.shape) time_new_pos_embed = time_new_pos_embed[:, :, :, toffset:toffset + x.shape[-1]] else: time_new_pos_embed = time_new_pos_embed[:, :, :, :x.shape[-1]] if first_RUN: print(" CUT time_new_pos_embed.shape", time_new_pos_embed.shape) else: warnings.warn( f"the patches shape:{x.shape} are larger than the expected time encodings {time_new_pos_embed.shape}, x will be cut") x = x[:, :, :, :time_new_pos_embed.shape[-1]] x = x + time_new_pos_embed if first_RUN: print(" self.freq_new_pos_embed.shape", self.freq_new_pos_embed.shape) x = x + self.freq_new_pos_embed # Structured Patchout https://arxiv.org/abs/2110.05069 Section 2.2 if self.training and self.s_patchout_t: if first_RUN: print(f"X Before time Patchout of {self.s_patchout_t} ", x.size()) # ([1, 768, 1, 82]) random_indices = torch.randperm(T_dim)[:T_dim - self.s_patchout_t].sort().values x = x[:, :, :, random_indices] if first_RUN: print("X after time Patchout", x.size()) if self.training and self.s_patchout_f: if first_RUN: print(f"X Before Freq Patchout of {self.s_patchout_f} ", x.size()) # [1, 768, 12, 1] random_indices = torch.randperm(F_dim)[:F_dim - self.s_patchout_f].sort().values x = x[:, :, random_indices, :] if first_RUN: print(" \n X after freq Patchout: ", x.size()) ### # Flatten the sequence x = x.flatten(2).transpose(1, 2) # Unstructured Patchout if first_RUN: print("X flattened", x.size()) if self.training and self.u_patchout: seq_len = x.shape[1] random_indices = torch.randperm(seq_len)[:seq_len - self.u_patchout].sort().values x = x[:, random_indices, :] if first_RUN: print("X After Unstructured Patchout", x.size()) #### # Add the C/D tokens if first_RUN: print(" self.new_pos_embed.shape", self.new_pos_embed.shape) cls_tokens = self.cls_token.expand(B_dim, -1, -1) + self.new_pos_embed[:, :1, :] if first_RUN: print(" self.cls_tokens.shape", cls_tokens.shape) if self.dist_token is None: x = torch.cat((cls_tokens, x), dim=1) else: dist_token = self.dist_token.expand(B_dim, -1, -1) + self.new_pos_embed[:, 1:, :] if first_RUN: print(" self.dist_token.shape", dist_token.shape) x = torch.cat((cls_tokens, dist_token, x), dim=1) if first_RUN: print(" final sequence x", x.shape) x = self.pos_drop(x) x = self.blocks(x) if first_RUN: print(f" after {len(self.blocks)} atten blocks x", x.shape) x = self.norm(x) if self.dist_token is None: return self.pre_logits(x[:, 0]) else: return x[:, 0], x[:, 1] def forward(self, x): global first_RUN if first_RUN: print("x", x.size()) x = self.forward_features(x) if self.head_dist is not None: features = (x[0] + x[1]) / 2 if first_RUN: print("forward_features", features.size()) x = self.head(features) if first_RUN: print("head", x.size()) first_RUN = False return x, features else: features = x if first_RUN: print("forward_features", features.size()) x = self.head(x) if first_RUN: print("head", x.size()) first_RUN = False return x, features def _init_vit_weights(module: nn.Module, name: str = '', head_bias: float = 0., jax_impl: bool = False): """ ViT weight initialization * When called without n, head_bias, jax_impl args it will behave exactly the same as my original init for compatibility with prev hparam / downstream use cases (ie DeiT). * When called w/ valid n (module name) and jax_impl=True, will (hopefully) match JAX impl """ if isinstance(module, nn.Linear): if name.startswith('head'): nn.init.zeros_(module.weight) nn.init.constant_(module.bias, head_bias) elif name.startswith('pre_logits'): lecun_normal_(module.weight) nn.init.zeros_(module.bias) else: if jax_impl: nn.init.xavier_uniform_(module.weight) if module.bias is not None: if 'mlp' in name: nn.init.normal_(module.bias, std=1e-6) else: nn.init.zeros_(module.bias) else: trunc_normal_(module.weight, std=.02) if module.bias is not None: nn.init.zeros_(module.bias) elif jax_impl and isinstance(module, nn.Conv2d): # NOTE conv was left to pytorch default in my original init lecun_normal_(module.weight) if module.bias is not None: nn.init.zeros_(module.bias) elif isinstance(module, (nn.LayerNorm, nn.GroupNorm, nn.BatchNorm2d)): nn.init.zeros_(module.bias) nn.init.ones_(module.weight) def resize_pos_embed(posemb, posemb_new, num_tokens=1, gs_new=(), mode='bicubic'): # Rescale the grid of position embeddings when loading from state_dict. Adapted from # https://github.com/google-research/vision_transformer/blob/00883dd691c63a6830751563748663526e811cee/vit_jax/checkpoint.py#L224 _logger.info('Resized position embedding: %s to %s with %s cls/dis tokens', posemb.shape, posemb_new.shape, num_tokens) ntok_new = posemb_new.shape[1] if num_tokens: posemb_tok, posemb_grid = posemb[:, :num_tokens], posemb[0, num_tokens:] ntok_new -= num_tokens else: posemb_tok, posemb_grid = posemb[:, :0], posemb[0] gs_old = int(math.sqrt(len(posemb_grid))) if not len(gs_new): # backwards compatibility gs_new = [int(math.sqrt(ntok_new))] * 2 assert len(gs_new) >= 2 _logger.info('Position embedding grid-size from %s to %s', [gs_old, gs_old], gs_new) posemb_grid = posemb_grid.reshape(1, gs_old, gs_old, -1).permute(0, 3, 1, 2) posemb_grid = F.interpolate(posemb_grid, size=gs_new, mode=mode, align_corners=False) posemb_grid = posemb_grid.permute(0, 2, 3, 1).reshape(1, gs_new[0] * gs_new[1], -1) posemb = torch.cat([posemb_tok, posemb_grid], dim=1) return posemb def adapt_image_pos_embed_to_passt(posemb, num_tokens=1, gs_new=(), mode='bicubic'): # Rescale the grid of position embeddings when loading from state_dict. Adapted from # https://github.com/google-research/vision_transformer/blob/00883dd691c63a6830751563748663526e811cee/vit_jax/checkpoint.py#L224 _logger.info('Resized position embedding: %s to %s with %s cls/dis tokens', posemb.shape, gs_new, num_tokens) if num_tokens: posemb_tok, posemb_grid = posemb[:, :num_tokens], posemb[0, num_tokens:] else: posemb_tok, posemb_grid = posemb[:, :0], posemb[0] gs_old = int(math.sqrt(len(posemb_grid))) assert len(gs_new) >= 2 _logger.info('Position embedding grid-size from %s to %s', [gs_old, gs_old], gs_new) posemb_grid = posemb_grid.reshape(1, gs_old, gs_old, -1).permute(0, 3, 1, 2) posemb_grid = F.interpolate(posemb_grid, size=gs_new, mode=mode, align_corners=False) freq_new_pos_embed = posemb_grid.mean(dim=3, keepdim=True) time_new_pos_embed = posemb_grid.mean(dim=2, keepdim=True) _logger.info('New Position cls/dstl embedding %s', posemb_tok.shape) _logger.info('New FREQ Position embedding %s', freq_new_pos_embed.shape) _logger.info('New TIME Position embedding %s', time_new_pos_embed.shape) return posemb_tok, freq_new_pos_embed, time_new_pos_embed def checkpoint_filter_fn(state_dict, model): """ convert patch embedding weight from manual patchify + linear proj to conv""" out_dict = {} if 'model' in state_dict: # For deit models state_dict = state_dict['model'] state_dict = {k: v for k, v in state_dict.items()} if "time_new_pos_embed" not in state_dict: # we are working with ImageNet model _logger.info("Adapting pos embedding from ImageNet pretrained model to PaSST.") v = state_dict.pop("pos_embed") new_pos_embed, freq_new_pos_embed, time_new_pos_embed = adapt_image_pos_embed_to_passt( v, getattr(model, 'num_tokens', 1), model.patch_embed.grid_size) state_dict["new_pos_embed"] = new_pos_embed state_dict["freq_new_pos_embed"] = freq_new_pos_embed state_dict["time_new_pos_embed"] = time_new_pos_embed for k, v in state_dict.items(): if 'patch_embed.proj.weight' in k and len(v.shape) < 4: # For old models that I trained prior to conv based patchification O, I, H, W = model.patch_embed.proj.weight.shape v = v.reshape(O, -1, H, W) elif k == 'pos_embed' and v.shape != model.pos_embed.shape: # this should never occur v = resize_pos_embed( v, model.pos_embed, getattr(model, 'num_tokens', 1), model.patch_embed.grid_size) out_dict[k] = v return out_dict def _create_vision_transformer(variant, pretrained=False, default_cfg=None, **kwargs): default_cfg = default_cfg or default_cfgs[variant] if kwargs.get('features_only', None): raise RuntimeError('features_only not implemented for Vision Transformer models.') # NOTE this extra code to support handling of repr size for in21k pretrained models default_num_classes = default_cfg['num_classes'] num_classes = kwargs.get('num_classes', default_num_classes) repr_size = kwargs.pop('representation_size', None) if repr_size is not None and num_classes != default_num_classes: # Remove representation layer if fine-tuning. This may not always be the desired action, # but I feel better than doing nothing by default for fine-tuning. Perhaps a better interface? _logger.warning("Removing representation layer for fine-tuning.") repr_size = None model = build_model_with_cfg( PaSST, variant, pretrained, default_cfg=default_cfg, representation_size=repr_size, pretrained_filter_fn=checkpoint_filter_fn, pretrained_custom_load='npz' in default_cfg['url'], **kwargs) return model def vit_huge_patch14_224_in21k(pretrained=False, **kwargs): """ ViT-Huge model (ViT-H/14) from original paper (https://arxiv.org/abs/2010.11929). ImageNet-21k weights @ 224x224, source https://github.com/google-research/vision_transformer. NOTE: this model has a representation layer but the 21k classifier head is zero'd out in original weights """ model_kwargs = dict( patch_size=14, embed_dim=1280, depth=32, num_heads=16, representation_size=1280, **kwargs) model = _create_vision_transformer('vit_huge_patch14_224_in21k', pretrained=pretrained, **model_kwargs) return model def deit_base_distilled_patch16_384(pretrained=False, **kwargs): """ DeiT-base distilled model @ 384x384 from paper (https://arxiv.org/abs/2012.12877). ImageNet-1k weights from https://github.com/facebookresearch/deit. """ print("\n\n Loading DEIT BASE 384\n\n") model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs) model = _create_vision_transformer( 'deit_base_distilled_patch16_384', pretrained=pretrained, distilled=True, **model_kwargs) return model def passt_s_swa_p16_128_ap476(pretrained=False, **kwargs): """ PaSST pre-trained on AudioSet """ print("\n\n Loading PaSST pre-trained on AudioSet Patch 16 stride 10 structured patchout mAP=476 SWA \n\n") model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs) if model_kwargs.get("stride") != (10, 10): warnings.warn( f"This model was pre-trained with strides {(10, 10)}, but now you set (fstride,tstride) to {model_kwargs.get("stride")}.") model = _create_vision_transformer( 'passt_s_swa_p16_128_ap476', pretrained=pretrained, distilled=True, **model_kwargs) return model def passt_s_swa_p16_128_ap4761(pretrained=False, **kwargs): """ PaSST pre-trained on AudioSet """ print("\n\n Loading PaSST pre-trained on AudioSet Patch 16 stride 10 structured patchout mAP=4763 SWA \n\n") model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs) if model_kwargs.get("stride") != (10, 10): warnings.warn( f"This model was pre-trained with strides {(10, 10)}, but now you set (fstride,tstride) to {model_kwargs.get("stride")}.") model = _create_vision_transformer( 'passt_s_swa_p16_128_ap4761', pretrained=pretrained, distilled=True, **model_kwargs) return model def passt_s_p16_128_ap472(pretrained=False, **kwargs): """ PaSST pre-trained on AudioSet """ print("\n\n Loading PaSST pre-trained on AudioSet Patch 16 stride 10 structured patchout mAP=472 \n\n") model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs) if model_kwargs.get("stride") != (10, 10): warnings.warn( f"This model was pre-trained with strides {(10, 10)}, but now you set (fstride,tstride) to {model_kwargs.get("stride")}.") model = _create_vision_transformer( 'passt_s_p16_128_ap472', pretrained=pretrained, distilled=True, **model_kwargs) return model def passt_s_p16_s12_128_ap470(pretrained=False, **kwargs): """ PaSST pre-trained on AudioSet """ print("\n\n Loading PaSST pre-trained on AudioSet Patch 16 stride 12 structured patchout mAP=472 \n\n") model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs) if model_kwargs.get("stride") != (12, 12): warnings.warn( f"This model was pre-trained with strides {(12, 12)}, but now you set (fstride,tstride) to {model_kwargs.get("stride")}.") model = _create_vision_transformer( 'passt_s_p16_s12_128_ap470', pretrained=pretrained, distilled=True, **model_kwargs) return model def passt_s_f128_20sec_p16_s10_ap474_swa(pretrained=False, **kwargs): print("\n\n Loading PASST TRAINED ON AUDISET with 20 Second time encodings, with STFT hop of 160 \n\n") model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs) model = _create_vision_transformer( 'passt-s-f128-20sec-p16-s10-ap474-swa', pretrained=pretrained, distilled=True, **model_kwargs) return model def passt_s_f128_30sec_p16_s10_ap473_swa(pretrained=False, **kwargs): print("\n\n Loading PASST TRAINED ON AUDISET with 30 Second time encodings, with STFT hop of 160 \n\n") model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs) model = _create_vision_transformer( 'passt-s-f128-30sec-p16-s10-ap473-swa', pretrained=pretrained, distilled=True, **model_kwargs) return model def passt_s_swa_p16_s12_128_ap473(pretrained=False, **kwargs): """ PaSST pre-trained on AudioSet """ print("\n\n Loading PaSST pre-trained on AudioSet Patch 16 stride 12 structured patchout mAP=472 \n\n") model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs) if model_kwargs.get("stride") != (12, 12): warnings.warn( f"This model was pre-trained with strides {(12, 12)}, but now you set (fstride,tstride) to {model_kwargs.get("stride")}.") model = _create_vision_transformer( 'passt_s_swa_p16_s12_128_ap473', pretrained=pretrained, distilled=True, **model_kwargs) return model def passt_s_p16_s14_128_ap469(pretrained=False, **kwargs): """ PaSST pre-trained on AudioSet """ print("\n\n Loading PaSST pre-trained on AudioSet Patch 16 stride 14 structured patchout mAP=472 \n\n") model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs) if model_kwargs.get("stride") != (14, 14): warnings.warn( f"This model was pre-trained with strides {(14, 14)}, but now you set (fstride,tstride) to {model_kwargs.get("stride")}.") model = _create_vision_transformer( 'passt_s_p16_s14_128_ap469', pretrained=pretrained, distilled=True, **model_kwargs) return model def passt_s_swa_p16_s14_128_ap471(pretrained=False, **kwargs): """ PaSST pre-trained on AudioSet """ print("\n\n Loading PaSST pre-trained on AudioSet Patch 16 stride 14 structured patchout mAP=472 \n\n") model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs) if model_kwargs.get("stride") != (14, 14): warnings.warn( f"This model was pre-trained with strides {(14, 14)}, but now you set (fstride,tstride) to {model_kwargs.get("stride")}.") model = _create_vision_transformer( 'passt_s_swa_p16_s14_128_ap471', pretrained=pretrained, distilled=True, **model_kwargs) return model def passt_s_swa_p16_s16_128_ap473(pretrained=False, **kwargs): """ PaSST pre-trained on AudioSet """ print("\n\n Loading PaSST pre-trained on AudioSet Patch 16 stride 16 structured patchout mAP=472 \n\n") model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs) if model_kwargs.get("stride") != (16, 16): warnings.warn( f"This model was pre-trained with strides {(16, 16)}, but now you set (fstride,tstride) to {model_kwargs.get("stride")}.") model = _create_vision_transformer( 'passt_s_swa_p16_s16_128_ap473', pretrained=pretrained, distilled=True, **model_kwargs) return model def passt_s_p16_s16_128_ap468(pretrained=False, **kwargs): """ PaSST pre-trained on AudioSet """ print("\n\n Loading PaSST pre-trained on AudioSet Patch 16 stride 16 structured patchout mAP=472 \n\n") model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs) if model_kwargs.get("stride") != (16, 16): warnings.warn( f"This model was pre-trained with strides {(16, 16)}, but now you set (fstride,tstride) to {model_kwargs.get("stride")}.") model = _create_vision_transformer( 'passt_s_p16_s16_128_ap468', pretrained=pretrained, distilled=True, **model_kwargs) return model from ba3l.ingredients.ingredient import Ingredient model_ing = Ingredient("passt") model_ing.add_config(instance_cmd="get_model") @model_ing.command def fix_embedding_layer(model, embed="default"): if embed == "default": return model if embed == "overlap": model.patch_embed = PatchEmbedAdaptiveMean(replace=model.patch_embed) if embed == "am_keepconv": model.patch_embed = PatchEmbedAdaptiveMeanKeepConv(replace=model.patch_embed) return model @model_ing.command def lighten_model(model, cut_depth=0): if cut_depth == 0: return model if cut_depth: if cut_depth < 0: print(f"\n Reducing model depth by removing every {-cut_depth} layer \n\n") else: print(f"\n Reducing model depth by {cut_depth} \n\n") if len(model.blocks) < cut_depth + 2: raise ValueError(f"Cut depth a VIT with {len(model.blocks)} " f"layers should be between 1 and {len(model.blocks) - 2}") print(f"\n Before Cutting it was {len(model.blocks)} \n\n") old_blocks = list(model.blocks.children()) if cut_depth < 0: print(f"cut_depth={cut_depth}") old_blocks = [old_blocks[0]] + old_blocks[1:-1:-cut_depth] + [old_blocks[-1]] else: old_blocks = [old_blocks[0]] + old_blocks[cut_depth + 1:] model.blocks = nn.Sequential(*old_blocks) print(f"\n Atfer Cutting it is {len(model.blocks)} \n\n") return model @model_ing.command def get_model(arch="passt_s_swa_p16_128_ap476", pretrained=True, n_classes=527, in_channels=1, fstride=10, tstride=10, input_fdim=128, input_tdim=998, u_patchout=0, s_patchout_t=0, s_patchout_f=0, ): """ :param arch: Base ViT or Deit architecture :param pretrained: use pretrained model on imagenet :param n_classes: number of classes :param in_channels: number of input channels: 1 for mono :param fstride: the patches stride over frequency. :param tstride: the patches stride over time. :param input_fdim: the expected input frequency bins. :param input_tdim: the expected input time bins. :param u_patchout: number of input patches to drop in Unstructured Patchout as defined in https://arxiv.org/abs/2110.05069 :param s_patchout_t: number of input time frames to drop Structured Patchout as defined in https://arxiv.org/abs/2110.05069 :param s_patchout_f: number of input frequency bins to drop Structured Patchout as defined in https://arxiv.org/abs/2110.05069 :param audioset_pretrain: use pretrained models on Audioset. :return: """ model_func = None input_size = (input_fdim, input_tdim) stride = (fstride, tstride) if arch == "passt_deit_bd_p16_384": # base deit model_func = deit_base_distilled_patch16_384 elif arch == "passt_s_swa_p16_128_ap476": # pretrained model_func = passt_s_swa_p16_128_ap476 elif arch == "passt_s_swa_p16_128_ap4761": model_func = passt_s_swa_p16_128_ap4761 elif arch == "passt_s_p16_128_ap472": model_func = passt_s_p16_128_ap472 elif arch == "passt_s_p16_s16_128_ap468": model_func = passt_s_p16_s16_128_ap468 elif arch == "passt_s_swa_p16_s16_128_ap473": model_func = passt_s_swa_p16_s16_128_ap473 elif arch == "passt_s_swa_p16_s14_128_ap471": model_func = passt_s_swa_p16_s14_128_ap471 elif arch == "passt_s_p16_s14_128_ap469": model_func = passt_s_p16_s14_128_ap469 elif arch == "passt_s_swa_p16_s12_128_ap473": model_func = passt_s_swa_p16_s12_128_ap473 elif arch == "passt_s_p16_s12_128_ap470": model_func = passt_s_p16_s12_128_ap470 elif arch == "passt_s_f128_20sec_p16_s10_ap474": model_func = passt_s_f128_20sec_p16_s10_ap474_swa elif arch == "passt_s_f128_30sec_p16_s10_ap473": model_func = passt_s_f128_30sec_p16_s10_ap473_swa if model_func is None: raise RuntimeError(f"Unknown model {arch}") model = model_func(pretrained=pretrained, num_classes=n_classes, in_chans=in_channels, img_size=input_size, stride=stride, u_patchout=u_patchout, s_patchout_t=s_patchout_t, s_patchout_f=s_patchout_f) model = fix_embedding_layer(model) model = lighten_model(model) print(model) return model class EnsembelerModel(nn.Module): def __init__(self, models): super(EnsembelerModel, self).__init__() self.models = nn.ModuleList(models) def forward(self, x): # ModuleList can act as an iterable, or be indexed using ints all_out = None for i, m in enumerate(self.models): out, _ = m(x) if all_out is None: all_out = out else: all_out = out + all_out all_out = all_out / len(self.models) return all_out, all_out @model_ing.command def get_ensemble_model(arch_list=[]): # arch_list = [(passt_s_swa_p16_128_ap476,fstride,tstride)] models_list = [get_model(arch=arch, fstride=fstride, tstride=tstride) for arch, fstride, tstride in arch_list] model = EnsembelerModel(models_list) print(model) return model
""" Most of this code comes from the timm library. We tried to disentangle from the timm library version. Adapted from https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py """ import math import logging import warnings from functools import partial from collections import OrderedDict from copy import deepcopy import torch import torch.nn as nn import torch.nn.functional as F from timm.models.layers.helpers import to_2tuple from .helpers.vit_helpers import update_default_cfg_and_kwargs, DropPath, trunc_normal_, build_model_with_cfg _logger = logging.getLogger() IMAGENET_DEFAULT_MEAN = (0.485, 0.456, 0.406) IMAGENET_DEFAULT_STD = (0.229, 0.224, 0.225) IMAGENET_INCEPTION_MEAN = (0.5, 0.5, 0.5) IMAGENET_INCEPTION_STD = (0.5, 0.5, 0.5) def _cfg(url='', **kwargs): return { 'url': url, 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': None, 'crop_pct': .9, 'interpolation': 'bicubic', 'fixed_input_size': True, 'mean': IMAGENET_INCEPTION_MEAN, 'std': IMAGENET_INCEPTION_STD, 'first_conv': 'patch_embed.proj', 'classifier': 'head', **kwargs } default_cfgs = { # patch models (weights from official Google JAX impl) 'vit_tiny_patch16_224': _cfg( url='https://storage.googleapis.com/vit_models/augreg/' 'Ti_16-i21k-300ep-lr_0.001-aug_none-wd_0.03-do_0.0-sd_0.0--imagenet2012-steps_20k-lr_0.03-res_224.npz'), 'vit_tiny_patch16_384': _cfg( url='https://storage.googleapis.com/vit_models/augreg/' 'Ti_16-i21k-300ep-lr_0.001-aug_none-wd_0.03-do_0.0-sd_0.0--imagenet2012-steps_20k-lr_0.03-res_384.npz', input_size=(3, 384, 384), crop_pct=1.0), 'vit_small_patch32_224': _cfg( url='https://storage.googleapis.com/vit_models/augreg/' 'S_32-i21k-300ep-lr_0.001-aug_light1-wd_0.03-do_0.0-sd_0.0--imagenet2012-steps_20k-lr_0.03-res_224.npz'), 'vit_small_patch32_384': _cfg( url='https://storage.googleapis.com/vit_models/augreg/' 'S_32-i21k-300ep-lr_0.001-aug_light1-wd_0.03-do_0.0-sd_0.0--imagenet2012-steps_20k-lr_0.03-res_384.npz', input_size=(3, 384, 384), crop_pct=1.0), 'vit_small_patch16_224': _cfg( url='https://storage.googleapis.com/vit_models/augreg/' 'S_16-i21k-300ep-lr_0.001-aug_light1-wd_0.03-do_0.0-sd_0.0--imagenet2012-steps_20k-lr_0.03-res_224.npz'), 'vit_small_patch16_384': _cfg( url='https://storage.googleapis.com/vit_models/augreg/' 'S_16-i21k-300ep-lr_0.001-aug_light1-wd_0.03-do_0.0-sd_0.0--imagenet2012-steps_20k-lr_0.03-res_384.npz', input_size=(3, 384, 384), crop_pct=1.0), 'vit_base_patch32_224': _cfg( url='https://storage.googleapis.com/vit_models/augreg/' 'B_32-i21k-300ep-lr_0.001-aug_medium1-wd_0.03-do_0.0-sd_0.0--imagenet2012-steps_20k-lr_0.03-res_224.npz'), 'vit_base_patch32_384': _cfg( url='https://storage.googleapis.com/vit_models/augreg/' 'B_32-i21k-300ep-lr_0.001-aug_light1-wd_0.1-do_0.0-sd_0.0--imagenet2012-steps_20k-lr_0.03-res_384.npz', input_size=(3, 384, 384), crop_pct=1.0), 'vit_base_patch16_224': _cfg( url='https://storage.googleapis.com/vit_models/augreg/' 'B_16-i21k-300ep-lr_0.001-aug_medium1-wd_0.1-do_0.0-sd_0.0--imagenet2012-steps_20k-lr_0.01-res_224.npz'), 'vit_base_patch16_384': _cfg( url='https://storage.googleapis.com/vit_models/augreg/' 'B_16-i21k-300ep-lr_0.001-aug_medium1-wd_0.1-do_0.0-sd_0.0--imagenet2012-steps_20k-lr_0.01-res_384.npz', input_size=(3, 384, 384), crop_pct=1.0), 'vit_large_patch32_224': _cfg( url='', # no official model weights for this combo, only for in21k ), 'vit_large_patch32_384': _cfg( url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-vitjx/jx_vit_large_p32_384-9b920ba8.pth', input_size=(3, 384, 384), crop_pct=1.0), 'vit_large_patch16_224': _cfg( url='https://storage.googleapis.com/vit_models/augreg/' 'L_16-i21k-300ep-lr_0.001-aug_medium1-wd_0.1-do_0.1-sd_0.1--imagenet2012-steps_20k-lr_0.01-res_224.npz'), 'vit_large_patch16_384': _cfg( url='https://storage.googleapis.com/vit_models/augreg/' 'L_16-i21k-300ep-lr_0.001-aug_medium1-wd_0.1-do_0.1-sd_0.1--imagenet2012-steps_20k-lr_0.01-res_384.npz', input_size=(3, 384, 384), crop_pct=1.0), # patch models, imagenet21k (weights from official Google JAX impl) 'vit_tiny_patch16_224_in21k': _cfg( url='https://storage.googleapis.com/vit_models/augreg/Ti_16-i21k-300ep-lr_0.001-aug_none-wd_0.03-do_0.0-sd_0.0.npz', num_classes=21843), 'vit_small_patch32_224_in21k': _cfg( url='https://storage.googleapis.com/vit_models/augreg/S_32-i21k-300ep-lr_0.001-aug_light1-wd_0.03-do_0.0-sd_0.0.npz', num_classes=21843), 'vit_small_patch16_224_in21k': _cfg( url='https://storage.googleapis.com/vit_models/augreg/S_16-i21k-300ep-lr_0.001-aug_light1-wd_0.03-do_0.0-sd_0.0.npz', num_classes=21843), 'vit_base_patch32_224_in21k': _cfg( url='https://storage.googleapis.com/vit_models/augreg/B_32-i21k-300ep-lr_0.001-aug_medium1-wd_0.03-do_0.0-sd_0.0.npz', num_classes=21843), 'vit_base_patch16_224_in21k': _cfg( url='https://storage.googleapis.com/vit_models/augreg/B_16-i21k-300ep-lr_0.001-aug_medium1-wd_0.1-do_0.0-sd_0.0.npz', num_classes=21843), 'vit_large_patch32_224_in21k': _cfg( url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-vitjx/jx_vit_large_patch32_224_in21k-9046d2e7.pth', num_classes=21843), 'vit_large_patch16_224_in21k': _cfg( url='https://storage.googleapis.com/vit_models/augreg/L_16-i21k-300ep-lr_0.001-aug_medium1-wd_0.1-do_0.1-sd_0.1.npz', num_classes=21843), 'vit_huge_patch14_224_in21k': _cfg( url='https://storage.googleapis.com/vit_models/imagenet21k/ViT-H_14.npz', hf_hub='timm/vit_huge_patch14_224_in21k', num_classes=21843), # SAM trained models (https://arxiv.org/abs/2106.01548) 'vit_base_patch32_sam_224': _cfg( url='https://storage.googleapis.com/vit_models/sam/ViT-B_32.npz'), 'vit_base_patch16_sam_224': _cfg( url='https://storage.googleapis.com/vit_models/sam/ViT-B_16.npz'), # deit models (FB weights) 'deit_tiny_patch16_224': _cfg( url='https://dl.fbaipublicfiles.com/deit/deit_tiny_patch16_224-a1311bcf.pth', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD), 'deit_small_patch16_224': _cfg( url='https://dl.fbaipublicfiles.com/deit/deit_small_patch16_224-cd65a155.pth', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD), 'deit_base_patch16_224': _cfg( url='https://dl.fbaipublicfiles.com/deit/deit_base_patch16_224-b5f2ef4d.pth', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD), 'deit_base_patch16_384': _cfg( url='https://dl.fbaipublicfiles.com/deit/deit_base_patch16_384-8de9b5d1.pth', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, input_size=(3, 384, 384), crop_pct=1.0), 'deit_tiny_distilled_patch16_224': _cfg( url='https://dl.fbaipublicfiles.com/deit/deit_tiny_distilled_patch16_224-b40b3cf7.pth', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, classifier=('head', 'head_dist')), 'deit_small_distilled_patch16_224': _cfg( url='https://dl.fbaipublicfiles.com/deit/deit_small_distilled_patch16_224-649709d9.pth', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, classifier=('head', 'head_dist')), 'deit_base_distilled_patch16_224': _cfg( url='https://dl.fbaipublicfiles.com/deit/deit_base_distilled_patch16_224-df68dfff.pth', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, classifier=('head', 'head_dist')), 'deit_base_distilled_patch16_384': _cfg( url='https://dl.fbaipublicfiles.com/deit/deit_base_distilled_patch16_384-d0272ac0.pth', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, input_size=(3, 384, 384), crop_pct=1.0, classifier=('head', 'head_dist')), # ViT ImageNet-21K-P pretraining by MILL 'vit_base_patch16_224_miil_in21k': _cfg( url='https://miil-public-eu.oss-eu-central-1.aliyuncs.com/model-zoo/ImageNet_21K_P/models/timm/vit_base_patch16_224_in21k_miil.pth', mean=(0, 0, 0), std=(1, 1, 1), crop_pct=0.875, interpolation='bilinear', num_classes=11221, ), 'vit_base_patch16_224_miil': _cfg( url='https://miil-public-eu.oss-eu-central-1.aliyuncs.com/model-zoo/ImageNet_21K_P/models/timm' '/vit_base_patch16_224_1k_miil_84_4.pth', mean=(0, 0, 0), std=(1, 1, 1), crop_pct=0.875, interpolation='bilinear', ), # PaSST 'passt_s_swa_p16_128_ap476': _cfg( url='https://github.com/kkoutini/PaSST/releases/download/v0.0.1-audioset/passt-s-f128-p16-s10-ap.476-swa.pt', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, input_size=(1, 128, 998), crop_pct=1.0, classifier=('head.1', 'head_dist'), num_classes=527), 'passt_s_swa_p16_128_ap4761': _cfg( url='https://github.com/kkoutini/PaSST/releases/download/v0.0.2-audioset/passt-s-f128-p16-s10-ap.4761-swa.pt', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, input_size=(1, 128, 998), crop_pct=1.0, classifier=('head.1', 'head_dist'), num_classes=527), 'passt_s_p16_128_ap472': _cfg( url='https://github.com/kkoutini/PaSST/releases/download/v0.0.2-audioset/passt-s-f128-p16-s10-ap.472.pt', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, input_size=(1, 128, 998), crop_pct=1.0, classifier=('head.1', 'head_dist'), num_classes=527), 'passt_s_p16_s16_128_ap468': _cfg( url='https://github.com/kkoutini/PaSST/releases/download/v0.0.2-audioset/passt-s-f128-p16-s16-ap.468.pt', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, input_size=(1, 128, 998), crop_pct=1.0, classifier=('head.1', 'head_dist'), num_classes=527), 'passt_s_swa_p16_s16_128_ap473': _cfg( url='https://github.com/kkoutini/PaSST/releases/download/v0.0.2-audioset/passt-s-f128-p16-s16-ap.473-swa.pt', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, input_size=(1, 128, 998), crop_pct=1.0, classifier=('head.1', 'head_dist'), num_classes=527), 'passt_s_swa_p16_s14_128_ap471': _cfg( url='https://github.com/kkoutini/PaSST/releases/download/v0.0.2-audioset/passt-s-f128-p16-s14-ap.471-swa.pt', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, input_size=(1, 128, 998), crop_pct=1.0, classifier=('head.1', 'head_dist'), num_classes=527), 'passt_s_p16_s14_128_ap469': _cfg( url='https://github.com/kkoutini/PaSST/releases/download/v0.0.2-audioset/passt-s-f128-p16-s14-ap.469.pt', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, input_size=(1, 128, 998), crop_pct=1.0, classifier=('head.1', 'head_dist'), num_classes=527), 'passt_s_swa_p16_s12_128_ap473': _cfg( url='https://github.com/kkoutini/PaSST/releases/download/v0.0.2-audioset/passt-s-f128-p16-s12-ap.473-swa.pt', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, input_size=(1, 128, 998), crop_pct=1.0, classifier=('head.1', 'head_dist'), num_classes=527), 'passt_s_p16_s12_128_ap470': _cfg( url='https://github.com/kkoutini/PaSST/releases/download/v0.0.2-audioset/passt-s-f128-p16-s12-ap.470.pt', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, input_size=(1, 128, 998), crop_pct=1.0, classifier=('head.1', 'head_dist'), num_classes=527), 'passt_s_swa_f128_stfthop100_p16_s10_ap473': _cfg( url='https://github.com/kkoutini/PaSST/releases/download/v0.0.3-audioset/passt-s-f128-stfthop100-p16-s10-ap.473-swa.pt', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, input_size=(1, 128, 3200), crop_pct=1.0, classifier=('head.1', 'head_dist'), num_classes=527), 'passt_s_swa_f128_stfthop160_p16_s10_ap473': _cfg( url='https://github.com/kkoutini/PaSST/releases/download/v0.0.3-audioset/passt-s-f128-stfthop160-p16-s10-ap.473-swa.pt', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, input_size=(1, 128, 2000), crop_pct=1.0, classifier=('head.1', 'head_dist'), num_classes=527), 'passt-s-f128-20sec-p16-s10-ap474-swa': _cfg( url='https://github.com/kkoutini/PaSST/releases/download/v0.0.3-audioset/passt-s-f128-20sec-p16-s10-ap.474-swa.pt', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, input_size=(1, 128, 2000), crop_pct=1.0, classifier=('head.1', 'head_dist'), num_classes=527), 'passt-s-f128-30sec-p16-s10-ap473-swa': _cfg( url='https://github.com/kkoutini/PaSST/releases/download/v0.0.3-audioset/passt-s-f128-30sec-p16-s10-ap.473-swa.pt', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, input_size=(1, 128, 3000), crop_pct=1.0, classifier=('head.1', 'head_dist'), num_classes=527), 'openmic2008_passt_u_f128_p16_s10_ap85_swa': _cfg( url='https://github.com/kkoutini/PaSST/releases/download/v0.0.4-openmic/openmic2008.passt-u-f128-p16-s10-ap.85-swa.pt', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, input_size=(1, 128, 3200), crop_pct=1.0, classifier=('head.1', 'head_dist'), num_classes=20), 'openmic2008_passt_u_f128_p16_s10_ap85 ': _cfg( url='https://github.com/kkoutini/PaSST/releases/download/v0.0.4-openmic/openmic2008.passt-u-f128-p16-s10-ap.85.pt', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, input_size=(1, 128, 2000), crop_pct=1.0, classifier=('head.1', 'head_dist'), num_classes=20), } def adapt_input_conv(in_chans, conv_weight): conv_type = conv_weight.dtype conv_weight = conv_weight.float() # Some weights are in torch.half, ensure it's float for sum on CPU O, I, J, K = conv_weight.shape if in_chans == 1: if I > 3: assert conv_weight.shape[1] % 3 == 0 # For models with space2depth stems conv_weight = conv_weight.reshape(O, I // 3, 3, J, K) conv_weight = conv_weight.sum(dim=2, keepdim=False) else: conv_weight = conv_weight.sum(dim=1, keepdim=True) elif in_chans != 3: if I != 3: raise NotImplementedError('Weight format not supported by conversion.') else: # NOTE this strategy should be better than random init, but there could be other combinations of # the original RGB input layer weights that'd work better for specific cases. repeat = int(math.ceil(in_chans / 3)) conv_weight = conv_weight.repeat(1, repeat, 1, 1)[:, :in_chans, :, :] conv_weight *= (3 / float(in_chans)) conv_weight = conv_weight.to(conv_type) return conv_weight class Mlp(nn.Module): """ MLP as used in Vision Transformer, MLP-Mixer and related networks """ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.): super().__init__() out_features = out_features or in_features hidden_features = hidden_features or in_features self.fc1 = nn.Linear(in_features, hidden_features) self.act = act_layer() self.fc2 = nn.Linear(hidden_features, out_features) self.drop = nn.Dropout(drop) def forward(self, x): x = self.fc1(x) x = self.act(x) x = self.drop(x) x = self.fc2(x) x = self.drop(x) return x first_RUN = True class PatchEmbed(nn.Module): """ 2D Image to Patch Embedding """ def __init__(self, img_size=224, patch_size=16, stride=16, in_chans=3, embed_dim=768, norm_layer=None, flatten=True): super().__init__() img_size = to_2tuple(img_size) patch_size = to_2tuple(patch_size) stride = to_2tuple(stride) self.img_size = img_size self.patch_size = patch_size self.stride = stride self.grid_size = (img_size[0] // stride[0], img_size[1] // stride[1]) self.num_patches = self.grid_size[0] * self.grid_size[1] self.flatten = flatten self.embed_dim = embed_dim self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=stride) self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity() def forward(self, x): B, C, H, W = x.shape if not (H == self.img_size[0] and W == self.img_size[1]): warnings.warn(f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]}).") # to do maybe replace weights x = self.proj(x) if self.flatten: x = x.flatten(2).transpose(1, 2) # BCHW -> BNC x = self.norm(x) if first_RUN: print("self.norm(x)", x.size()) return x class Attention(nn.Module): def __init__(self, dim, num_heads=8, qkv_bias=False, attn_drop=0., proj_drop=0.): super().__init__() self.num_heads = num_heads head_dim = dim // num_heads self.scale = head_dim ** -0.5 self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) self.attn_drop = nn.Dropout(attn_drop) self.proj = nn.Linear(dim, dim) self.proj_drop = nn.Dropout(proj_drop) def forward(self, x): B, N, C = x.shape qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple) attn = (q @ k.transpose(-2, -1)) * self.scale attn = attn.softmax(dim=-1) attn = self.attn_drop(attn) x = (attn @ v).transpose(1, 2).reshape(B, N, C) x = self.proj(x) x = self.proj_drop(x) return x class Block(nn.Module): def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, drop=0., attn_drop=0., drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm): super().__init__() self.norm1 = norm_layer(dim) self.attn = Attention(dim, num_heads=num_heads, qkv_bias=qkv_bias, attn_drop=attn_drop, proj_drop=drop) # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() self.norm2 = norm_layer(dim) mlp_hidden_dim = int(dim * mlp_ratio) self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) def forward(self, x): x = x + self.drop_path(self.attn(self.norm1(x))) x = x + self.drop_path(self.mlp(self.norm2(x))) return x class PaSST(nn.Module): """ Based on the implementation of Vision Transformer in timm library. Take a look at the get_model function, adapting the weights of pretrained imagenet models. """ def __init__(self, u_patchout=0, s_patchout_t=0, s_patchout_f=0, img_size=(128, 998), patch_size=16, stride=16, in_chans=1, num_classes=527, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4., qkv_bias=True, representation_size=None, distilled=False, drop_rate=0., attn_drop_rate=0., drop_path_rate=0., embed_layer=PatchEmbed, norm_layer=None, act_layer=None, weight_init=''): """ Args: u_patchout: Unstructured Patchout integer, number of items to be removed from the final sequence s_patchout_t: structured Patchout time integer, number of columns to be removed from the patches grid s_patchout_f: structured Patchout Frequency integer, number of rows to be removed from the patches grid img_size (int, tuple): input image size patch_size (int, tuple): patch size in_chans (int): number of input channels num_classes (int): number of classes for classification head embed_dim (int): embedding dimension depth (int): depth of transformer num_heads (int): number of attention heads mlp_ratio (int): ratio of mlp hidden dim to embedding dim qkv_bias (bool): enable bias for qkv if True representation_size (Optional[int]): enable and set representation layer (pre-logits) to this value if set distilled (bool): model includes a distillation token and head as in DeiT models drop_rate (float): dropout rate attn_drop_rate (float): attention dropout rate drop_path_rate (float): stochastic depth rate embed_layer (nn.Module): patch embedding layer norm_layer: (nn.Module): normalization layer weight_init: (str): weight init scheme """ super().__init__() self.num_classes = num_classes self.u_patchout = u_patchout self.s_patchout_t = s_patchout_t self.s_patchout_f = s_patchout_f self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models self.num_tokens = 2 if distilled else 1 norm_layer = norm_layer or partial(nn.LayerNorm, eps=1e-6) act_layer = act_layer or nn.GELU self.patch_embed = embed_layer( img_size=img_size, patch_size=patch_size, stride=stride, in_chans=in_chans, embed_dim=embed_dim, flatten=False) num_patches = self.patch_embed.num_patches self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) self.dist_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) if distilled else None # PaSST # refer to https://arxiv.org/abs/2110.05069 Section 2 self.new_pos_embed = nn.Parameter(torch.zeros(1, self.num_tokens, embed_dim)) # for C and D tokens self.freq_new_pos_embed = nn.Parameter(torch.zeros(1, embed_dim, self.patch_embed.grid_size[0], 1)) # | f self.time_new_pos_embed = nn.Parameter(torch.zeros(1, embed_dim, 1, self.patch_embed.grid_size[1])) # __ t #### self.pos_drop = nn.Dropout(p=drop_rate) dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule self.blocks = nn.Sequential(*[ Block( dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer, act_layer=act_layer) for i in range(depth)]) self.norm = norm_layer(embed_dim) # Representation layer if representation_size and not distilled: self.num_features = representation_size self.pre_logits = nn.Sequential(OrderedDict([ ('fc', nn.Linear(embed_dim, representation_size)), ('act', nn.Tanh()) ])) else: self.pre_logits = nn.Identity() # Classifier head(s) self.head = nn.Sequential(nn.LayerNorm(self.num_features), nn.Linear(self.num_features, num_classes) if num_classes > 0 else nn.Identity()) self.head_dist = None if distilled: self.head_dist = nn.Linear(self.embed_dim, self.num_classes) if num_classes > 0 else nn.Identity() self.init_weights(weight_init) def init_weights(self, mode=''): assert mode in ('jax', 'jax_nlhb', 'nlhb', '') head_bias = -math.log(self.num_classes) if 'nlhb' in mode else 0. trunc_normal_(self.new_pos_embed, std=.02) trunc_normal_(self.freq_new_pos_embed, std=.02) trunc_normal_(self.time_new_pos_embed, std=.02) if self.dist_token is not None: trunc_normal_(self.dist_token, std=.02) if mode.startswith('jax'): # leave cls token as zeros to match jax impl raise RuntimeError("Not supported yet") else: trunc_normal_(self.cls_token, std=.02) self.apply(_init_vit_weights) def _init_weights(self, m): # this fn left here for compat with downstream users _init_vit_weights(m) @torch.jit.ignore def no_weight_decay(self): return {'new_pos_embed', 'freq_new_pos_embed', 'time_new_pos_embed', 'cls_token', 'dist_token'} def get_classifier(self): if self.dist_token is None: return self.head else: return self.head, self.head_dist def reset_classifier(self, num_classes, global_pool=''): self.num_classes = num_classes self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity() if self.num_tokens == 2: self.head_dist = nn.Linear(self.embed_dim, self.num_classes) if num_classes > 0 else nn.Identity() def forward_features(self, x): global first_RUN # not jit friendly? use trace instead x = self.patch_embed(x) # [b, e, f, t] B_dim, E_dim, F_dim, T_dim = x.shape # slow if first_RUN: print(" patch_embed : ", x.shape) # Adding Time/Freq information if first_RUN: print(" self.time_new_pos_embed.shape", self.time_new_pos_embed.shape) time_new_pos_embed = self.time_new_pos_embed if x.shape[-1] < time_new_pos_embed.shape[-1]: if self.training: toffset = torch.randint(1 + time_new_pos_embed.shape[-1] - x.shape[-1], (1,)).item() if first_RUN: print(f" CUT with randomoffset={toffset} time_new_pos_embed.shape", time_new_pos_embed.shape) time_new_pos_embed = time_new_pos_embed[:, :, :, toffset:toffset + x.shape[-1]] else: time_new_pos_embed = time_new_pos_embed[:, :, :, :x.shape[-1]] if first_RUN: print(" CUT time_new_pos_embed.shape", time_new_pos_embed.shape) else: warnings.warn( f"the patches shape:{x.shape} are larger than the expected time encodings {time_new_pos_embed.shape}, x will be cut") x = x[:, :, :, :time_new_pos_embed.shape[-1]] x = x + time_new_pos_embed if first_RUN: print(" self.freq_new_pos_embed.shape", self.freq_new_pos_embed.shape) x = x + self.freq_new_pos_embed # Structured Patchout https://arxiv.org/abs/2110.05069 Section 2.2 if self.training and self.s_patchout_t: if first_RUN: print(f"X Before time Patchout of {self.s_patchout_t} ", x.size()) # ([1, 768, 1, 82]) random_indices = torch.randperm(T_dim)[:T_dim - self.s_patchout_t].sort().values x = x[:, :, :, random_indices] if first_RUN: print("X after time Patchout", x.size()) if self.training and self.s_patchout_f: if first_RUN: print(f"X Before Freq Patchout of {self.s_patchout_f} ", x.size()) # [1, 768, 12, 1] random_indices = torch.randperm(F_dim)[:F_dim - self.s_patchout_f].sort().values x = x[:, :, random_indices, :] if first_RUN: print(" \n X after freq Patchout: ", x.size()) ### # Flatten the sequence x = x.flatten(2).transpose(1, 2) # Unstructured Patchout if first_RUN: print("X flattened", x.size()) if self.training and self.u_patchout: seq_len = x.shape[1] random_indices = torch.randperm(seq_len)[:seq_len - self.u_patchout].sort().values x = x[:, random_indices, :] if first_RUN: print("X After Unstructured Patchout", x.size()) #### # Add the C/D tokens if first_RUN: print(" self.new_pos_embed.shape", self.new_pos_embed.shape) cls_tokens = self.cls_token.expand(B_dim, -1, -1) + self.new_pos_embed[:, :1, :] if first_RUN: print(" self.cls_tokens.shape", cls_tokens.shape) if self.dist_token is None: x = torch.cat((cls_tokens, x), dim=1) else: dist_token = self.dist_token.expand(B_dim, -1, -1) + self.new_pos_embed[:, 1:, :] if first_RUN: print(" self.dist_token.shape", dist_token.shape) x = torch.cat((cls_tokens, dist_token, x), dim=1) if first_RUN: print(" final sequence x", x.shape) x = self.pos_drop(x) x = self.blocks(x) if first_RUN: print(f" after {len(self.blocks)} atten blocks x", x.shape) x = self.norm(x) if self.dist_token is None: return self.pre_logits(x[:, 0]) else: return x[:, 0], x[:, 1] def forward(self, x): global first_RUN if first_RUN: print("x", x.size()) x = self.forward_features(x) if self.head_dist is not None: features = (x[0] + x[1]) / 2 if first_RUN: print("forward_features", features.size()) x = self.head(features) if first_RUN: print("head", x.size()) first_RUN = False return x, features else: features = x if first_RUN: print("forward_features", features.size()) x = self.head(x) if first_RUN: print("head", x.size()) first_RUN = False return x, features def _init_vit_weights(module: nn.Module, name: str = '', head_bias: float = 0., jax_impl: bool = False): """ ViT weight initialization * When called without n, head_bias, jax_impl args it will behave exactly the same as my original init for compatibility with prev hparam / downstream use cases (ie DeiT). * When called w/ valid n (module name) and jax_impl=True, will (hopefully) match JAX impl """ if isinstance(module, nn.Linear): if name.startswith('head'): nn.init.zeros_(module.weight) nn.init.constant_(module.bias, head_bias) elif name.startswith('pre_logits'): lecun_normal_(module.weight) nn.init.zeros_(module.bias) else: if jax_impl: nn.init.xavier_uniform_(module.weight) if module.bias is not None: if 'mlp' in name: nn.init.normal_(module.bias, std=1e-6) else: nn.init.zeros_(module.bias) else: trunc_normal_(module.weight, std=.02) if module.bias is not None: nn.init.zeros_(module.bias) elif jax_impl and isinstance(module, nn.Conv2d): # NOTE conv was left to pytorch default in my original init lecun_normal_(module.weight) if module.bias is not None: nn.init.zeros_(module.bias) elif isinstance(module, (nn.LayerNorm, nn.GroupNorm, nn.BatchNorm2d)): nn.init.zeros_(module.bias) nn.init.ones_(module.weight) def resize_pos_embed(posemb, posemb_new, num_tokens=1, gs_new=(), mode='bicubic'): # Rescale the grid of position embeddings when loading from state_dict. Adapted from # https://github.com/google-research/vision_transformer/blob/00883dd691c63a6830751563748663526e811cee/vit_jax/checkpoint.py#L224 _logger.info('Resized position embedding: %s to %s with %s cls/dis tokens', posemb.shape, posemb_new.shape, num_tokens) ntok_new = posemb_new.shape[1] if num_tokens: posemb_tok, posemb_grid = posemb[:, :num_tokens], posemb[0, num_tokens:] ntok_new -= num_tokens else: posemb_tok, posemb_grid = posemb[:, :0], posemb[0] gs_old = int(math.sqrt(len(posemb_grid))) if not len(gs_new): # backwards compatibility gs_new = [int(math.sqrt(ntok_new))] * 2 assert len(gs_new) >= 2 _logger.info('Position embedding grid-size from %s to %s', [gs_old, gs_old], gs_new) posemb_grid = posemb_grid.reshape(1, gs_old, gs_old, -1).permute(0, 3, 1, 2) posemb_grid = F.interpolate(posemb_grid, size=gs_new, mode=mode, align_corners=False) posemb_grid = posemb_grid.permute(0, 2, 3, 1).reshape(1, gs_new[0] * gs_new[1], -1) posemb = torch.cat([posemb_tok, posemb_grid], dim=1) return posemb def adapt_image_pos_embed_to_passt(posemb, num_tokens=1, gs_new=(), mode='bicubic'): # Rescale the grid of position embeddings when loading from state_dict. Adapted from # https://github.com/google-research/vision_transformer/blob/00883dd691c63a6830751563748663526e811cee/vit_jax/checkpoint.py#L224 _logger.info('Resized position embedding: %s to %s with %s cls/dis tokens', posemb.shape, gs_new, num_tokens) if num_tokens: posemb_tok, posemb_grid = posemb[:, :num_tokens], posemb[0, num_tokens:] else: posemb_tok, posemb_grid = posemb[:, :0], posemb[0] gs_old = int(math.sqrt(len(posemb_grid))) assert len(gs_new) >= 2 _logger.info('Position embedding grid-size from %s to %s', [gs_old, gs_old], gs_new) posemb_grid = posemb_grid.reshape(1, gs_old, gs_old, -1).permute(0, 3, 1, 2) posemb_grid = F.interpolate(posemb_grid, size=gs_new, mode=mode, align_corners=False) freq_new_pos_embed = posemb_grid.mean(dim=3, keepdim=True) time_new_pos_embed = posemb_grid.mean(dim=2, keepdim=True) _logger.info('New Position cls/dstl embedding %s', posemb_tok.shape) _logger.info('New FREQ Position embedding %s', freq_new_pos_embed.shape) _logger.info('New TIME Position embedding %s', time_new_pos_embed.shape) return posemb_tok, freq_new_pos_embed, time_new_pos_embed def checkpoint_filter_fn(state_dict, model): """ convert patch embedding weight from manual patchify + linear proj to conv""" out_dict = {} if 'model' in state_dict: # For deit models state_dict = state_dict['model'] state_dict = {k: v for k, v in state_dict.items()} if "time_new_pos_embed" not in state_dict: # we are working with ImageNet model _logger.info("Adapting pos embedding from ImageNet pretrained model to PaSST.") v = state_dict.pop("pos_embed") new_pos_embed, freq_new_pos_embed, time_new_pos_embed = adapt_image_pos_embed_to_passt( v, getattr(model, 'num_tokens', 1), model.patch_embed.grid_size) state_dict["new_pos_embed"] = new_pos_embed state_dict["freq_new_pos_embed"] = freq_new_pos_embed state_dict["time_new_pos_embed"] = time_new_pos_embed for k, v in state_dict.items(): if 'patch_embed.proj.weight' in k and len(v.shape) < 4: # For old models that I trained prior to conv based patchification O, I, H, W = model.patch_embed.proj.weight.shape v = v.reshape(O, -1, H, W) elif k == 'pos_embed' and v.shape != model.pos_embed.shape: # this should never occur v = resize_pos_embed( v, model.pos_embed, getattr(model, 'num_tokens', 1), model.patch_embed.grid_size) out_dict[k] = v return out_dict def _create_vision_transformer(variant, pretrained=False, default_cfg=None, **kwargs): default_cfg = default_cfg or default_cfgs[variant] if kwargs.get('features_only', None): raise RuntimeError('features_only not implemented for Vision Transformer models.') # NOTE this extra code to support handling of repr size for in21k pretrained models default_num_classes = default_cfg['num_classes'] num_classes = kwargs.get('num_classes', default_num_classes) repr_size = kwargs.pop('representation_size', None) if repr_size is not None and num_classes != default_num_classes: # Remove representation layer if fine-tuning. This may not always be the desired action, # but I feel better than doing nothing by default for fine-tuning. Perhaps a better interface? _logger.warning("Removing representation layer for fine-tuning.") repr_size = None model = build_model_with_cfg( PaSST, variant, pretrained, default_cfg=default_cfg, representation_size=repr_size, pretrained_filter_fn=checkpoint_filter_fn, pretrained_custom_load='npz' in default_cfg['url'], **kwargs) return model def vit_huge_patch14_224_in21k(pretrained=False, **kwargs): """ ViT-Huge model (ViT-H/14) from original paper (https://arxiv.org/abs/2010.11929). ImageNet-21k weights @ 224x224, source https://github.com/google-research/vision_transformer. NOTE: this model has a representation layer but the 21k classifier head is zero'd out in original weights """ model_kwargs = dict( patch_size=14, embed_dim=1280, depth=32, num_heads=16, representation_size=1280, **kwargs) model = _create_vision_transformer('vit_huge_patch14_224_in21k', pretrained=pretrained, **model_kwargs) return model def deit_base_distilled_patch16_384(pretrained=False, **kwargs): """ DeiT-base distilled model @ 384x384 from paper (https://arxiv.org/abs/2012.12877). ImageNet-1k weights from https://github.com/facebookresearch/deit. """ print("\n\n Loading DEIT BASE 384\n\n") model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs) model = _create_vision_transformer( 'deit_base_distilled_patch16_384', pretrained=pretrained, distilled=True, **model_kwargs) return model def passt_s_swa_p16_128_ap476(pretrained=False, **kwargs): """ PaSST pre-trained on AudioSet """ print("\n\n Loading PaSST pre-trained on AudioSet Patch 16 stride 10 structured patchout mAP=476 SWA \n\n") model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs) if model_kwargs.get("stride") != (10, 10): warnings.warn( f"This model was pre-trained with strides {(10, 10)}, but now you set (fstride,tstride) to {model_kwargs.get('stride')}.") model = _create_vision_transformer( 'passt_s_swa_p16_128_ap476', pretrained=pretrained, distilled=True, **model_kwargs) return model def passt_s_swa_p16_128_ap4761(pretrained=False, **kwargs): """ PaSST pre-trained on AudioSet """ print("\n\n Loading PaSST pre-trained on AudioSet Patch 16 stride 10 structured patchout mAP=4763 SWA \n\n") model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs) if model_kwargs.get("stride") != (10, 10): warnings.warn( f"This model was pre-trained with strides {(10, 10)}, but now you set (fstride,tstride) to {model_kwargs.get('stride')}.") model = _create_vision_transformer( 'passt_s_swa_p16_128_ap4761', pretrained=pretrained, distilled=True, **model_kwargs) return model def passt_s_p16_128_ap472(pretrained=False, **kwargs): """ PaSST pre-trained on AudioSet """ print("\n\n Loading PaSST pre-trained on AudioSet Patch 16 stride 10 structured patchout mAP=472 \n\n") model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs) if model_kwargs.get("stride") != (10, 10): warnings.warn( f"This model was pre-trained with strides {(10, 10)}, but now you set (fstride,tstride) to {model_kwargs.get('stride')}.") model = _create_vision_transformer( 'passt_s_p16_128_ap472', pretrained=pretrained, distilled=True, **model_kwargs) return model def passt_s_p16_s12_128_ap470(pretrained=False, **kwargs): """ PaSST pre-trained on AudioSet """ print("\n\n Loading PaSST pre-trained on AudioSet Patch 16 stride 12 structured patchout mAP=472 \n\n") model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs) if model_kwargs.get("stride") != (12, 12): warnings.warn( f"This model was pre-trained with strides {(12, 12)}, but now you set (fstride,tstride) to {model_kwargs.get('stride')}.") model = _create_vision_transformer( 'passt_s_p16_s12_128_ap470', pretrained=pretrained, distilled=True, **model_kwargs) return model def passt_s_f128_20sec_p16_s10_ap474_swa(pretrained=False, **kwargs): print("\n\n Loading PASST TRAINED ON AUDISET with 20 Second time encodings, with STFT hop of 160 \n\n") model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs) model = _create_vision_transformer( 'passt-s-f128-20sec-p16-s10-ap474-swa', pretrained=pretrained, distilled=True, **model_kwargs) return model def passt_s_f128_30sec_p16_s10_ap473_swa(pretrained=False, **kwargs): print("\n\n Loading PASST TRAINED ON AUDISET with 30 Second time encodings, with STFT hop of 160 \n\n") model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs) model = _create_vision_transformer( 'passt-s-f128-30sec-p16-s10-ap473-swa', pretrained=pretrained, distilled=True, **model_kwargs) return model def passt_s_swa_p16_s12_128_ap473(pretrained=False, **kwargs): """ PaSST pre-trained on AudioSet """ print("\n\n Loading PaSST pre-trained on AudioSet Patch 16 stride 12 structured patchout mAP=472 \n\n") model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs) if model_kwargs.get("stride") != (12, 12): warnings.warn( f"This model was pre-trained with strides {(12, 12)}, but now you set (fstride,tstride) to {model_kwargs.get('stride')}.") model = _create_vision_transformer( 'passt_s_swa_p16_s12_128_ap473', pretrained=pretrained, distilled=True, **model_kwargs) return model def passt_s_p16_s14_128_ap469(pretrained=False, **kwargs): """ PaSST pre-trained on AudioSet """ print("\n\n Loading PaSST pre-trained on AudioSet Patch 16 stride 14 structured patchout mAP=472 \n\n") model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs) if model_kwargs.get("stride") != (14, 14): warnings.warn( f"This model was pre-trained with strides {(14, 14)}, but now you set (fstride,tstride) to {model_kwargs.get('stride')}.") model = _create_vision_transformer( 'passt_s_p16_s14_128_ap469', pretrained=pretrained, distilled=True, **model_kwargs) return model def passt_s_swa_p16_s14_128_ap471(pretrained=False, **kwargs): """ PaSST pre-trained on AudioSet """ print("\n\n Loading PaSST pre-trained on AudioSet Patch 16 stride 14 structured patchout mAP=472 \n\n") model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs) if model_kwargs.get("stride") != (14, 14): warnings.warn( f"This model was pre-trained with strides {(14, 14)}, but now you set (fstride,tstride) to {model_kwargs.get('stride')}.") model = _create_vision_transformer( 'passt_s_swa_p16_s14_128_ap471', pretrained=pretrained, distilled=True, **model_kwargs) return model def passt_s_swa_p16_s16_128_ap473(pretrained=False, **kwargs): """ PaSST pre-trained on AudioSet """ print("\n\n Loading PaSST pre-trained on AudioSet Patch 16 stride 16 structured patchout mAP=472 \n\n") model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs) if model_kwargs.get("stride") != (16, 16): warnings.warn( f"This model was pre-trained with strides {(16, 16)}, but now you set (fstride,tstride) to {model_kwargs.get('stride')}.") model = _create_vision_transformer( 'passt_s_swa_p16_s16_128_ap473', pretrained=pretrained, distilled=True, **model_kwargs) return model def passt_s_p16_s16_128_ap468(pretrained=False, **kwargs): """ PaSST pre-trained on AudioSet """ print("\n\n Loading PaSST pre-trained on AudioSet Patch 16 stride 16 structured patchout mAP=472 \n\n") model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs) if model_kwargs.get("stride") != (16, 16): warnings.warn( f"This model was pre-trained with strides {(16, 16)}, but now you set (fstride,tstride) to {model_kwargs.get('stride')}.") model = _create_vision_transformer( 'passt_s_p16_s16_128_ap468', pretrained=pretrained, distilled=True, **model_kwargs) return model from ba3l.ingredients.ingredient import Ingredient model_ing = Ingredient("passt") model_ing.add_config(instance_cmd="get_model") @model_ing.command def fix_embedding_layer(model, embed="default"): if embed == "default": return model if embed == "overlap": model.patch_embed = PatchEmbedAdaptiveMean(replace=model.patch_embed) if embed == "am_keepconv": model.patch_embed = PatchEmbedAdaptiveMeanKeepConv(replace=model.patch_embed) return model @model_ing.command def lighten_model(model, cut_depth=0): if cut_depth == 0: return model if cut_depth: if cut_depth < 0: print(f"\n Reducing model depth by removing every {-cut_depth} layer \n\n") else: print(f"\n Reducing model depth by {cut_depth} \n\n") if len(model.blocks) < cut_depth + 2: raise ValueError(f"Cut depth a VIT with {len(model.blocks)} " f"layers should be between 1 and {len(model.blocks) - 2}") print(f"\n Before Cutting it was {len(model.blocks)} \n\n") old_blocks = list(model.blocks.children()) if cut_depth < 0: print(f"cut_depth={cut_depth}") old_blocks = [old_blocks[0]] + old_blocks[1:-1:-cut_depth] + [old_blocks[-1]] else: old_blocks = [old_blocks[0]] + old_blocks[cut_depth + 1:] model.blocks = nn.Sequential(*old_blocks) print(f"\n Atfer Cutting it is {len(model.blocks)} \n\n") return model @model_ing.command def get_model(arch="passt_s_swa_p16_128_ap476", pretrained=True, n_classes=527, in_channels=1, fstride=10, tstride=10, input_fdim=128, input_tdim=998, u_patchout=0, s_patchout_t=0, s_patchout_f=0, ): """ :param arch: Base ViT or Deit architecture :param pretrained: use pretrained model on imagenet :param n_classes: number of classes :param in_channels: number of input channels: 1 for mono :param fstride: the patches stride over frequency. :param tstride: the patches stride over time. :param input_fdim: the expected input frequency bins. :param input_tdim: the expected input time bins. :param u_patchout: number of input patches to drop in Unstructured Patchout as defined in https://arxiv.org/abs/2110.05069 :param s_patchout_t: number of input time frames to drop Structured Patchout as defined in https://arxiv.org/abs/2110.05069 :param s_patchout_f: number of input frequency bins to drop Structured Patchout as defined in https://arxiv.org/abs/2110.05069 :param audioset_pretrain: use pretrained models on Audioset. :return: """ model_func = None input_size = (input_fdim, input_tdim) stride = (fstride, tstride) if arch == "passt_deit_bd_p16_384": # base deit model_func = deit_base_distilled_patch16_384 elif arch == "passt_s_swa_p16_128_ap476": # pretrained model_func = passt_s_swa_p16_128_ap476 elif arch == "passt_s_swa_p16_128_ap4761": model_func = passt_s_swa_p16_128_ap4761 elif arch == "passt_s_p16_128_ap472": model_func = passt_s_p16_128_ap472 elif arch == "passt_s_p16_s16_128_ap468": model_func = passt_s_p16_s16_128_ap468 elif arch == "passt_s_swa_p16_s16_128_ap473": model_func = passt_s_swa_p16_s16_128_ap473 elif arch == "passt_s_swa_p16_s14_128_ap471": model_func = passt_s_swa_p16_s14_128_ap471 elif arch == "passt_s_p16_s14_128_ap469": model_func = passt_s_p16_s14_128_ap469 elif arch == "passt_s_swa_p16_s12_128_ap473": model_func = passt_s_swa_p16_s12_128_ap473 elif arch == "passt_s_p16_s12_128_ap470": model_func = passt_s_p16_s12_128_ap470 elif arch == "passt_s_f128_20sec_p16_s10_ap474": model_func = passt_s_f128_20sec_p16_s10_ap474_swa elif arch == "passt_s_f128_30sec_p16_s10_ap473": model_func = passt_s_f128_30sec_p16_s10_ap473_swa if model_func is None: raise RuntimeError(f"Unknown model {arch}") model = model_func(pretrained=pretrained, num_classes=n_classes, in_chans=in_channels, img_size=input_size, stride=stride, u_patchout=u_patchout, s_patchout_t=s_patchout_t, s_patchout_f=s_patchout_f) model = fix_embedding_layer(model) model = lighten_model(model) print(model) return model class EnsembelerModel(nn.Module): def __init__(self, models): super(EnsembelerModel, self).__init__() self.models = nn.ModuleList(models) def forward(self, x): # ModuleList can act as an iterable, or be indexed using ints all_out = None for i, m in enumerate(self.models): out, _ = m(x) if all_out is None: all_out = out else: all_out = out + all_out all_out = all_out / len(self.models) return all_out, all_out @model_ing.command def get_ensemble_model(arch_list=[]): # arch_list = [(passt_s_swa_p16_128_ap476,fstride,tstride)] models_list = [get_model(arch=arch, fstride=fstride, tstride=tstride) for arch, fstride, tstride in arch_list] model = EnsembelerModel(models_list) print(model) return model
# -*- coding: utf-8 -*- __author__ = 'lundberg' import urllib.parse from contextlib import contextmanager from dataclasses import dataclass, field from datetime import datetime, timedelta, timezone from typing import Any, Dict, Iterator, List, Optional, Set from flask import abort, current_app, request from flask_limiter.util import get_ipaddr from pymisp import PyMISPError from validators import domain, ipv4, ipv6, md5, sha1, sha256, url, validator from ioc_lookup.misp_api import Attr, AttrType, MISPApi class ParseException(Exception): pass @dataclass class User: identifier: str is_trusted_user: bool in_trusted_org: bool org_domain: str @dataclass class Votes: positives: int = 0 positive_orgs: Set[str] = field(default_factory=set) negatives: int = 0 negative_orgs: Set[str] = field(default_factory=set) @dataclass class SightingsData: can_add_sighting: bool can_add_false_positive: bool votes: Dict[str, Votes] = field(default_factory=dict) @classmethod def from_sightings(cls, data: List[Dict[str, Any]], votes: Dict[str, Votes]): can_add_sighting = True can_add_false_positive = True now = datetime.utcnow() for item in data: # Check if a sighting has been reported in the latest 24 hours by this org if can_add_sighting and item.get('type', None) == '0': date_sighting = datetime.utcfromtimestamp(int(item['date_sighting'])) min_vote_hours = current_app.config['SIGHTING_MIN_POSITIVE_VOTE_HOURS'] if date_sighting > (now - timedelta(hours=min_vote_hours)): can_add_sighting = False # Check if there has been a false-positive report by this org elif can_add_false_positive and item.get('type', None) == '1': can_add_false_positive = False return cls(can_add_sighting=can_add_sighting, can_add_false_positive=can_add_false_positive, votes=votes) @validator def defanged_url(value, public=False) -> bool: """ hxxps://defanged.url/path -> https://defanged.url/path """ if value.startswith('hxxp://') or value.startswith('hxxps://'): value = value.replace('hxx', 'htt', 1) # Replace only the first occurrence of hxx with htt return url(value=value, public=public) return False def get_canonical_url(uri: str) -> str: url_components = urllib.parse.urlsplit(uri) # Always end url with / path = url_components.path if not path.endswith('/'): path = f'{url_components.path}/' return urllib.parse.urlunsplit([url_components.scheme, url_components.netloc, path, None, None]) def parse_items(items: Optional[str]) -> List[Attr]: parsed_items: List[Attr] = [] if not items: return parsed_items for item in items.split('\n'): if item: item = ''.join(item.split()) # Normalize whitespace item = urllib.parse.unquote_plus(item) if domain(item): typ = AttrType.DOMAIN search_types = [AttrType.DOMAIN] report_types = [AttrType.DOMAIN] elif url(item): typ = AttrType.URL search_types = [AttrType.URL] report_types = [AttrType.URL] # Remove arguments from URLs item = get_canonical_url(item) elif defanged_url(item): typ = AttrType.URL search_types = [AttrType.URL] report_types = [AttrType.URL] # MISP wants a correct URL, so replace hxx with htt item = item.replace('hxx', 'htt', 1) elif ipv4(item) or ipv6(item): typ = AttrType.IP_SRC search_types = [ AttrType.DOMAIN_IP, AttrType.IP_SRC, AttrType.IP_SRC_PORT, AttrType.IP_DST, AttrType.IP_DST_PORT, ] report_types = [AttrType.IP_SRC] elif md5(item): typ = AttrType.MD5 search_types = [AttrType.MD5, AttrType.FILENAME_MD5] report_types = [AttrType.MD5] elif sha1(item): typ = AttrType.SHA1 search_types = [AttrType.SHA1, AttrType.FILENAME_SHA1] report_types = [AttrType.SHA1] elif sha256(item): typ = AttrType.SHA256 search_types = [AttrType.SHA256, AttrType.FILENAME_SHA256] report_types = [AttrType.SHA256] else: raise ParseException(f'Could not parse {item}') parsed_items.append(Attr(value=item, type=typ, search_types=search_types, report_types=report_types)) return parsed_items def parse_item(item: Optional[str]) -> Optional[Attr]: try: items = parse_items(item) except ParseException: return None if not items: return None return items[0] def get_ipaddr_or_eppn() -> str: """ Uses eppn if supplied else remote address for rate limiting """ current_app.logger.debug('REQUEST ENVIRONMENT:') current_app.logger.debug(request.environ) identifier = request.environ.get('HTTP_EPPN', None) current_app.logger.debug(f'Identifier from request environment: {identifier}') if not identifier: current_app.logger.warning('HTTP_EPPN is missing from request environment') identifier = get_ipaddr() current_app.logger.debug(f'Identifier from get_ipaddr: {identifier}') return identifier def get_user() -> User: identifier = get_ipaddr_or_eppn() return User( identifier=identifier, is_trusted_user=is_trusted_user(identifier), in_trusted_org=in_trusted_orgs(identifier), org_domain=get_org_domain(identifier), ) def is_trusted_user(userid: str) -> bool: """ Checks the eppn against a whitelist """ if userid in current_app.trusted_users: current_app.logger.debug(f'User with id {userid} is a trusted user') return True current_app.logger.debug(f'User with id {userid} IS NOT a trusted user') return False def get_org_domain(userid: str) -> str: return userid.split('@')[-1].lower() def in_trusted_orgs(userid: str) -> bool: org_domain = get_org_domain(userid) return org_domain in current_app.trusted_orgs['org_domains'] def get_sightings_data(user: User, search_result: List[Dict[str, Any]]): attribute_votes = {} org_sightings = [] with misp_api_for() as api: for item in search_result: votes = Votes() for sighting in api.sighting_lookup(attribute_id=item['id']): org_name = sighting['source'].replace(current_app.config["SIGHTING_SOURCE_PREFIX"], '') if sighting['type'] == '0': votes.positives += 1 votes.positive_orgs.add(org_name) elif sighting['type'] == '1': votes.negatives += 1 votes.negative_orgs.add(org_name) attribute_votes[item['id']] = votes with misp_api_for(user) as org_api: org_sightings.extend( org_api.sighting_lookup( attribute_id=item['id'], source=f'{current_app.config['SIGHTING_SOURCE_PREFIX']}{user.org_domain}', ) ) return SightingsData.from_sightings(data=org_sightings, votes=attribute_votes) @contextmanager def misp_api_for(user: Optional[User] = None) -> Iterator[MISPApi]: if user is None: # Use default api key as org specific api keys return org specific data user = User(identifier='default', is_trusted_user=False, in_trusted_org=False, org_domain='default') current_app.logger.debug('Default user used for api call') current_app.logger.debug(f'User {user.identifier} mapped to domain {user.org_domain}') # Lazy load apis per org if user.org_domain not in current_app.misp_apis and user.org_domain in current_app.trusted_orgs['org_domains']: try: current_app.misp_apis[user.org_domain] = MISPApi( current_app.config['MISP_URL'], current_app.trusted_orgs['org_domains'][user.org_domain], current_app.config['MISP_VERIFYCERT'], ) current_app.logger.info(f'Loaded api for {user.org_domain}') except PyMISPError: abort(400, 'Authentication failed. Make sure your organizations api key is up to date.') except Exception as ex: current_app.logger.exception(f'Could not load domain mapping for {user.org_domain}: {ex}') api = current_app.misp_apis.get(user.org_domain) if api is None: current_app.logger.debug('Using default api') yield current_app.misp_apis['default'] else: current_app.logger.debug(f'Using {user.org_domain} api') yield api def utc_now() -> datetime: """Return current time with tz=UTC""" return datetime.now(tz=timezone.utc)
# -*- coding: utf-8 -*- __author__ = 'lundberg' import urllib.parse from contextlib import contextmanager from dataclasses import dataclass, field from datetime import datetime, timedelta, timezone from typing import Any, Dict, Iterator, List, Optional, Set from flask import abort, current_app, request from flask_limiter.util import get_ipaddr from pymisp import PyMISPError from validators import domain, ipv4, ipv6, md5, sha1, sha256, url, validator from ioc_lookup.misp_api import Attr, AttrType, MISPApi class ParseException(Exception): pass @dataclass class User: identifier: str is_trusted_user: bool in_trusted_org: bool org_domain: str @dataclass class Votes: positives: int = 0 positive_orgs: Set[str] = field(default_factory=set) negatives: int = 0 negative_orgs: Set[str] = field(default_factory=set) @dataclass class SightingsData: can_add_sighting: bool can_add_false_positive: bool votes: Dict[str, Votes] = field(default_factory=dict) @classmethod def from_sightings(cls, data: List[Dict[str, Any]], votes: Dict[str, Votes]): can_add_sighting = True can_add_false_positive = True now = datetime.utcnow() for item in data: # Check if a sighting has been reported in the latest 24 hours by this org if can_add_sighting and item.get('type', None) == '0': date_sighting = datetime.utcfromtimestamp(int(item['date_sighting'])) min_vote_hours = current_app.config['SIGHTING_MIN_POSITIVE_VOTE_HOURS'] if date_sighting > (now - timedelta(hours=min_vote_hours)): can_add_sighting = False # Check if there has been a false-positive report by this org elif can_add_false_positive and item.get('type', None) == '1': can_add_false_positive = False return cls(can_add_sighting=can_add_sighting, can_add_false_positive=can_add_false_positive, votes=votes) @validator def defanged_url(value, public=False) -> bool: """ hxxps://defanged.url/path -> https://defanged.url/path """ if value.startswith('hxxp://') or value.startswith('hxxps://'): value = value.replace('hxx', 'htt', 1) # Replace only the first occurrence of hxx with htt return url(value=value, public=public) return False def get_canonical_url(uri: str) -> str: url_components = urllib.parse.urlsplit(uri) # Always end url with / path = url_components.path if not path.endswith('/'): path = f'{url_components.path}/' return urllib.parse.urlunsplit([url_components.scheme, url_components.netloc, path, None, None]) def parse_items(items: Optional[str]) -> List[Attr]: parsed_items: List[Attr] = [] if not items: return parsed_items for item in items.split('\n'): if item: item = ''.join(item.split()) # Normalize whitespace item = urllib.parse.unquote_plus(item) if domain(item): typ = AttrType.DOMAIN search_types = [AttrType.DOMAIN] report_types = [AttrType.DOMAIN] elif url(item): typ = AttrType.URL search_types = [AttrType.URL] report_types = [AttrType.URL] # Remove arguments from URLs item = get_canonical_url(item) elif defanged_url(item): typ = AttrType.URL search_types = [AttrType.URL] report_types = [AttrType.URL] # MISP wants a correct URL, so replace hxx with htt item = item.replace('hxx', 'htt', 1) elif ipv4(item) or ipv6(item): typ = AttrType.IP_SRC search_types = [ AttrType.DOMAIN_IP, AttrType.IP_SRC, AttrType.IP_SRC_PORT, AttrType.IP_DST, AttrType.IP_DST_PORT, ] report_types = [AttrType.IP_SRC] elif md5(item): typ = AttrType.MD5 search_types = [AttrType.MD5, AttrType.FILENAME_MD5] report_types = [AttrType.MD5] elif sha1(item): typ = AttrType.SHA1 search_types = [AttrType.SHA1, AttrType.FILENAME_SHA1] report_types = [AttrType.SHA1] elif sha256(item): typ = AttrType.SHA256 search_types = [AttrType.SHA256, AttrType.FILENAME_SHA256] report_types = [AttrType.SHA256] else: raise ParseException(f'Could not parse {item}') parsed_items.append(Attr(value=item, type=typ, search_types=search_types, report_types=report_types)) return parsed_items def parse_item(item: Optional[str]) -> Optional[Attr]: try: items = parse_items(item) except ParseException: return None if not items: return None return items[0] def get_ipaddr_or_eppn() -> str: """ Uses eppn if supplied else remote address for rate limiting """ current_app.logger.debug('REQUEST ENVIRONMENT:') current_app.logger.debug(request.environ) identifier = request.environ.get('HTTP_EPPN', None) current_app.logger.debug(f'Identifier from request environment: {identifier}') if not identifier: current_app.logger.warning('HTTP_EPPN is missing from request environment') identifier = get_ipaddr() current_app.logger.debug(f'Identifier from get_ipaddr: {identifier}') return identifier def get_user() -> User: identifier = get_ipaddr_or_eppn() return User( identifier=identifier, is_trusted_user=is_trusted_user(identifier), in_trusted_org=in_trusted_orgs(identifier), org_domain=get_org_domain(identifier), ) def is_trusted_user(userid: str) -> bool: """ Checks the eppn against a whitelist """ if userid in current_app.trusted_users: current_app.logger.debug(f'User with id {userid} is a trusted user') return True current_app.logger.debug(f'User with id {userid} IS NOT a trusted user') return False def get_org_domain(userid: str) -> str: return userid.split('@')[-1].lower() def in_trusted_orgs(userid: str) -> bool: org_domain = get_org_domain(userid) return org_domain in current_app.trusted_orgs['org_domains'] def get_sightings_data(user: User, search_result: List[Dict[str, Any]]): attribute_votes = {} org_sightings = [] with misp_api_for() as api: for item in search_result: votes = Votes() for sighting in api.sighting_lookup(attribute_id=item['id']): org_name = sighting['source'].replace(current_app.config["SIGHTING_SOURCE_PREFIX"], '') if sighting['type'] == '0': votes.positives += 1 votes.positive_orgs.add(org_name) elif sighting['type'] == '1': votes.negatives += 1 votes.negative_orgs.add(org_name) attribute_votes[item['id']] = votes with misp_api_for(user) as org_api: org_sightings.extend( org_api.sighting_lookup( attribute_id=item['id'], source=f'{current_app.config["SIGHTING_SOURCE_PREFIX"]}{user.org_domain}', ) ) return SightingsData.from_sightings(data=org_sightings, votes=attribute_votes) @contextmanager def misp_api_for(user: Optional[User] = None) -> Iterator[MISPApi]: if user is None: # Use default api key as org specific api keys return org specific data user = User(identifier='default', is_trusted_user=False, in_trusted_org=False, org_domain='default') current_app.logger.debug('Default user used for api call') current_app.logger.debug(f'User {user.identifier} mapped to domain {user.org_domain}') # Lazy load apis per org if user.org_domain not in current_app.misp_apis and user.org_domain in current_app.trusted_orgs['org_domains']: try: current_app.misp_apis[user.org_domain] = MISPApi( current_app.config['MISP_URL'], current_app.trusted_orgs['org_domains'][user.org_domain], current_app.config['MISP_VERIFYCERT'], ) current_app.logger.info(f'Loaded api for {user.org_domain}') except PyMISPError: abort(400, 'Authentication failed. Make sure your organizations api key is up to date.') except Exception as ex: current_app.logger.exception(f'Could not load domain mapping for {user.org_domain}: {ex}') api = current_app.misp_apis.get(user.org_domain) if api is None: current_app.logger.debug('Using default api') yield current_app.misp_apis['default'] else: current_app.logger.debug(f'Using {user.org_domain} api') yield api def utc_now() -> datetime: """Return current time with tz=UTC""" return datetime.now(tz=timezone.utc)
from enum import Enum from typing import NewType, NamedTuple, Optional, Mapping, Sequence, Any, List import typeit from inflection import camelize from typeit.schema import Invalid __all__ = ( 'TypeGenerator', 'ContentTypeTag', 'Ref', 'EmptyValue', ) ContentTypeFormat = NewType('ContentTypeFormat', str) MediaTypeCharset = NewType('MediaTypeCharset', str) class ContentTypeTag(NamedTuple): format: ContentTypeFormat charset: Optional[MediaTypeCharset] class ContentTypeTagSchema(typeit.schema.primitives.Str): def deserialize(self, node, cstruct: str) -> ContentTypeTag: """ Converts input string value ``cstruct`` to ``ContentTypeTag`` """ try: tag_str = super().deserialize(node, cstruct) except Invalid as e: error = Invalid(node, "Media Type should be a string", cstruct) error.add(e) raise error media_format, *param = tag_str.split(';') typed_format = ContentTypeFormat(media_format) if param: param = [x for x in param[0].split('charset=') if x.strip()] if param: charset = param[0] else: charset = None else: charset = None return ContentTypeTag( format=typed_format, charset=charset ) def serialize(self, node, appstruct: ContentTypeTag) -> str: """ Converts ``ContentTypeTag`` back to string value suitable for JSON/YAML """ rv: List = [appstruct.format] if appstruct.charset: rv.extend([';', "charset=", appstruct.charset]) return super().serialize(node, ''.join(rv)) class RefTo(Enum): SCHEMAS = '#/components/schemas/' LINKS = '#/components/links/' PARAMS = '#/components/parameters/' RESPONSES = '#/components/responses/' HEADERS = '#/components/headers/' EXAMPLES = '#/components/examples/' REQUEST_BODIES = '#/components/requestBodies/' SECURITY_SCHEMES = '#/components/securitySchemes/' CALLBACKS = '#/components/callbacks/' class Ref(NamedTuple): location: RefTo name: str class RefSchema(typeit.schema.primitives.Str): REF_PREFIX: Sequence[str] = ['#', 'components'] REF_LOCATIONS: Mapping[str, RefTo] = { 'schemas': RefTo.SCHEMAS, 'links': RefTo.LINKS, 'parameters': RefTo.PARAMS, 'responses': RefTo.RESPONSES, 'headers': RefTo.HEADERS, 'examples': RefTo.EXAMPLES, 'requestBodies': RefTo.REQUEST_BODIES, 'securitySchemes': RefTo.SECURITY_SCHEMES, 'callbacks': RefTo.CALLBACKS, } def deserialize(self, node, cstruct: str) -> Ref: """ Converts input string value ``cstruct`` to ``Ref`` """ try: ref_str = super().deserialize(node, cstruct) except Invalid as e: error = Invalid(node, "Reference should be a string", cstruct) error.add(e) raise error try: *prefix, location, ref_name = ref_str.split('/') except (ValueError, AttributeError): raise Invalid(node, "Invalid reference format", ref_str) if prefix != self.REF_PREFIX: raise Invalid(node, f"Reference is not prefixed with {"/".join(self.REF_PREFIX)}", ref_str) try: ref_location = self.REF_LOCATIONS[location] except KeyError: raise Invalid(node, f"Unrecognised reference location '{location}'", ref_str) return Ref(ref_location, ref_name) def serialize(self, node, appstruct: Ref) -> str: """ Converts ``Ref`` back to string value suitable for JSON/YAML """ rv = [appstruct.location.value, appstruct.name] return super().serialize(node, ''.join(rv)) class EmptyValue(NamedTuple): """ Sometimes spec contains schemas like: { "type": "array", "items": {} } In that case we need a strict type that would check that its serialized representation exactly matches the empty schema value {}. This object serves that purpose. """ pass _empty = EmptyValue() class EmptyValueSchema(typeit.schema.meta.SchemaType): def deserialize(self, node, cstruct: Any) -> EmptyValue: """ Converts input value ``cstruct`` to ``EmptyValue`` """ if cstruct != {}: error = Invalid(node, "Not an empty type", cstruct) raise error return _empty def serialize(self, node, appstruct: EmptyValue) -> Mapping[Any, Any]: """ Converts ``EmptyValue`` back to a value suitable for JSON/YAML """ return {} TypeGenerator = (typeit.TypeConstructor & ContentTypeTagSchema[ContentTypeTag] # type: ignore & RefSchema[Ref] # type: ignore & EmptyValueSchema[EmptyValue] # type: ignore & typeit.flags.GlobalNameOverride(lambda x: camelize(x, uppercase_first_letter=False)) )
from enum import Enum from typing import NewType, NamedTuple, Optional, Mapping, Sequence, Any, List import typeit from inflection import camelize from typeit.schema import Invalid __all__ = ( 'TypeGenerator', 'ContentTypeTag', 'Ref', 'EmptyValue', ) ContentTypeFormat = NewType('ContentTypeFormat', str) MediaTypeCharset = NewType('MediaTypeCharset', str) class ContentTypeTag(NamedTuple): format: ContentTypeFormat charset: Optional[MediaTypeCharset] class ContentTypeTagSchema(typeit.schema.primitives.Str): def deserialize(self, node, cstruct: str) -> ContentTypeTag: """ Converts input string value ``cstruct`` to ``ContentTypeTag`` """ try: tag_str = super().deserialize(node, cstruct) except Invalid as e: error = Invalid(node, "Media Type should be a string", cstruct) error.add(e) raise error media_format, *param = tag_str.split(';') typed_format = ContentTypeFormat(media_format) if param: param = [x for x in param[0].split('charset=') if x.strip()] if param: charset = param[0] else: charset = None else: charset = None return ContentTypeTag( format=typed_format, charset=charset ) def serialize(self, node, appstruct: ContentTypeTag) -> str: """ Converts ``ContentTypeTag`` back to string value suitable for JSON/YAML """ rv: List = [appstruct.format] if appstruct.charset: rv.extend([';', "charset=", appstruct.charset]) return super().serialize(node, ''.join(rv)) class RefTo(Enum): SCHEMAS = '#/components/schemas/' LINKS = '#/components/links/' PARAMS = '#/components/parameters/' RESPONSES = '#/components/responses/' HEADERS = '#/components/headers/' EXAMPLES = '#/components/examples/' REQUEST_BODIES = '#/components/requestBodies/' SECURITY_SCHEMES = '#/components/securitySchemes/' CALLBACKS = '#/components/callbacks/' class Ref(NamedTuple): location: RefTo name: str class RefSchema(typeit.schema.primitives.Str): REF_PREFIX: Sequence[str] = ['#', 'components'] REF_LOCATIONS: Mapping[str, RefTo] = { 'schemas': RefTo.SCHEMAS, 'links': RefTo.LINKS, 'parameters': RefTo.PARAMS, 'responses': RefTo.RESPONSES, 'headers': RefTo.HEADERS, 'examples': RefTo.EXAMPLES, 'requestBodies': RefTo.REQUEST_BODIES, 'securitySchemes': RefTo.SECURITY_SCHEMES, 'callbacks': RefTo.CALLBACKS, } def deserialize(self, node, cstruct: str) -> Ref: """ Converts input string value ``cstruct`` to ``Ref`` """ try: ref_str = super().deserialize(node, cstruct) except Invalid as e: error = Invalid(node, "Reference should be a string", cstruct) error.add(e) raise error try: *prefix, location, ref_name = ref_str.split('/') except (ValueError, AttributeError): raise Invalid(node, "Invalid reference format", ref_str) if prefix != self.REF_PREFIX: raise Invalid(node, f"Reference is not prefixed with {'/'.join(self.REF_PREFIX)}", ref_str) try: ref_location = self.REF_LOCATIONS[location] except KeyError: raise Invalid(node, f"Unrecognised reference location '{location}'", ref_str) return Ref(ref_location, ref_name) def serialize(self, node, appstruct: Ref) -> str: """ Converts ``Ref`` back to string value suitable for JSON/YAML """ rv = [appstruct.location.value, appstruct.name] return super().serialize(node, ''.join(rv)) class EmptyValue(NamedTuple): """ Sometimes spec contains schemas like: { "type": "array", "items": {} } In that case we need a strict type that would check that its serialized representation exactly matches the empty schema value {}. This object serves that purpose. """ pass _empty = EmptyValue() class EmptyValueSchema(typeit.schema.meta.SchemaType): def deserialize(self, node, cstruct: Any) -> EmptyValue: """ Converts input value ``cstruct`` to ``EmptyValue`` """ if cstruct != {}: error = Invalid(node, "Not an empty type", cstruct) raise error return _empty def serialize(self, node, appstruct: EmptyValue) -> Mapping[Any, Any]: """ Converts ``EmptyValue`` back to a value suitable for JSON/YAML """ return {} TypeGenerator = (typeit.TypeConstructor & ContentTypeTagSchema[ContentTypeTag] # type: ignore & RefSchema[Ref] # type: ignore & EmptyValueSchema[EmptyValue] # type: ignore & typeit.flags.GlobalNameOverride(lambda x: camelize(x, uppercase_first_letter=False)) )
# Copyright 2020 The GenoML Authors. All Rights Reserved. # # 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 # # http://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. # ============================================================================== import argparse import functools import sys from genoml import utils from genoml import dependencies from genoml.cli import continuous_supervised_train, continuous_supervised_tune, \ continuous_supervised_test, discrete_supervised_train, \ discrete_supervised_tune, discrete_supervised_test, munging, harmonizing def handle_main(): entry_points = [ {"name": "continuous", "handler": handle_continuous, "description": "for processing continuous datatypes (ex: age at onset)"}, {"name": "discrete", "handler": handle_discrete, "description": "for processing discrete datatypes (ex: case vs. control status)"}, {"name": "harmonize", "handler": handle_harmonize, "description": "for harmonizing incoming test datasets to use the same SNPs and reference alleles prior to munging, training, and testing"}, ] handle_dispatcher(entry_points, "genoml", 0) def handle_continuous(): entry_points = [ {"name": "supervised", "handler": handle_continuous_supervised, "description": "choice of munge, train, tune, or test your continuous dataset must be specified"}, ] handle_dispatcher(entry_points, "genoml continuous", 1) def handle_discrete(): entry_points = [ {"name": "supervised", "handler": handle_discrete_supervised, "description": "choice of munge, train, tune, or test your discrete dataset must be specified"}, ] handle_dispatcher(entry_points, "genoml discrete", 1) def handle_continuous_supervised(): entry_points = [ {"name": "munge", "handler": handle_continuous_supervised_munge, "description": "for supervised munging and preprocessing of your continuous dataset prior to training"}, {"name": "train", "handler": handle_continuous_supervised_train, "description": "for supervised training of your munged continuous dataset by competing different algorithms"}, {"name": "tune", "handler": handle_continuous_supervised_tune, "description": "for supervised tuning of your munged and trained continuous dataset"}, {"name": "test", "handler": handle_continuous_supervised_test, "description": "for supervised testing of your model generated on continuous data on unseen continuous data (after its been harmonized and munged)"}, ] handle_dispatcher(entry_points, "genoml continuous supervised", 2) def handle_discrete_supervised(): entry_points = [ {"name": "munge", "handler": handle_discrete_supervised_munge, "description": "for supervised munging and preprocessing of your discrete dataset prior to training"}, {"name": "train", "handler": handle_discrete_supervised_train, "description": "for supervised training of your munged discrete dataset by competing different algorithms"}, {"name": "tune", "handler": handle_discrete_supervised_tune, "description": "for supervised tuning of your munged and trained discrete dataset"}, {"name": "test", "handler": handle_discrete_supervised_test, "description": "for supervised testing of your model generated on discrete data on unseen discrete data (after its been harmonized and munged)"}, ] handle_dispatcher(entry_points, "genoml discrete supervised", 2) def handle_harmonize(): handle_endpoints("genoml harmonize", ["test_geno_prefix", "test_prefix", "ref_model_prefix", "training_snps_alleles"], harmonizing.main, 1) def handle_continuous_supervised_munge(): handle_endpoints("genoml discrete supervised munge", ["prefix", "impute", "geno", "skip_prune", "r2_cutoff", "pheno", "addit", "feature_selection", "gwas", "p", "vif", "iter", "ref_cols_harmonize", "umap_reduce", "adjust_data", "adjust_normalize","target_features", "confounders"], functools.partial(munging.main, data_type="c"), 3) def handle_continuous_supervised_train(): handle_endpoints("genoml continuous supervised train", ["prefix", "export_predictions", "matching_columns"], continuous_supervised_train.main, 3) def handle_continuous_supervised_tune(): handle_endpoints("genoml continuous supervised tune", ["prefix", "max_tune", "n_cv", "matching_columns"], continuous_supervised_tune.main, 3) def handle_continuous_supervised_test(): handle_endpoints("genoml continuous supervised test", ["prefix", "test_prefix", "ref_model_prefix"], continuous_supervised_test.main, 3) def handle_discrete_supervised_munge(): handle_endpoints("genoml discrete supervised munge", ["prefix", "impute", "geno", "skip_prune", "r2_cutoff", "pheno", "addit", "feature_selection", "gwas", "p", "vif", "iter", "ref_cols_harmonize", "umap_reduce", "adjust_data", "adjust_normalize","target_features", "confounders"], functools.partial(munging.main, data_type="d"), 3) def handle_discrete_supervised_train(): handle_endpoints("genoml discrete supervised train", ["prefix", "metric_max", "prob_hist", "auc", "matching_columns"], discrete_supervised_train.main, 3) def handle_discrete_supervised_tune(): handle_endpoints("genoml discrete supervised tune", ["prefix", "metric_tune", "max_tune", "n_cv", "matching_columns"], discrete_supervised_tune.main, 3) def handle_discrete_supervised_test(): handle_endpoints("genoml discrete supervised test", ["prefix", "test_prefix", "ref_model_prefix"], discrete_supervised_test.main, 3) def handle_dispatcher(entry_points, command_name, level): usage_description = f'{command_name} <command> [<args>]\n' for command in entry_points: usage_description += " {name:15s} {description}\n".format(**command) parser = argparse.ArgumentParser(prog=command_name, description=f'{command_name}', usage=usage_description ) parser.add_argument('command', help='Subcommand to run') args = parser.parse_args(sys.argv[level + 1:level + 2]) candidates = [] for command in entry_points: if command["name"] == args.command: command["handler"]() return if command["name"].startswith(args.command): candidates.append(command) if len(candidates) == 1: candidates[0]["handler"]() return parser.print_usage() print(f'Unrecognized command: {args.command}') exit(1) def add_default_flag(parser, flag_name): if flag_name == "prefix": parser.add_argument('--prefix', type=str, default="GenoML_data", help="Prefix for your output build.") elif flag_name == "metric_max": parser.add_argument('--metric_max', type=str, default='AUC', choices=['AUC', "Balanced_Accuracy", "Specificity", "Sensitivity"], help='How do you want to determine which algorithm' ' performed the best? [default: AUC].') elif flag_name == "verbose": parser.add_argument('-v', '--verbose', action='store_true', default=False, help="Verbose output.") elif flag_name == "matching_columns": parser.add_argument('--matching_columns', type=str, default=None, help="This is the list of intersecting columns " "between reference and testing datasets with " "the suffix *_finalHarmonizedCols_toKeep.txt") elif flag_name == "prob_hist": parser.add_argument('--prob_hist', type=bool, default=False) elif flag_name == "auc": parser.add_argument('--auc', type=bool, default=False) elif flag_name == "export_predictions": parser.add_argument('--export_predictions', type=bool, default=False) elif flag_name == "metric_tune": parser.add_argument('--metric_tune', type=str, default='AUC', choices=['AUC', "Balanced_Accuracy"], help='Using what metric of the best algorithm do ' 'you want to tune on? [default: AUC].') elif flag_name == "max_tune": parser.add_argument('--max_tune', type=int, default=50, help='Max number of tuning iterations: (integer ' 'likely greater than 10). This governs the ' 'length of tuning process, run speed and the ' 'maximum number of possible combinations of ' 'tuning parameters [default: 50].') elif flag_name == "n_cv": parser.add_argument('--n_cv', type=int, default=5, help='Number of cross validations: (integer likely ' 'greater than 3). Here we set the number of ' 'cross-validation runs for the algorithms ' '[default: 5].') elif flag_name == "test_prefix": parser.add_argument('--test_prefix', type=str, default='GenoML_data', help='Prefix for the dataset you would like to ' 'test against your reference model. ' 'Remember, the model will not function well ' 'if it does not include the same features, ' 'and these features should be on the same ' 'numeric scale, you can leave off the ' '\'.dataForML.h5\' suffix.') elif flag_name == "ref_model_prefix": parser.add_argument('--ref_model_prefix', type=str, default='GenoML_model', help='Prefix of your reference model file, ' 'you can leave off the \'.joblib\' suffix.') elif flag_name == "test_geno_prefix": parser.add_argument('--test_geno_prefix', type=str, default='genotype_binaries', help='Prefix of the genotypes for the test ' 'dataset in PLINK binary format.', required=True) elif flag_name == "training_snps_alleles": parser.add_argument('--training_snps_alleles', type=str, default=None, help='File to the SNPs and alleles file generated ' 'in the training phase that we will use to ' 'compare.', required=True) elif flag_name == "pheno": parser.add_argument("--pheno", type=str, default=None, help="Phenotype: (string file path). Path to CSV " "phenotype file [default: None].", required=True) elif flag_name == "geno": parser.add_argument("--geno", type=str, default=None, help="Genotype: (string file path). Path to PLINK " "format genotype file, everything before the " "*.bed/bim/fam [default: None].") elif flag_name == "skip_prune": parser.add_argument("--skip_prune", type=str, default="no", help="[default: no].", choices=["no", "yes"], required=False) elif flag_name == "r2_cutoff": parser.add_argument("--r2_cutoff", type=str, default="0.5", help="How strict would you like your pruning? [default: 0.5].", choices=["0.1", "0.2", "0.3", "0.4", "0.5"], required=False) elif flag_name == "addit": parser.add_argument("--addit", type=str, default=None, help="Additional: (string file path). Path to CSV " "format feature file [default: None].") elif flag_name == "gwas": parser.add_argument("--gwas", type=str, default=None, help="GWAS summary stats: (string file path). " "Path to CSV format external GWAS summary " "statistics containing at least the columns " "SNP and P in the header [default: None].") elif flag_name == "p": parser.add_argument("--p", type=float, default=0.001, help="P threshold for GWAS: (some value between " "0-1). P value to filter your SNP data on [" "default: 0.001].") elif flag_name == "vif": parser.add_argument("--vif", type=int, default=0, help="Variance Inflation Factor (VIF): (integer). " "This is the VIF threshold for pruning " "non-genotype features. We recommend a value " "of 5-10. The default of 0 means no VIF " "filtering will be done. [default: 0].") elif flag_name == "iter": parser.add_argument("--iter", type=int, default=0, help="Iterator: (integer). How many iterations of " "VIF pruning of features do you want to run. " "To save time VIF is run in randomly " "assorted chunks of 1000 features per " "iteration. The default of 1 means only one " "pass through the data. [default: 1].") elif flag_name == "impute": parser.add_argument("--impute", type=str, default="median", help="Imputation: (mean, median). Governs " "secondary imputation and data " "transformation [default: median].", choices=["median", "mean"]) elif flag_name == "feature_selection": parser.add_argument('--feature_selection', type=int, default=0, help='Run a quick tree-based feature selection ' 'routine prior to anything else, here you ' 'input the integer number of estimators ' 'needed, we suggest >= 50. The default of 0 ' 'will skip this functionality. This will ' 'also output a reduced dataset for analyses ' 'in addition to feature ranks. [default: 0]') elif flag_name == "ref_cols_harmonize": parser.add_argument('--ref_cols_harmonize', type=str, default=None, help='Are you now munging a test dataset ' 'following the harmonize step? Here you ' 'input the path to the to the ' '*_refColsHarmonize_toKeep.txt file ' 'generated at that step.') elif flag_name == "umap_reduce": parser.add_argument('--umap_reduce', type=str, default="no", help = 'Would you like to reduce your dimensions with UMAP? [default: no]. Must be run with --confounders flag if yes.', choices=["no", "yes"], required='--confounders' in sys.argv and '--adjust_data' in sys.argv and '--adjust_normalize' in sys.argv) elif flag_name == "adjust_data": parser.add_argument('--adjust_data', type=str, default="no", help = 'Would you like to adjust features and/or confounders in your data? [default: no]', choices=["yes", "no"], required='--adjust_normalize' in sys.argv and '--target_features' in sys.argv or '--confounders' in sys.argv) elif flag_name == "adjust_normalize": parser.add_argument('--adjust_normalize', type=str, default="yes", help = 'Would you like to normalize the features and/or confounders you are adjusting for in your data? [default: yes]', choices=["no", "yes"], required='--adjust_data' in sys.argv and '--target_features' in sys.argv or '--confounders' in sys.argv) elif flag_name == "target_features": parser.add_argument('--target_features', type=str, default=None, help = 'For adjusting data. A .txt file, one column, with a list of features ' 'to adjust (no header). These should correspond to features ' 'in the munged dataset', required='--adjust_data' in sys.argv and '--adjust_normalize' in sys.argv) elif flag_name == "confounders": parser.add_argument('--confounders', type=str, default=None, help = 'For adjusting data. A .csv of confounders to adjust for with ID column and header.' 'Numeric, with no missing data and the ID column' 'is mandatory', required='--adjust_data' in sys.argv and '--adjust_normalize' in sys.argv) else: raise Exception(f"Unknown flag: {flag_name}") def handle_endpoints(command_name, flag_names, endpoint, level): parser = argparse.ArgumentParser(prog=command_name) for name in flag_names: add_default_flag(parser, name) add_default_flag(parser, "verbose") args, unknown = parser.parse_known_args(sys.argv[level + 1:]) if unknown: parser.print_usage() print(f'Unrecognized arguments: {unknown[0]}') exit(1) utils.ContextScope._verbose = args.verbose args = [args.__dict__[name] for name in flag_names] args_string = ", ".join([f"{name}: {value if value else "[None]"}" for name, value in zip(flag_names, args)]) with utils.ContextScope(f"Running {command_name}", description="Args= " + args_string, error=""): dependencies.check_dependencies() endpoint(*args) if __name__ == "__main__": handle_main()
# Copyright 2020 The GenoML Authors. All Rights Reserved. # # 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 # # http://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. # ============================================================================== import argparse import functools import sys from genoml import utils from genoml import dependencies from genoml.cli import continuous_supervised_train, continuous_supervised_tune, \ continuous_supervised_test, discrete_supervised_train, \ discrete_supervised_tune, discrete_supervised_test, munging, harmonizing def handle_main(): entry_points = [ {"name": "continuous", "handler": handle_continuous, "description": "for processing continuous datatypes (ex: age at onset)"}, {"name": "discrete", "handler": handle_discrete, "description": "for processing discrete datatypes (ex: case vs. control status)"}, {"name": "harmonize", "handler": handle_harmonize, "description": "for harmonizing incoming test datasets to use the same SNPs and reference alleles prior to munging, training, and testing"}, ] handle_dispatcher(entry_points, "genoml", 0) def handle_continuous(): entry_points = [ {"name": "supervised", "handler": handle_continuous_supervised, "description": "choice of munge, train, tune, or test your continuous dataset must be specified"}, ] handle_dispatcher(entry_points, "genoml continuous", 1) def handle_discrete(): entry_points = [ {"name": "supervised", "handler": handle_discrete_supervised, "description": "choice of munge, train, tune, or test your discrete dataset must be specified"}, ] handle_dispatcher(entry_points, "genoml discrete", 1) def handle_continuous_supervised(): entry_points = [ {"name": "munge", "handler": handle_continuous_supervised_munge, "description": "for supervised munging and preprocessing of your continuous dataset prior to training"}, {"name": "train", "handler": handle_continuous_supervised_train, "description": "for supervised training of your munged continuous dataset by competing different algorithms"}, {"name": "tune", "handler": handle_continuous_supervised_tune, "description": "for supervised tuning of your munged and trained continuous dataset"}, {"name": "test", "handler": handle_continuous_supervised_test, "description": "for supervised testing of your model generated on continuous data on unseen continuous data (after its been harmonized and munged)"}, ] handle_dispatcher(entry_points, "genoml continuous supervised", 2) def handle_discrete_supervised(): entry_points = [ {"name": "munge", "handler": handle_discrete_supervised_munge, "description": "for supervised munging and preprocessing of your discrete dataset prior to training"}, {"name": "train", "handler": handle_discrete_supervised_train, "description": "for supervised training of your munged discrete dataset by competing different algorithms"}, {"name": "tune", "handler": handle_discrete_supervised_tune, "description": "for supervised tuning of your munged and trained discrete dataset"}, {"name": "test", "handler": handle_discrete_supervised_test, "description": "for supervised testing of your model generated on discrete data on unseen discrete data (after its been harmonized and munged)"}, ] handle_dispatcher(entry_points, "genoml discrete supervised", 2) def handle_harmonize(): handle_endpoints("genoml harmonize", ["test_geno_prefix", "test_prefix", "ref_model_prefix", "training_snps_alleles"], harmonizing.main, 1) def handle_continuous_supervised_munge(): handle_endpoints("genoml discrete supervised munge", ["prefix", "impute", "geno", "skip_prune", "r2_cutoff", "pheno", "addit", "feature_selection", "gwas", "p", "vif", "iter", "ref_cols_harmonize", "umap_reduce", "adjust_data", "adjust_normalize","target_features", "confounders"], functools.partial(munging.main, data_type="c"), 3) def handle_continuous_supervised_train(): handle_endpoints("genoml continuous supervised train", ["prefix", "export_predictions", "matching_columns"], continuous_supervised_train.main, 3) def handle_continuous_supervised_tune(): handle_endpoints("genoml continuous supervised tune", ["prefix", "max_tune", "n_cv", "matching_columns"], continuous_supervised_tune.main, 3) def handle_continuous_supervised_test(): handle_endpoints("genoml continuous supervised test", ["prefix", "test_prefix", "ref_model_prefix"], continuous_supervised_test.main, 3) def handle_discrete_supervised_munge(): handle_endpoints("genoml discrete supervised munge", ["prefix", "impute", "geno", "skip_prune", "r2_cutoff", "pheno", "addit", "feature_selection", "gwas", "p", "vif", "iter", "ref_cols_harmonize", "umap_reduce", "adjust_data", "adjust_normalize","target_features", "confounders"], functools.partial(munging.main, data_type="d"), 3) def handle_discrete_supervised_train(): handle_endpoints("genoml discrete supervised train", ["prefix", "metric_max", "prob_hist", "auc", "matching_columns"], discrete_supervised_train.main, 3) def handle_discrete_supervised_tune(): handle_endpoints("genoml discrete supervised tune", ["prefix", "metric_tune", "max_tune", "n_cv", "matching_columns"], discrete_supervised_tune.main, 3) def handle_discrete_supervised_test(): handle_endpoints("genoml discrete supervised test", ["prefix", "test_prefix", "ref_model_prefix"], discrete_supervised_test.main, 3) def handle_dispatcher(entry_points, command_name, level): usage_description = f'{command_name} <command> [<args>]\n' for command in entry_points: usage_description += " {name:15s} {description}\n".format(**command) parser = argparse.ArgumentParser(prog=command_name, description=f'{command_name}', usage=usage_description ) parser.add_argument('command', help='Subcommand to run') args = parser.parse_args(sys.argv[level + 1:level + 2]) candidates = [] for command in entry_points: if command["name"] == args.command: command["handler"]() return if command["name"].startswith(args.command): candidates.append(command) if len(candidates) == 1: candidates[0]["handler"]() return parser.print_usage() print(f'Unrecognized command: {args.command}') exit(1) def add_default_flag(parser, flag_name): if flag_name == "prefix": parser.add_argument('--prefix', type=str, default="GenoML_data", help="Prefix for your output build.") elif flag_name == "metric_max": parser.add_argument('--metric_max', type=str, default='AUC', choices=['AUC', "Balanced_Accuracy", "Specificity", "Sensitivity"], help='How do you want to determine which algorithm' ' performed the best? [default: AUC].') elif flag_name == "verbose": parser.add_argument('-v', '--verbose', action='store_true', default=False, help="Verbose output.") elif flag_name == "matching_columns": parser.add_argument('--matching_columns', type=str, default=None, help="This is the list of intersecting columns " "between reference and testing datasets with " "the suffix *_finalHarmonizedCols_toKeep.txt") elif flag_name == "prob_hist": parser.add_argument('--prob_hist', type=bool, default=False) elif flag_name == "auc": parser.add_argument('--auc', type=bool, default=False) elif flag_name == "export_predictions": parser.add_argument('--export_predictions', type=bool, default=False) elif flag_name == "metric_tune": parser.add_argument('--metric_tune', type=str, default='AUC', choices=['AUC', "Balanced_Accuracy"], help='Using what metric of the best algorithm do ' 'you want to tune on? [default: AUC].') elif flag_name == "max_tune": parser.add_argument('--max_tune', type=int, default=50, help='Max number of tuning iterations: (integer ' 'likely greater than 10). This governs the ' 'length of tuning process, run speed and the ' 'maximum number of possible combinations of ' 'tuning parameters [default: 50].') elif flag_name == "n_cv": parser.add_argument('--n_cv', type=int, default=5, help='Number of cross validations: (integer likely ' 'greater than 3). Here we set the number of ' 'cross-validation runs for the algorithms ' '[default: 5].') elif flag_name == "test_prefix": parser.add_argument('--test_prefix', type=str, default='GenoML_data', help='Prefix for the dataset you would like to ' 'test against your reference model. ' 'Remember, the model will not function well ' 'if it does not include the same features, ' 'and these features should be on the same ' 'numeric scale, you can leave off the ' '\'.dataForML.h5\' suffix.') elif flag_name == "ref_model_prefix": parser.add_argument('--ref_model_prefix', type=str, default='GenoML_model', help='Prefix of your reference model file, ' 'you can leave off the \'.joblib\' suffix.') elif flag_name == "test_geno_prefix": parser.add_argument('--test_geno_prefix', type=str, default='genotype_binaries', help='Prefix of the genotypes for the test ' 'dataset in PLINK binary format.', required=True) elif flag_name == "training_snps_alleles": parser.add_argument('--training_snps_alleles', type=str, default=None, help='File to the SNPs and alleles file generated ' 'in the training phase that we will use to ' 'compare.', required=True) elif flag_name == "pheno": parser.add_argument("--pheno", type=str, default=None, help="Phenotype: (string file path). Path to CSV " "phenotype file [default: None].", required=True) elif flag_name == "geno": parser.add_argument("--geno", type=str, default=None, help="Genotype: (string file path). Path to PLINK " "format genotype file, everything before the " "*.bed/bim/fam [default: None].") elif flag_name == "skip_prune": parser.add_argument("--skip_prune", type=str, default="no", help="[default: no].", choices=["no", "yes"], required=False) elif flag_name == "r2_cutoff": parser.add_argument("--r2_cutoff", type=str, default="0.5", help="How strict would you like your pruning? [default: 0.5].", choices=["0.1", "0.2", "0.3", "0.4", "0.5"], required=False) elif flag_name == "addit": parser.add_argument("--addit", type=str, default=None, help="Additional: (string file path). Path to CSV " "format feature file [default: None].") elif flag_name == "gwas": parser.add_argument("--gwas", type=str, default=None, help="GWAS summary stats: (string file path). " "Path to CSV format external GWAS summary " "statistics containing at least the columns " "SNP and P in the header [default: None].") elif flag_name == "p": parser.add_argument("--p", type=float, default=0.001, help="P threshold for GWAS: (some value between " "0-1). P value to filter your SNP data on [" "default: 0.001].") elif flag_name == "vif": parser.add_argument("--vif", type=int, default=0, help="Variance Inflation Factor (VIF): (integer). " "This is the VIF threshold for pruning " "non-genotype features. We recommend a value " "of 5-10. The default of 0 means no VIF " "filtering will be done. [default: 0].") elif flag_name == "iter": parser.add_argument("--iter", type=int, default=0, help="Iterator: (integer). How many iterations of " "VIF pruning of features do you want to run. " "To save time VIF is run in randomly " "assorted chunks of 1000 features per " "iteration. The default of 1 means only one " "pass through the data. [default: 1].") elif flag_name == "impute": parser.add_argument("--impute", type=str, default="median", help="Imputation: (mean, median). Governs " "secondary imputation and data " "transformation [default: median].", choices=["median", "mean"]) elif flag_name == "feature_selection": parser.add_argument('--feature_selection', type=int, default=0, help='Run a quick tree-based feature selection ' 'routine prior to anything else, here you ' 'input the integer number of estimators ' 'needed, we suggest >= 50. The default of 0 ' 'will skip this functionality. This will ' 'also output a reduced dataset for analyses ' 'in addition to feature ranks. [default: 0]') elif flag_name == "ref_cols_harmonize": parser.add_argument('--ref_cols_harmonize', type=str, default=None, help='Are you now munging a test dataset ' 'following the harmonize step? Here you ' 'input the path to the to the ' '*_refColsHarmonize_toKeep.txt file ' 'generated at that step.') elif flag_name == "umap_reduce": parser.add_argument('--umap_reduce', type=str, default="no", help = 'Would you like to reduce your dimensions with UMAP? [default: no]. Must be run with --confounders flag if yes.', choices=["no", "yes"], required='--confounders' in sys.argv and '--adjust_data' in sys.argv and '--adjust_normalize' in sys.argv) elif flag_name == "adjust_data": parser.add_argument('--adjust_data', type=str, default="no", help = 'Would you like to adjust features and/or confounders in your data? [default: no]', choices=["yes", "no"], required='--adjust_normalize' in sys.argv and '--target_features' in sys.argv or '--confounders' in sys.argv) elif flag_name == "adjust_normalize": parser.add_argument('--adjust_normalize', type=str, default="yes", help = 'Would you like to normalize the features and/or confounders you are adjusting for in your data? [default: yes]', choices=["no", "yes"], required='--adjust_data' in sys.argv and '--target_features' in sys.argv or '--confounders' in sys.argv) elif flag_name == "target_features": parser.add_argument('--target_features', type=str, default=None, help = 'For adjusting data. A .txt file, one column, with a list of features ' 'to adjust (no header). These should correspond to features ' 'in the munged dataset', required='--adjust_data' in sys.argv and '--adjust_normalize' in sys.argv) elif flag_name == "confounders": parser.add_argument('--confounders', type=str, default=None, help = 'For adjusting data. A .csv of confounders to adjust for with ID column and header.' 'Numeric, with no missing data and the ID column' 'is mandatory', required='--adjust_data' in sys.argv and '--adjust_normalize' in sys.argv) else: raise Exception(f"Unknown flag: {flag_name}") def handle_endpoints(command_name, flag_names, endpoint, level): parser = argparse.ArgumentParser(prog=command_name) for name in flag_names: add_default_flag(parser, name) add_default_flag(parser, "verbose") args, unknown = parser.parse_known_args(sys.argv[level + 1:]) if unknown: parser.print_usage() print(f'Unrecognized arguments: {unknown[0]}') exit(1) utils.ContextScope._verbose = args.verbose args = [args.__dict__[name] for name in flag_names] args_string = ", ".join([f"{name}: {value if value else '[None]'}" for name, value in zip(flag_names, args)]) with utils.ContextScope(f"Running {command_name}", description="Args= " + args_string, error=""): dependencies.check_dependencies() endpoint(*args) if __name__ == "__main__": handle_main()
"""This module defines the programmatic API that can be used to interact with `portray` to generate and view documentation. If you want to extend `portray` or use it directly from within Python - this is the place to start. """ import os import webbrowser from typing import Dict, Optional, Union import hug import mkdocs.commands.gh_deploy from portray import config, logo, render def as_html( directory: str = "", config_file: str = "pyproject.toml", output_dir: str = "site", overwrite: bool = False, modules: list = None, ) -> None: """Produces HTML documentation for a Python project placing it into output_dir. - *directory*: The root folder of your project. - *config_file*: The [TOML](https://github.com/toml-lang/toml#toml) formatted config file you wish to use. - *output_dir*: The directory to place the generated HTML into. - *overwrite*: If set to `True` any existing documentation output will be removed before generating new documentation. Otherwise, if documentation exists in the specified `output_dir` the command will fail with a `DocumentationAlreadyExists` exception. - *modules*: One or more modules to render reference documentation for """ directory = directory if directory else os.getcwd() render.documentation( project_configuration(directory, config_file, modules=modules, output_dir=output_dir), overwrite=overwrite, ) print(logo.ascii_art) print(f"Documentation successfully generated into `{os.path.abspath(output_dir)}` !") def in_browser( directory: str = "", config_file: str = "pyproject.toml", port: int = None, host: str = None, modules: list = None, ) -> None: """Opens your default webbrowser pointing to a locally started development webserver enabling you to browse documentation locally - *directory*: The root folder of your project. - *config_file*: The [TOML](https://github.com/toml-lang/toml#toml) formatted config file you wish to use. - *port*: The port to expose your documentation on (defaults to: `8000`) - *host*: The host to expose your documentation on (defaults to `"127.0.0.1"`) - *modules*: One or more modules to render reference documentation for """ directory = directory if directory else os.getcwd() server(directory=directory, config_file=config_file, open_browser=True, modules=modules) def server( directory: str = "", config_file: str = "pyproject.toml", open_browser: bool = False, port: int = None, host: str = None, modules: list = None, ) -> None: """Runs a development webserver enabling you to browse documentation locally. - *directory*: The root folder of your project. - *config_file*: The [TOML](https://github.com/toml-lang/toml#toml) formatted config file you wish to use. - *open_browser*: If true a browser will be opened pointing at the documentation server - *port*: The port to expose your documentation on (defaults to: `8000`) - *host*: The host to expose your documentation on (defaults to `"127.0.0.1"`) - *modules*: One or more modules to render reference documentation for """ directory = directory if directory else os.getcwd() api = hug.API("Doc Server") project_config = project_configuration(directory, config_file, modules=modules) with render.documentation_in_temp_folder(project_config) as doc_folder: @hug.static("/", api=api) def my_static_dirs(): # pragma: no cover return (doc_folder,) @hug.startup(api=api) def custom_startup(*args, **kwargs): # pragma: no cover print(logo.ascii_art) if open_browser: webbrowser.open_new(f"http://{project_config["host"]}:{project_config["port"]}") api.http.serve( host=host or project_config["host"], port=port or project_config["port"], no_documentation=True, display_intro=False, ) def project_configuration( directory: str = "", config_file: str = "pyproject.toml", modules: list = None, output_dir: str = "site", ) -> dict: """Returns the configuration associated with a project. - *directory*: The root folder of your project. - *config_file*: The [TOML](https://github.com/toml-lang/toml#toml) formatted config file you wish to use. - *modules*: One or more modules to include in the configuration for reference rendering """ overrides: Dict[str, Union[str, list]] = {} if modules: overrides["modules"] = modules if output_dir: overrides["output_dir"] = output_dir directory = directory if directory else os.getcwd() return config.project(directory=directory, config_file=config_file, **overrides) def on_github_pages( directory: str = "", config_file: str = "pyproject.toml", message: str = None, force: bool = False, ignore_version: bool = False, modules: list = None, ) -> None: """Regenerates and deploys the documentation to GitHub pages. - *directory*: The root folder of your project. - *config_file*: The [TOML](https://github.com/toml-lang/toml#toml) formatted config file you wish to use. - *message*: The commit message to use when uploading your documentation. - *force*: Force the push to the repository. - *ignore_version*: Ignore check that build is not being deployed with an old version. - *modules*: One or more modules to render reference documentation for """ directory = directory if directory else os.getcwd() project_config = project_configuration(directory, config_file, modules) with render.documentation_in_temp_folder(project_config): conf = render._mkdocs_config(project_config["mkdocs"]) conf.config_file_path = directory mkdocs.commands.gh_deploy.gh_deploy( conf, message=message, force=force, ignore_version=ignore_version ) print(logo.ascii_art) print("Documentation successfully generated and pushed!")
"""This module defines the programmatic API that can be used to interact with `portray` to generate and view documentation. If you want to extend `portray` or use it directly from within Python - this is the place to start. """ import os import webbrowser from typing import Dict, Optional, Union import hug import mkdocs.commands.gh_deploy from portray import config, logo, render def as_html( directory: str = "", config_file: str = "pyproject.toml", output_dir: str = "site", overwrite: bool = False, modules: list = None, ) -> None: """Produces HTML documentation for a Python project placing it into output_dir. - *directory*: The root folder of your project. - *config_file*: The [TOML](https://github.com/toml-lang/toml#toml) formatted config file you wish to use. - *output_dir*: The directory to place the generated HTML into. - *overwrite*: If set to `True` any existing documentation output will be removed before generating new documentation. Otherwise, if documentation exists in the specified `output_dir` the command will fail with a `DocumentationAlreadyExists` exception. - *modules*: One or more modules to render reference documentation for """ directory = directory if directory else os.getcwd() render.documentation( project_configuration(directory, config_file, modules=modules, output_dir=output_dir), overwrite=overwrite, ) print(logo.ascii_art) print(f"Documentation successfully generated into `{os.path.abspath(output_dir)}` !") def in_browser( directory: str = "", config_file: str = "pyproject.toml", port: int = None, host: str = None, modules: list = None, ) -> None: """Opens your default webbrowser pointing to a locally started development webserver enabling you to browse documentation locally - *directory*: The root folder of your project. - *config_file*: The [TOML](https://github.com/toml-lang/toml#toml) formatted config file you wish to use. - *port*: The port to expose your documentation on (defaults to: `8000`) - *host*: The host to expose your documentation on (defaults to `"127.0.0.1"`) - *modules*: One or more modules to render reference documentation for """ directory = directory if directory else os.getcwd() server(directory=directory, config_file=config_file, open_browser=True, modules=modules) def server( directory: str = "", config_file: str = "pyproject.toml", open_browser: bool = False, port: int = None, host: str = None, modules: list = None, ) -> None: """Runs a development webserver enabling you to browse documentation locally. - *directory*: The root folder of your project. - *config_file*: The [TOML](https://github.com/toml-lang/toml#toml) formatted config file you wish to use. - *open_browser*: If true a browser will be opened pointing at the documentation server - *port*: The port to expose your documentation on (defaults to: `8000`) - *host*: The host to expose your documentation on (defaults to `"127.0.0.1"`) - *modules*: One or more modules to render reference documentation for """ directory = directory if directory else os.getcwd() api = hug.API("Doc Server") project_config = project_configuration(directory, config_file, modules=modules) with render.documentation_in_temp_folder(project_config) as doc_folder: @hug.static("/", api=api) def my_static_dirs(): # pragma: no cover return (doc_folder,) @hug.startup(api=api) def custom_startup(*args, **kwargs): # pragma: no cover print(logo.ascii_art) if open_browser: webbrowser.open_new(f"http://{project_config['host']}:{project_config['port']}") api.http.serve( host=host or project_config["host"], port=port or project_config["port"], no_documentation=True, display_intro=False, ) def project_configuration( directory: str = "", config_file: str = "pyproject.toml", modules: list = None, output_dir: str = "site", ) -> dict: """Returns the configuration associated with a project. - *directory*: The root folder of your project. - *config_file*: The [TOML](https://github.com/toml-lang/toml#toml) formatted config file you wish to use. - *modules*: One or more modules to include in the configuration for reference rendering """ overrides: Dict[str, Union[str, list]] = {} if modules: overrides["modules"] = modules if output_dir: overrides["output_dir"] = output_dir directory = directory if directory else os.getcwd() return config.project(directory=directory, config_file=config_file, **overrides) def on_github_pages( directory: str = "", config_file: str = "pyproject.toml", message: str = None, force: bool = False, ignore_version: bool = False, modules: list = None, ) -> None: """Regenerates and deploys the documentation to GitHub pages. - *directory*: The root folder of your project. - *config_file*: The [TOML](https://github.com/toml-lang/toml#toml) formatted config file you wish to use. - *message*: The commit message to use when uploading your documentation. - *force*: Force the push to the repository. - *ignore_version*: Ignore check that build is not being deployed with an old version. - *modules*: One or more modules to render reference documentation for """ directory = directory if directory else os.getcwd() project_config = project_configuration(directory, config_file, modules) with render.documentation_in_temp_folder(project_config): conf = render._mkdocs_config(project_config["mkdocs"]) conf.config_file_path = directory mkdocs.commands.gh_deploy.gh_deploy( conf, message=message, force=force, ignore_version=ignore_version ) print(logo.ascii_art) print("Documentation successfully generated and pushed!")
import copy import os import tempfile from functools import wraps from itertools import groupby from typing import List, Optional, Tuple, TypeVar, Union import numpy as np import pyarrow as pa from . import config from .utils.logging import get_logger logger = get_logger(__name__) def inject_arrow_table_documentation(arrow_table_method): def wrapper(method): out = wraps(arrow_table_method)(method) out.__doc__ = out.__doc__.replace("pyarrow.Table", "Table") return out return wrapper def _in_memory_arrow_table_from_file(filename: str) -> pa.Table: in_memory_stream = pa.input_stream(filename) opened_stream = pa.ipc.open_stream(in_memory_stream) pa_table = opened_stream.read_all() return pa_table def _in_memory_arrow_table_from_buffer(buffer: pa.Buffer) -> pa.Table: stream = pa.BufferReader(buffer) opened_stream = pa.ipc.open_stream(stream) table = opened_stream.read_all() return table def _memory_mapped_arrow_table_from_file(filename: str) -> pa.Table: memory_mapped_stream = pa.memory_map(filename) opened_stream = pa.ipc.open_stream(memory_mapped_stream) pa_table = opened_stream.read_all() return pa_table def _write_table_to_file(table: pa.Table, filename: str) -> int: with open(filename, "wb") as sink: writer = pa.RecordBatchStreamWriter(sink=sink, schema=table.schema) batches: List[pa.RecordBatch] = table.to_batches() for batch in batches: writer.write_batch(batch) writer.close() return sum(batch.nbytes for batch in batches) def _deepcopy(x, memo: dict): """deepcopy a regular class instance""" cls = x.__class__ result = cls.__new__(cls) memo[id(x)] = result for k, v in x.__dict__.items(): setattr(result, k, copy.deepcopy(v, memo)) return result def _interpolation_search(arr: List[int], x: int) -> int: """ Return the position i of a sorted array so that arr[i] <= x < arr[i+1] Args: arr (:obj:`List[int]`): non-empty sorted list of integers x (:obj:`int`): query Returns: `int`: the position i so that arr[i] <= x < arr[i+1] Raises: `IndexError`: if the array is empty or if the query is outside the array values """ i, j = 0, len(arr) - 1 while i < j and arr[i] <= x < arr[j]: k = i + ((j - i) * (x - arr[i]) // (arr[j] - arr[i])) if arr[k] <= x < arr[k + 1]: return k elif arr[k] < x: i, j = k + 1, j else: i, j = i, k raise IndexError(f"Invalid query '{x}" for size {arr[-1] if len(arr) else "none"}.") class IndexedTableMixin: def __init__(self, table: pa.Table): self._schema = table.schema self._batches = table.to_batches() self._offsets: np.ndarray = np.cumsum([0] + [len(b) for b in self._batches], dtype=np.int64) def fast_gather(self, indices: Union[List[int], np.ndarray]) -> pa.Table: """ Create a pa.Table by gathering the records at the records at the specified indices. Should be faster than pa.concat_tables(table.fast_slice(int(i) % table.num_rows, 1) for i in indices) since NumPy can compute the binary searches in parallel, highly optimized C """ assert len(indices), "Indices must be non-empty" batch_indices = np.searchsorted(self._offsets, indices, side="right") - 1 return pa.Table.from_batches( [ self._batches[batch_idx].slice(i - self._offsets[batch_idx], 1) for batch_idx, i in zip(batch_indices, indices) ], schema=self._schema, ) def fast_slice(self, offset=0, length=None) -> pa.Table: """ Slice the Table using interpolation search. The behavior is the same as :obj:`pyarrow.Table.slice` but it's significantly faster. Interpolation search is used to find the start and end indexes of the batches we want to keep. The batches to keep are then concatenated to form the sliced Table. """ if offset < 0: raise IndexError("Offset must be non-negative") elif offset >= self._offsets[-1] or (length is not None and length <= 0): return pa.Table.from_batches([], schema=self._schema) i = _interpolation_search(self._offsets, offset) if length is None or length + offset >= self._offsets[-1]: batches = self._batches[i:] batches[0] = batches[0].slice(offset - self._offsets[i]) else: j = _interpolation_search(self._offsets, offset + length - 1) batches = self._batches[i : j + 1] batches[-1] = batches[-1].slice(0, offset + length - self._offsets[j]) batches[0] = batches[0].slice(offset - self._offsets[i]) return pa.Table.from_batches(batches, schema=self._schema) class Table(IndexedTableMixin): """ Wraps a pyarrow Table by using composition. This is the base class for InMemoryTable, MemoryMappedTable and ConcatenationTable. It implements all the basic attributes/methods of the pyarrow Table class except the Table transforms: slice, filter, flatten, combine_chunks, cast, add_column, append_column, remove_column, set_column, rename_columns and drop. The implementation of these methods differs for the subclasses. """ def __init__(self, table: pa.Table): super().__init__(table) self.table = table def __deepcopy__(self, memo: dict): # arrow tables are immutable, so there's no need to copy self.table # moreover calling deepcopy on a pyarrow table seems to make pa.total_allocated_bytes() decrease for some reason # by adding it to the memo, self.table won't be copied memo[id(self.table)] = self.table # same for the recordbatches used by the index memo[id(self._batches)] = list(self._batches) return _deepcopy(self, memo) def __getstate__(self): # We can't pickle objects that are bigger than 4GiB, or it causes OverflowError # So we write the table on disk instead if self.table.nbytes >= config.MAX_TABLE_NBYTES_FOR_PICKLING: table = self.table with tempfile.NamedTemporaryFile("wb", delete=False, suffix=".arrow") as tmp_file: filename = tmp_file.name logger.debug( f"Attempting to pickle a table bigger than 4GiB. Writing it on the disk instead at {filename}" ) _write_table_to_file(table=table, filename=filename) return {"path": filename} else: return {"table": self.table} def __setstate__(self, state): if "path" in state: filename = state["path"] logger.debug(f"Unpickling a big table from the disk at {filename}") table = _in_memory_arrow_table_from_file(filename) logger.debug(f"Removing temporary table file at {filename}") os.remove(filename) else: table = state["table"] Table.__init__(self, table) @inject_arrow_table_documentation(pa.Table.validate) def validate(self, *args, **kwargs): return self.table.validate(*args, **kwargs) @inject_arrow_table_documentation(pa.Table.equals) def equals(self, *args, **kwargs): args = tuple(arg.table if isinstance(arg, Table) else arg for arg in args) kwargs = {k: v.table if isinstance(v, Table) else v for k, v in kwargs} return self.table.equals(*args, **kwargs) @inject_arrow_table_documentation(pa.Table.to_batches) def to_batches(self, *args, **kwargs): return self.table.to_batches(*args, **kwargs) @inject_arrow_table_documentation(pa.Table.to_pydict) def to_pydict(self, *args, **kwargs): return self.table.to_pydict(*args, **kwargs) @inject_arrow_table_documentation(pa.Table.to_pandas) def to_pandas(self, *args, **kwargs): return self.table.to_pandas(*args, **kwargs) def to_string(self, *args, **kwargs): return self.table.to_string(*args, **kwargs) @inject_arrow_table_documentation(pa.Table.field) def field(self, *args, **kwargs): return self.table.field(*args, **kwargs) @inject_arrow_table_documentation(pa.Table.column) def column(self, *args, **kwargs): return self.table.column(*args, **kwargs) @inject_arrow_table_documentation(pa.Table.itercolumns) def itercolumns(self, *args, **kwargs): return self.table.itercolumns(*args, **kwargs) @property def schema(self): return self.table.schema @property def columns(self): return self.table.columns @property def num_columns(self): return self.table.num_columns @property def num_rows(self): return self.table.num_rows @property def shape(self): return self.table.shape @property def nbytes(self): return self.table.nbytes @property def column_names(self): return self.table.column_names def __eq__(self, other): return self.equals(other) def __getitem__(self, i): return self.table[i] def __len__(self): return len(self.table) def __repr__(self): return self.table.__repr__().replace("pyarrow.Table", self.__class__.__name__) def __str__(self): return self.table.__str__().replace("pyarrow.Table", self.__class__.__name__) @inject_arrow_table_documentation(pa.Table.slice) def slice(self, *args, **kwargs): raise NotImplementedError() @inject_arrow_table_documentation(pa.Table.filter) def filter(self, *args, **kwargs): raise NotImplementedError() @inject_arrow_table_documentation(pa.Table.flatten) def flatten(self, *args, **kwargs): raise NotImplementedError() @inject_arrow_table_documentation(pa.Table.combine_chunks) def combine_chunks(self, *args, **kwargs): raise NotImplementedError() @inject_arrow_table_documentation(pa.Table.cast) def cast(self, *args, **kwargs): raise NotImplementedError() @inject_arrow_table_documentation(pa.Table.add_column) def add_column(self, *args, **kwargs): raise NotImplementedError() @inject_arrow_table_documentation(pa.Table.append_column) def append_column(self, *args, **kwargs): raise NotImplementedError() @inject_arrow_table_documentation(pa.Table.remove_column) def remove_column(self, *args, **kwargs): raise NotImplementedError() @inject_arrow_table_documentation(pa.Table.set_column) def set_column(self, *args, **kwargs): raise NotImplementedError() @inject_arrow_table_documentation(pa.Table.rename_columns) def rename_columns(self, *args, **kwargs): raise NotImplementedError() @inject_arrow_table_documentation(pa.Table.drop) def drop(self, *args, **kwargs): raise NotImplementedError() class TableBlock(Table): """ TableBlock is the allowed class inside a ConcanetationTable. Only MemoryMappedTable and InMemoryTable are TableBlock. This is because we don't want a ConcanetationTable made out of other ConcanetationTables. """ pass class InMemoryTable(TableBlock): """ The table is said in-memory when it is loaded into the user's RAM. Pickling it does copy all the data using memory. Its implementation is simple and uses the underlying pyarrow Table methods directly. This is different from the MemoryMapped table, for which pickling doesn't copy all the data in memory. For a MemoryMapped, unpickling instead reloads the table from the disk. InMemoryTable must be used when data fit in memory, while MemoryMapped are reserved for data bigger than memory or when you want the memory footprint of your application to stay low. """ @classmethod def from_file(cls, filename: str): table = _in_memory_arrow_table_from_file(filename) return cls(table) @classmethod def from_buffer(cls, buffer: pa.Buffer): table = _in_memory_arrow_table_from_buffer(buffer) return cls(table) @inject_arrow_table_documentation(pa.Table.from_pandas) @classmethod def from_pandas(cls, *args, **kwargs): return cls(pa.Table.from_pandas(*args, **kwargs)) @inject_arrow_table_documentation(pa.Table.from_arrays) @classmethod def from_arrays(cls, *args, **kwargs): return cls(pa.Table.from_arrays(*args, **kwargs)) @inject_arrow_table_documentation(pa.Table.from_pydict) @classmethod def from_pydict(cls, *args, **kwargs): return cls(pa.Table.from_pydict(*args, **kwargs)) @inject_arrow_table_documentation(pa.Table.from_batches) @classmethod def from_batches(cls, *args, **kwargs): return cls(pa.Table.from_batches(*args, **kwargs)) @inject_arrow_table_documentation(pa.Table.slice) def slice(self, offset=0, length=None): # Use fast slicing here return InMemoryTable(self.fast_slice(offset=offset, length=length)) @inject_arrow_table_documentation(pa.Table.filter) def filter(self, *args, **kwargs): return InMemoryTable(self.table.filter(*args, **kwargs)) @inject_arrow_table_documentation(pa.Table.flatten) def flatten(self, *args, **kwargs): return InMemoryTable(self.table.flatten(*args, **kwargs)) @inject_arrow_table_documentation(pa.Table.combine_chunks) def combine_chunks(self, *args, **kwargs): return InMemoryTable(self.table.combine_chunks(*args, **kwargs)) @inject_arrow_table_documentation(pa.Table.cast) def cast(self, *args, **kwargs): return InMemoryTable(self.table.cast(*args, **kwargs)) @inject_arrow_table_documentation(pa.Table.add_column) def add_column(self, *args, **kwargs): return InMemoryTable(self.table.add_column(*args, **kwargs)) @inject_arrow_table_documentation(pa.Table.append_column) def append_column(self, *args, **kwargs): return InMemoryTable(self.table.append_column(*args, **kwargs)) @inject_arrow_table_documentation(pa.Table.remove_column) def remove_column(self, *args, **kwargs): return InMemoryTable(self.table.remove_column(*args, **kwargs)) @inject_arrow_table_documentation(pa.Table.set_column) def set_column(self, *args, **kwargs): return InMemoryTable(self.table.set_column(*args, **kwargs)) @inject_arrow_table_documentation(pa.Table.rename_columns) def rename_columns(self, *args, **kwargs): return InMemoryTable(self.table.rename_columns(*args, **kwargs)) @inject_arrow_table_documentation(pa.Table.drop) def drop(self, *args, **kwargs): return InMemoryTable(self.table.drop(*args, **kwargs)) # The MemoryMappedTable needs replays to properly reload tables from the disk Replay = Tuple[str, tuple, dict] class MemoryMappedTable(TableBlock): """ The table is said memory mapped when it doesn't use the user's RAM but loads the data from the disk instead. Pickling it doesn't copy the data into memory. Instead, only the path to the memory mapped arrow file is pickled, as well as the list of transforms to "replay" when reloading the table from the disk. Its implementation requires to store an history of all the transforms that were applied to the underlying pyarrow Table, so that they can be "replayed" when reloading the Table from the disk. This is different from the InMemoryTable table, for which pickling does copy all the data in memory. InMemoryTable must be used when data fit in memory, while MemoryMapped are reserved for data bigger than memory or when you want the memory footprint of your application to stay low. """ def __init__(self, table: pa.Table, path: str, replays: Optional[List[Replay]] = None): super().__init__(table) self.path = path self.replays: List[Replay] = replays if replays is not None else [] @classmethod def from_file(cls, filename: str, replays=None): table = _memory_mapped_arrow_table_from_file(filename) table = cls._apply_replays(table, replays) return cls(table, filename, replays) def __getstate__(self): return {"path": self.path, "replays": self.replays} def __setstate__(self, state): path = state["path"] replays = state["replays"] table = _memory_mapped_arrow_table_from_file(path) table = self._apply_replays(table, replays) MemoryMappedTable.__init__(self, table, path=path, replays=replays) @staticmethod def _apply_replays(table: pa.Table, replays: Optional[List[Replay]] = None) -> pa.Table: if replays is not None: for name, args, kwargs in replays: table = getattr(table, name)(*args, **kwargs) return table def _append_replay(self, replay: Replay) -> List[Replay]: replays = copy.deepcopy(self.replays) replays.append(replay) return replays @inject_arrow_table_documentation(pa.Table.slice) def slice(self, offset=0, length=None): replay = ("slice", (offset, length), {}) replays = self._append_replay(replay) # Use fast slicing here return MemoryMappedTable(self.fast_slice(offset=offset, length=length), self.path, replays) @inject_arrow_table_documentation(pa.Table.filter) def filter(self, *args, **kwargs): replay = ("filter", copy.deepcopy(args), copy.deepcopy(kwargs)) replays = self._append_replay(replay) return MemoryMappedTable(self.table.filter(*args, **kwargs), self.path, replays) @inject_arrow_table_documentation(pa.Table.flatten) def flatten(self, *args, **kwargs): replay = ("flatten", copy.deepcopy(args), copy.deepcopy(kwargs)) replays = self._append_replay(replay) return MemoryMappedTable(self.table.flatten(*args, **kwargs), self.path, replays) @inject_arrow_table_documentation(pa.Table.combine_chunks) def combine_chunks(self, *args, **kwargs): replay = ("combine_chunks", copy.deepcopy(args), copy.deepcopy(kwargs)) replays = self._append_replay(replay) return MemoryMappedTable(self.table.combine_chunks(*args, **kwargs), self.path, replays) @inject_arrow_table_documentation(pa.Table.cast) def cast(self, *args, **kwargs): replay = ("cast", copy.deepcopy(args), copy.deepcopy(kwargs)) replays = self._append_replay(replay) return MemoryMappedTable(self.table.cast(*args, **kwargs), self.path, replays) @inject_arrow_table_documentation(pa.Table.add_column) def add_column(self, *args, **kwargs): replay = ("add_column", copy.deepcopy(args), copy.deepcopy(kwargs)) replays = self._append_replay(replay) return MemoryMappedTable(self.table.add_column(*args, **kwargs), self.path, replays) @inject_arrow_table_documentation(pa.Table.append_column) def append_column(self, *args, **kwargs): replay = ("append_column", copy.deepcopy(args), copy.deepcopy(kwargs)) replays = self._append_replay(replay) return MemoryMappedTable(self.table.append_column(*args, **kwargs), self.path, replays) @inject_arrow_table_documentation(pa.Table.remove_column) def remove_column(self, *args, **kwargs): replay = ("remove_column", copy.deepcopy(args), copy.deepcopy(kwargs)) replays = self._append_replay(replay) return MemoryMappedTable(self.table.remove_column(*args, **kwargs), self.path, replays) @inject_arrow_table_documentation(pa.Table.set_column) def set_column(self, *args, **kwargs): replay = ("set_column", copy.deepcopy(args), copy.deepcopy(kwargs)) replays = self._append_replay(replay) return MemoryMappedTable(self.table.set_column(*args, **kwargs), self.path, replays) @inject_arrow_table_documentation(pa.Table.rename_columns) def rename_columns(self, *args, **kwargs): replay = ("rename_columns", copy.deepcopy(args), copy.deepcopy(kwargs)) replays = self._append_replay(replay) return MemoryMappedTable(self.table.rename_columns(*args, **kwargs), self.path, replays) @inject_arrow_table_documentation(pa.Table.drop) def drop(self, *args, **kwargs): replay = ("drop", copy.deepcopy(args), copy.deepcopy(kwargs)) replays = self._append_replay(replay) return MemoryMappedTable(self.table.drop(*args, **kwargs), self.path, replays) # A ConcatenationTable is the concatenation of several tables. # The ``blocks`` attributes stores a list of list of blocks. # The first axis concatenates the tables along the axis 0 (it appends rows), # while the second axis concatenates tables along the axis 1 (it appends columns). TableBlockContainer = TypeVar("TableBlockContainer", TableBlock, List[TableBlock], List[List[TableBlock]]) class ConcatenationTable(Table): """ The table comes from the concatenation of several tables called blocks. It enables concatenation on both axis 0 (append rows) and axis 1 (append columns). The underlying tables are called "blocks" and can be either InMemoryTable or MemoryMappedTable objects. This allows to combine tables that come from memory or that are memory mapped. When a ConcatenationTable is pickled, then each block is pickled: - the InMemoryTable objects are pickled by copying all the data in memory; - the MemoryMappedTable objects are pickled without copying the data into memory. Instead, only the path to the memory mapped arrow file is pickled, as well as the list of transforms to "replays" when reloading the table from the disk. Its implementation requires to store each block separately. The ``blocks`` attributes stores a list of list of blocks. The first axis concatenates the tables along the axis 0 (it appends rows), while the second axis concatenates tables along the axis 1 (it appends columns). You can access the fully combined table by accessing the ConcatenationTable.table attribute, and the blocks by accessing the ConcatenationTable.blocks attribute. """ def __init__(self, table: pa.Table, blocks: List[List[TableBlock]]): super().__init__(table) self.blocks = blocks # Check that all the blocks have the right type. # Only InMemoryTable and MemoryMappedTable are allowed. for subtables in blocks: for subtable in subtables: if not isinstance(subtable, TableBlock): raise TypeError( "The blocks of a ConcatenationTable must be InMemoryTable or MemoryMappedTable objects" f", but got {subtable}." ) def __getstate__(self): return {"blocks": self.blocks} def __setstate__(self, state): blocks = state["blocks"] table = self._concat_blocks_horizontally_and_vertically(blocks) ConcatenationTable.__init__(self, table, blocks=blocks) @staticmethod def _concat_blocks(blocks: List[Union[TableBlock, pa.Table]], axis: int = 0) -> pa.Table: pa_tables = [table.table if hasattr(table, "table") else table for table in blocks] if axis == 0: # Align schemas: re-order the columns to make the schemas match before concatenating over rows schema = pa_tables[0].schema pa_tables = [ table if table.schema == schema else pa.Table.from_arrays([table[name] for name in schema.names], names=schema.names) for table in pa_tables ] return pa.concat_tables(pa_tables) elif axis == 1: for i, table in enumerate(pa_tables): if i == 0: pa_table = table else: for name, col in zip(table.column_names, table.columns): pa_table = pa_table.append_column(name, col) return pa_table else: raise ValueError("'axis' must be either 0 or 1") @classmethod def _concat_blocks_horizontally_and_vertically(cls, blocks: List[List[TableBlock]]) -> pa.Table: pa_tables_to_concat_vertically = [] for i, tables in enumerate(blocks): if not tables: continue pa_table_horizontally_concatenated = cls._concat_blocks(tables, axis=1) pa_tables_to_concat_vertically.append(pa_table_horizontally_concatenated) return cls._concat_blocks(pa_tables_to_concat_vertically, axis=0) @classmethod def _merge_blocks(cls, blocks: TableBlockContainer, axis: Optional[int] = None) -> TableBlockContainer: if axis is not None: merged_blocks = [] for is_in_memory, block_group in groupby(blocks, key=lambda x: isinstance(x, InMemoryTable)): if is_in_memory: block_group = [InMemoryTable(cls._concat_blocks(list(block_group), axis=axis))] merged_blocks += list(block_group) else: # both merged_blocks = [cls._merge_blocks(row_block, axis=1) for row_block in blocks] if all(len(row_block) == 1 for row_block in merged_blocks): merged_blocks = cls._merge_blocks( [block for row_block in merged_blocks for block in row_block], axis=0 ) return merged_blocks @classmethod def _consolidate_blocks(cls, blocks: TableBlockContainer) -> TableBlockContainer: if isinstance(blocks, TableBlock): return blocks elif isinstance(blocks[0], TableBlock): return cls._merge_blocks(blocks, axis=0) else: return cls._merge_blocks(blocks) @classmethod def from_blocks(cls, blocks: TableBlockContainer) -> "ConcatenationTable": blocks = cls._consolidate_blocks(blocks) if isinstance(blocks, TableBlock): table = blocks return cls(table.table, [[table]]) elif isinstance(blocks[0], TableBlock): table = cls._concat_blocks(blocks, axis=0) blocks = [[t] for t in blocks] return cls(table, blocks) else: table = cls._concat_blocks_horizontally_and_vertically(blocks) return cls(table, blocks) @classmethod def from_tables(cls, tables: List[Union[pa.Table, Table]], axis: int = 0) -> "ConcatenationTable": """Create ConcatenationTable from list of tables. Args: tables (list of :class:`Table` or list of :obj:`pyarrow.Table`): List of tables. axis: (``{0, 1}``, default ``0``, meaning over rows): Axis to concatenate over, where ``0`` means over rows (vertically) and ``1`` means over columns (horizontally). .. versionadded:: 1.6.0 """ def to_blocks(table): if isinstance(table, pa.Table): return [[InMemoryTable(table)]] elif isinstance(table, ConcatenationTable): return copy.deepcopy(table.blocks) else: return [[table]] def _split_like(blocks_to_split, blocks_like): splits = [] offset = 0 for block_row in blocks_like: length = block_row[0].num_rows splits.append((offset, length)) offset += length return [ [block.slice(offset=split[0], length=split[1]) for block in blocks_to_split[0]] for split in splits ] def _extend_blocks(result, blocks: List[List[TableBlock]], axis: int = 0): if axis == 0: result.extend(blocks) elif axis == 1: if len(result) == 1 and len(blocks) > 1: result = _split_like(result, blocks) # Split result elif len(blocks) == 1 and len(result) > 1: blocks = _split_like(blocks, result) # Split blocks # TODO: This assumes each block_row has the same num_rows for i, row_blocks in enumerate(blocks): result[i].extend(row_blocks) return result blocks = to_blocks(tables[0]) for table in tables[1:]: table_blocks = to_blocks(table) blocks = _extend_blocks(blocks, table_blocks, axis=axis) return cls.from_blocks(blocks) @property def _slices(self): offset = 0 for tables in self.blocks: length = len(tables[0]) yield (offset, length) offset += length @inject_arrow_table_documentation(pa.Table.slice) def slice(self, offset=0, length=None): table = self.table.slice(offset, length=length) length = length if length is not None else self.num_rows - offset blocks = [] for tables in self.blocks: n_rows = len(tables[0]) if length == 0: break elif n_rows <= offset: offset = offset - n_rows elif n_rows <= offset + length: blocks.append([t.slice(offset) for t in tables]) length, offset = length + offset - n_rows, 0 else: blocks.append([t.slice(offset, length) for t in tables]) length, offset = 0, 0 return ConcatenationTable(table, blocks) @inject_arrow_table_documentation(pa.Table.filter) def filter(self, mask, *args, **kwargs): table = self.table.filter(mask, *args, **kwargs) blocks = [] for (offset, length), tables in zip(self._slices, self.blocks): submask = mask.slice(offset, length) blocks.append([t.filter(submask, *args, **kwargs) for t in tables]) return ConcatenationTable(table, blocks) @inject_arrow_table_documentation(pa.Table.flatten) def flatten(self, *args, **kwargs): table = self.table.flatten(*args, **kwargs) blocks = [] for tables in self.blocks: blocks.append([t.flatten(*args, **kwargs) for t in tables]) return ConcatenationTable(table, blocks) @inject_arrow_table_documentation(pa.Table.combine_chunks) def combine_chunks(self, *args, **kwargs): table = self.table.combine_chunks(*args, **kwargs) blocks = [] for tables in self.blocks: blocks.append([t.combine_chunks(*args, **kwargs) for t in tables]) return ConcatenationTable(table, blocks) @inject_arrow_table_documentation(pa.Table.cast) def cast(self, target_schema, *args, **kwargs): table = self.table.cast(target_schema, *args, **kwargs) blocks = [] for subtables in self.blocks: new_tables = [] fields = list(target_schema) for subtable in subtables: subfields = [] for name in subtable.column_names: subfields.append(fields.pop(next(i for i, field in enumerate(fields) if field.name == name))) subschema = pa.schema(subfields) new_tables.append(subtable.cast(subschema, *args, **kwargs)) blocks.append(new_tables) return ConcatenationTable(table, blocks) @inject_arrow_table_documentation(pa.Table.add_column) def add_column(self, *args, **kwargs): raise NotImplementedError() @inject_arrow_table_documentation(pa.Table.append_column) def append_column(self, *args, **kwargs): raise NotImplementedError() @inject_arrow_table_documentation(pa.Table.remove_column) def remove_column(self, i, *args, **kwargs): table = self.table.remove_column(i, *args, **kwargs) name = self.table.column_names[i] blocks = [] for tables in self.blocks: blocks.append( [ t.remove_column(t.column_names.index(name), *args, **kwargs) if name in t.column_names else t for t in tables ] ) return ConcatenationTable(table, blocks) @inject_arrow_table_documentation(pa.Table.set_column) def set_column(self, *args, **kwargs): raise NotImplementedError() @inject_arrow_table_documentation(pa.Table.rename_columns) def rename_columns(self, names, *args, **kwargs): table = self.table.rename_columns(names, *args, **kwargs) names = dict(zip(self.table.column_names, names)) blocks = [] for tables in self.blocks: blocks.append( [t.rename_columns([names[name] for name in t.column_names], *args, **kwargs) for t in tables] ) return ConcatenationTable(table, blocks) @inject_arrow_table_documentation(pa.Table.drop) def drop(self, columns, *args, **kwargs): table = self.table.drop(columns) blocks = [] for tables in self.blocks: blocks.append([t.drop([c for c in columns if c in t.column_names], *args, **kwargs) for t in tables]) return ConcatenationTable(table, blocks) def concat_tables(tables: List[Table], axis: int = 0) -> Table: """ Concatenate tables. Args: tables (list of :class:`Table`): List of tables to be concatenated. axis (``{0, 1}``, default ``0``, meaning over rows): Axis to concatenate over, where ``0`` means over rows (vertically) and ``1`` means over columns (horizontally). .. versionadded:: 1.6.0 Returns: :obj:`datasets.table.Table` that is the concatenated table: If the number of input tables is > 1, then the returned table is a :obj:`datasets.table.ConcatenationTable`. Otherwise if there's only one table, it is returned as is. """ tables = list(tables) if len(tables) == 1: return tables[0] return ConcatenationTable.from_tables(tables, axis=axis) def list_table_cache_files(table: Table) -> List[str]: """ Get the cache files that are loaded by the table. Cache file are used when parts of the table come from the disk via memory mapping. Returns: :obj:`List[str]`: a list of paths to the cache files loaded by the table """ if isinstance(table, ConcatenationTable): cache_files = [] for subtables in table.blocks: for subtable in subtables: cache_files += list_table_cache_files(subtable) return cache_files elif isinstance(table, MemoryMappedTable): return [table.path] else: return []
import copy import os import tempfile from functools import wraps from itertools import groupby from typing import List, Optional, Tuple, TypeVar, Union import numpy as np import pyarrow as pa from . import config from .utils.logging import get_logger logger = get_logger(__name__) def inject_arrow_table_documentation(arrow_table_method): def wrapper(method): out = wraps(arrow_table_method)(method) out.__doc__ = out.__doc__.replace("pyarrow.Table", "Table") return out return wrapper def _in_memory_arrow_table_from_file(filename: str) -> pa.Table: in_memory_stream = pa.input_stream(filename) opened_stream = pa.ipc.open_stream(in_memory_stream) pa_table = opened_stream.read_all() return pa_table def _in_memory_arrow_table_from_buffer(buffer: pa.Buffer) -> pa.Table: stream = pa.BufferReader(buffer) opened_stream = pa.ipc.open_stream(stream) table = opened_stream.read_all() return table def _memory_mapped_arrow_table_from_file(filename: str) -> pa.Table: memory_mapped_stream = pa.memory_map(filename) opened_stream = pa.ipc.open_stream(memory_mapped_stream) pa_table = opened_stream.read_all() return pa_table def _write_table_to_file(table: pa.Table, filename: str) -> int: with open(filename, "wb") as sink: writer = pa.RecordBatchStreamWriter(sink=sink, schema=table.schema) batches: List[pa.RecordBatch] = table.to_batches() for batch in batches: writer.write_batch(batch) writer.close() return sum(batch.nbytes for batch in batches) def _deepcopy(x, memo: dict): """deepcopy a regular class instance""" cls = x.__class__ result = cls.__new__(cls) memo[id(x)] = result for k, v in x.__dict__.items(): setattr(result, k, copy.deepcopy(v, memo)) return result def _interpolation_search(arr: List[int], x: int) -> int: """ Return the position i of a sorted array so that arr[i] <= x < arr[i+1] Args: arr (:obj:`List[int]`): non-empty sorted list of integers x (:obj:`int`): query Returns: `int`: the position i so that arr[i] <= x < arr[i+1] Raises: `IndexError`: if the array is empty or if the query is outside the array values """ i, j = 0, len(arr) - 1 while i < j and arr[i] <= x < arr[j]: k = i + ((j - i) * (x - arr[i]) // (arr[j] - arr[i])) if arr[k] <= x < arr[k + 1]: return k elif arr[k] < x: i, j = k + 1, j else: i, j = i, k raise IndexError(f"Invalid query '{x}' for size {arr[-1] if len(arr) else 'none'}.") class IndexedTableMixin: def __init__(self, table: pa.Table): self._schema = table.schema self._batches = table.to_batches() self._offsets: np.ndarray = np.cumsum([0] + [len(b) for b in self._batches], dtype=np.int64) def fast_gather(self, indices: Union[List[int], np.ndarray]) -> pa.Table: """ Create a pa.Table by gathering the records at the records at the specified indices. Should be faster than pa.concat_tables(table.fast_slice(int(i) % table.num_rows, 1) for i in indices) since NumPy can compute the binary searches in parallel, highly optimized C """ assert len(indices), "Indices must be non-empty" batch_indices = np.searchsorted(self._offsets, indices, side="right") - 1 return pa.Table.from_batches( [ self._batches[batch_idx].slice(i - self._offsets[batch_idx], 1) for batch_idx, i in zip(batch_indices, indices) ], schema=self._schema, ) def fast_slice(self, offset=0, length=None) -> pa.Table: """ Slice the Table using interpolation search. The behavior is the same as :obj:`pyarrow.Table.slice` but it's significantly faster. Interpolation search is used to find the start and end indexes of the batches we want to keep. The batches to keep are then concatenated to form the sliced Table. """ if offset < 0: raise IndexError("Offset must be non-negative") elif offset >= self._offsets[-1] or (length is not None and length <= 0): return pa.Table.from_batches([], schema=self._schema) i = _interpolation_search(self._offsets, offset) if length is None or length + offset >= self._offsets[-1]: batches = self._batches[i:] batches[0] = batches[0].slice(offset - self._offsets[i]) else: j = _interpolation_search(self._offsets, offset + length - 1) batches = self._batches[i : j + 1] batches[-1] = batches[-1].slice(0, offset + length - self._offsets[j]) batches[0] = batches[0].slice(offset - self._offsets[i]) return pa.Table.from_batches(batches, schema=self._schema) class Table(IndexedTableMixin): """ Wraps a pyarrow Table by using composition. This is the base class for InMemoryTable, MemoryMappedTable and ConcatenationTable. It implements all the basic attributes/methods of the pyarrow Table class except the Table transforms: slice, filter, flatten, combine_chunks, cast, add_column, append_column, remove_column, set_column, rename_columns and drop. The implementation of these methods differs for the subclasses. """ def __init__(self, table: pa.Table): super().__init__(table) self.table = table def __deepcopy__(self, memo: dict): # arrow tables are immutable, so there's no need to copy self.table # moreover calling deepcopy on a pyarrow table seems to make pa.total_allocated_bytes() decrease for some reason # by adding it to the memo, self.table won't be copied memo[id(self.table)] = self.table # same for the recordbatches used by the index memo[id(self._batches)] = list(self._batches) return _deepcopy(self, memo) def __getstate__(self): # We can't pickle objects that are bigger than 4GiB, or it causes OverflowError # So we write the table on disk instead if self.table.nbytes >= config.MAX_TABLE_NBYTES_FOR_PICKLING: table = self.table with tempfile.NamedTemporaryFile("wb", delete=False, suffix=".arrow") as tmp_file: filename = tmp_file.name logger.debug( f"Attempting to pickle a table bigger than 4GiB. Writing it on the disk instead at {filename}" ) _write_table_to_file(table=table, filename=filename) return {"path": filename} else: return {"table": self.table} def __setstate__(self, state): if "path" in state: filename = state["path"] logger.debug(f"Unpickling a big table from the disk at {filename}") table = _in_memory_arrow_table_from_file(filename) logger.debug(f"Removing temporary table file at {filename}") os.remove(filename) else: table = state["table"] Table.__init__(self, table) @inject_arrow_table_documentation(pa.Table.validate) def validate(self, *args, **kwargs): return self.table.validate(*args, **kwargs) @inject_arrow_table_documentation(pa.Table.equals) def equals(self, *args, **kwargs): args = tuple(arg.table if isinstance(arg, Table) else arg for arg in args) kwargs = {k: v.table if isinstance(v, Table) else v for k, v in kwargs} return self.table.equals(*args, **kwargs) @inject_arrow_table_documentation(pa.Table.to_batches) def to_batches(self, *args, **kwargs): return self.table.to_batches(*args, **kwargs) @inject_arrow_table_documentation(pa.Table.to_pydict) def to_pydict(self, *args, **kwargs): return self.table.to_pydict(*args, **kwargs) @inject_arrow_table_documentation(pa.Table.to_pandas) def to_pandas(self, *args, **kwargs): return self.table.to_pandas(*args, **kwargs) def to_string(self, *args, **kwargs): return self.table.to_string(*args, **kwargs) @inject_arrow_table_documentation(pa.Table.field) def field(self, *args, **kwargs): return self.table.field(*args, **kwargs) @inject_arrow_table_documentation(pa.Table.column) def column(self, *args, **kwargs): return self.table.column(*args, **kwargs) @inject_arrow_table_documentation(pa.Table.itercolumns) def itercolumns(self, *args, **kwargs): return self.table.itercolumns(*args, **kwargs) @property def schema(self): return self.table.schema @property def columns(self): return self.table.columns @property def num_columns(self): return self.table.num_columns @property def num_rows(self): return self.table.num_rows @property def shape(self): return self.table.shape @property def nbytes(self): return self.table.nbytes @property def column_names(self): return self.table.column_names def __eq__(self, other): return self.equals(other) def __getitem__(self, i): return self.table[i] def __len__(self): return len(self.table) def __repr__(self): return self.table.__repr__().replace("pyarrow.Table", self.__class__.__name__) def __str__(self): return self.table.__str__().replace("pyarrow.Table", self.__class__.__name__) @inject_arrow_table_documentation(pa.Table.slice) def slice(self, *args, **kwargs): raise NotImplementedError() @inject_arrow_table_documentation(pa.Table.filter) def filter(self, *args, **kwargs): raise NotImplementedError() @inject_arrow_table_documentation(pa.Table.flatten) def flatten(self, *args, **kwargs): raise NotImplementedError() @inject_arrow_table_documentation(pa.Table.combine_chunks) def combine_chunks(self, *args, **kwargs): raise NotImplementedError() @inject_arrow_table_documentation(pa.Table.cast) def cast(self, *args, **kwargs): raise NotImplementedError() @inject_arrow_table_documentation(pa.Table.add_column) def add_column(self, *args, **kwargs): raise NotImplementedError() @inject_arrow_table_documentation(pa.Table.append_column) def append_column(self, *args, **kwargs): raise NotImplementedError() @inject_arrow_table_documentation(pa.Table.remove_column) def remove_column(self, *args, **kwargs): raise NotImplementedError() @inject_arrow_table_documentation(pa.Table.set_column) def set_column(self, *args, **kwargs): raise NotImplementedError() @inject_arrow_table_documentation(pa.Table.rename_columns) def rename_columns(self, *args, **kwargs): raise NotImplementedError() @inject_arrow_table_documentation(pa.Table.drop) def drop(self, *args, **kwargs): raise NotImplementedError() class TableBlock(Table): """ TableBlock is the allowed class inside a ConcanetationTable. Only MemoryMappedTable and InMemoryTable are TableBlock. This is because we don't want a ConcanetationTable made out of other ConcanetationTables. """ pass class InMemoryTable(TableBlock): """ The table is said in-memory when it is loaded into the user's RAM. Pickling it does copy all the data using memory. Its implementation is simple and uses the underlying pyarrow Table methods directly. This is different from the MemoryMapped table, for which pickling doesn't copy all the data in memory. For a MemoryMapped, unpickling instead reloads the table from the disk. InMemoryTable must be used when data fit in memory, while MemoryMapped are reserved for data bigger than memory or when you want the memory footprint of your application to stay low. """ @classmethod def from_file(cls, filename: str): table = _in_memory_arrow_table_from_file(filename) return cls(table) @classmethod def from_buffer(cls, buffer: pa.Buffer): table = _in_memory_arrow_table_from_buffer(buffer) return cls(table) @inject_arrow_table_documentation(pa.Table.from_pandas) @classmethod def from_pandas(cls, *args, **kwargs): return cls(pa.Table.from_pandas(*args, **kwargs)) @inject_arrow_table_documentation(pa.Table.from_arrays) @classmethod def from_arrays(cls, *args, **kwargs): return cls(pa.Table.from_arrays(*args, **kwargs)) @inject_arrow_table_documentation(pa.Table.from_pydict) @classmethod def from_pydict(cls, *args, **kwargs): return cls(pa.Table.from_pydict(*args, **kwargs)) @inject_arrow_table_documentation(pa.Table.from_batches) @classmethod def from_batches(cls, *args, **kwargs): return cls(pa.Table.from_batches(*args, **kwargs)) @inject_arrow_table_documentation(pa.Table.slice) def slice(self, offset=0, length=None): # Use fast slicing here return InMemoryTable(self.fast_slice(offset=offset, length=length)) @inject_arrow_table_documentation(pa.Table.filter) def filter(self, *args, **kwargs): return InMemoryTable(self.table.filter(*args, **kwargs)) @inject_arrow_table_documentation(pa.Table.flatten) def flatten(self, *args, **kwargs): return InMemoryTable(self.table.flatten(*args, **kwargs)) @inject_arrow_table_documentation(pa.Table.combine_chunks) def combine_chunks(self, *args, **kwargs): return InMemoryTable(self.table.combine_chunks(*args, **kwargs)) @inject_arrow_table_documentation(pa.Table.cast) def cast(self, *args, **kwargs): return InMemoryTable(self.table.cast(*args, **kwargs)) @inject_arrow_table_documentation(pa.Table.add_column) def add_column(self, *args, **kwargs): return InMemoryTable(self.table.add_column(*args, **kwargs)) @inject_arrow_table_documentation(pa.Table.append_column) def append_column(self, *args, **kwargs): return InMemoryTable(self.table.append_column(*args, **kwargs)) @inject_arrow_table_documentation(pa.Table.remove_column) def remove_column(self, *args, **kwargs): return InMemoryTable(self.table.remove_column(*args, **kwargs)) @inject_arrow_table_documentation(pa.Table.set_column) def set_column(self, *args, **kwargs): return InMemoryTable(self.table.set_column(*args, **kwargs)) @inject_arrow_table_documentation(pa.Table.rename_columns) def rename_columns(self, *args, **kwargs): return InMemoryTable(self.table.rename_columns(*args, **kwargs)) @inject_arrow_table_documentation(pa.Table.drop) def drop(self, *args, **kwargs): return InMemoryTable(self.table.drop(*args, **kwargs)) # The MemoryMappedTable needs replays to properly reload tables from the disk Replay = Tuple[str, tuple, dict] class MemoryMappedTable(TableBlock): """ The table is said memory mapped when it doesn't use the user's RAM but loads the data from the disk instead. Pickling it doesn't copy the data into memory. Instead, only the path to the memory mapped arrow file is pickled, as well as the list of transforms to "replay" when reloading the table from the disk. Its implementation requires to store an history of all the transforms that were applied to the underlying pyarrow Table, so that they can be "replayed" when reloading the Table from the disk. This is different from the InMemoryTable table, for which pickling does copy all the data in memory. InMemoryTable must be used when data fit in memory, while MemoryMapped are reserved for data bigger than memory or when you want the memory footprint of your application to stay low. """ def __init__(self, table: pa.Table, path: str, replays: Optional[List[Replay]] = None): super().__init__(table) self.path = path self.replays: List[Replay] = replays if replays is not None else [] @classmethod def from_file(cls, filename: str, replays=None): table = _memory_mapped_arrow_table_from_file(filename) table = cls._apply_replays(table, replays) return cls(table, filename, replays) def __getstate__(self): return {"path": self.path, "replays": self.replays} def __setstate__(self, state): path = state["path"] replays = state["replays"] table = _memory_mapped_arrow_table_from_file(path) table = self._apply_replays(table, replays) MemoryMappedTable.__init__(self, table, path=path, replays=replays) @staticmethod def _apply_replays(table: pa.Table, replays: Optional[List[Replay]] = None) -> pa.Table: if replays is not None: for name, args, kwargs in replays: table = getattr(table, name)(*args, **kwargs) return table def _append_replay(self, replay: Replay) -> List[Replay]: replays = copy.deepcopy(self.replays) replays.append(replay) return replays @inject_arrow_table_documentation(pa.Table.slice) def slice(self, offset=0, length=None): replay = ("slice", (offset, length), {}) replays = self._append_replay(replay) # Use fast slicing here return MemoryMappedTable(self.fast_slice(offset=offset, length=length), self.path, replays) @inject_arrow_table_documentation(pa.Table.filter) def filter(self, *args, **kwargs): replay = ("filter", copy.deepcopy(args), copy.deepcopy(kwargs)) replays = self._append_replay(replay) return MemoryMappedTable(self.table.filter(*args, **kwargs), self.path, replays) @inject_arrow_table_documentation(pa.Table.flatten) def flatten(self, *args, **kwargs): replay = ("flatten", copy.deepcopy(args), copy.deepcopy(kwargs)) replays = self._append_replay(replay) return MemoryMappedTable(self.table.flatten(*args, **kwargs), self.path, replays) @inject_arrow_table_documentation(pa.Table.combine_chunks) def combine_chunks(self, *args, **kwargs): replay = ("combine_chunks", copy.deepcopy(args), copy.deepcopy(kwargs)) replays = self._append_replay(replay) return MemoryMappedTable(self.table.combine_chunks(*args, **kwargs), self.path, replays) @inject_arrow_table_documentation(pa.Table.cast) def cast(self, *args, **kwargs): replay = ("cast", copy.deepcopy(args), copy.deepcopy(kwargs)) replays = self._append_replay(replay) return MemoryMappedTable(self.table.cast(*args, **kwargs), self.path, replays) @inject_arrow_table_documentation(pa.Table.add_column) def add_column(self, *args, **kwargs): replay = ("add_column", copy.deepcopy(args), copy.deepcopy(kwargs)) replays = self._append_replay(replay) return MemoryMappedTable(self.table.add_column(*args, **kwargs), self.path, replays) @inject_arrow_table_documentation(pa.Table.append_column) def append_column(self, *args, **kwargs): replay = ("append_column", copy.deepcopy(args), copy.deepcopy(kwargs)) replays = self._append_replay(replay) return MemoryMappedTable(self.table.append_column(*args, **kwargs), self.path, replays) @inject_arrow_table_documentation(pa.Table.remove_column) def remove_column(self, *args, **kwargs): replay = ("remove_column", copy.deepcopy(args), copy.deepcopy(kwargs)) replays = self._append_replay(replay) return MemoryMappedTable(self.table.remove_column(*args, **kwargs), self.path, replays) @inject_arrow_table_documentation(pa.Table.set_column) def set_column(self, *args, **kwargs): replay = ("set_column", copy.deepcopy(args), copy.deepcopy(kwargs)) replays = self._append_replay(replay) return MemoryMappedTable(self.table.set_column(*args, **kwargs), self.path, replays) @inject_arrow_table_documentation(pa.Table.rename_columns) def rename_columns(self, *args, **kwargs): replay = ("rename_columns", copy.deepcopy(args), copy.deepcopy(kwargs)) replays = self._append_replay(replay) return MemoryMappedTable(self.table.rename_columns(*args, **kwargs), self.path, replays) @inject_arrow_table_documentation(pa.Table.drop) def drop(self, *args, **kwargs): replay = ("drop", copy.deepcopy(args), copy.deepcopy(kwargs)) replays = self._append_replay(replay) return MemoryMappedTable(self.table.drop(*args, **kwargs), self.path, replays) # A ConcatenationTable is the concatenation of several tables. # The ``blocks`` attributes stores a list of list of blocks. # The first axis concatenates the tables along the axis 0 (it appends rows), # while the second axis concatenates tables along the axis 1 (it appends columns). TableBlockContainer = TypeVar("TableBlockContainer", TableBlock, List[TableBlock], List[List[TableBlock]]) class ConcatenationTable(Table): """ The table comes from the concatenation of several tables called blocks. It enables concatenation on both axis 0 (append rows) and axis 1 (append columns). The underlying tables are called "blocks" and can be either InMemoryTable or MemoryMappedTable objects. This allows to combine tables that come from memory or that are memory mapped. When a ConcatenationTable is pickled, then each block is pickled: - the InMemoryTable objects are pickled by copying all the data in memory; - the MemoryMappedTable objects are pickled without copying the data into memory. Instead, only the path to the memory mapped arrow file is pickled, as well as the list of transforms to "replays" when reloading the table from the disk. Its implementation requires to store each block separately. The ``blocks`` attributes stores a list of list of blocks. The first axis concatenates the tables along the axis 0 (it appends rows), while the second axis concatenates tables along the axis 1 (it appends columns). You can access the fully combined table by accessing the ConcatenationTable.table attribute, and the blocks by accessing the ConcatenationTable.blocks attribute. """ def __init__(self, table: pa.Table, blocks: List[List[TableBlock]]): super().__init__(table) self.blocks = blocks # Check that all the blocks have the right type. # Only InMemoryTable and MemoryMappedTable are allowed. for subtables in blocks: for subtable in subtables: if not isinstance(subtable, TableBlock): raise TypeError( "The blocks of a ConcatenationTable must be InMemoryTable or MemoryMappedTable objects" f", but got {subtable}." ) def __getstate__(self): return {"blocks": self.blocks} def __setstate__(self, state): blocks = state["blocks"] table = self._concat_blocks_horizontally_and_vertically(blocks) ConcatenationTable.__init__(self, table, blocks=blocks) @staticmethod def _concat_blocks(blocks: List[Union[TableBlock, pa.Table]], axis: int = 0) -> pa.Table: pa_tables = [table.table if hasattr(table, "table") else table for table in blocks] if axis == 0: # Align schemas: re-order the columns to make the schemas match before concatenating over rows schema = pa_tables[0].schema pa_tables = [ table if table.schema == schema else pa.Table.from_arrays([table[name] for name in schema.names], names=schema.names) for table in pa_tables ] return pa.concat_tables(pa_tables) elif axis == 1: for i, table in enumerate(pa_tables): if i == 0: pa_table = table else: for name, col in zip(table.column_names, table.columns): pa_table = pa_table.append_column(name, col) return pa_table else: raise ValueError("'axis' must be either 0 or 1") @classmethod def _concat_blocks_horizontally_and_vertically(cls, blocks: List[List[TableBlock]]) -> pa.Table: pa_tables_to_concat_vertically = [] for i, tables in enumerate(blocks): if not tables: continue pa_table_horizontally_concatenated = cls._concat_blocks(tables, axis=1) pa_tables_to_concat_vertically.append(pa_table_horizontally_concatenated) return cls._concat_blocks(pa_tables_to_concat_vertically, axis=0) @classmethod def _merge_blocks(cls, blocks: TableBlockContainer, axis: Optional[int] = None) -> TableBlockContainer: if axis is not None: merged_blocks = [] for is_in_memory, block_group in groupby(blocks, key=lambda x: isinstance(x, InMemoryTable)): if is_in_memory: block_group = [InMemoryTable(cls._concat_blocks(list(block_group), axis=axis))] merged_blocks += list(block_group) else: # both merged_blocks = [cls._merge_blocks(row_block, axis=1) for row_block in blocks] if all(len(row_block) == 1 for row_block in merged_blocks): merged_blocks = cls._merge_blocks( [block for row_block in merged_blocks for block in row_block], axis=0 ) return merged_blocks @classmethod def _consolidate_blocks(cls, blocks: TableBlockContainer) -> TableBlockContainer: if isinstance(blocks, TableBlock): return blocks elif isinstance(blocks[0], TableBlock): return cls._merge_blocks(blocks, axis=0) else: return cls._merge_blocks(blocks) @classmethod def from_blocks(cls, blocks: TableBlockContainer) -> "ConcatenationTable": blocks = cls._consolidate_blocks(blocks) if isinstance(blocks, TableBlock): table = blocks return cls(table.table, [[table]]) elif isinstance(blocks[0], TableBlock): table = cls._concat_blocks(blocks, axis=0) blocks = [[t] for t in blocks] return cls(table, blocks) else: table = cls._concat_blocks_horizontally_and_vertically(blocks) return cls(table, blocks) @classmethod def from_tables(cls, tables: List[Union[pa.Table, Table]], axis: int = 0) -> "ConcatenationTable": """Create ConcatenationTable from list of tables. Args: tables (list of :class:`Table` or list of :obj:`pyarrow.Table`): List of tables. axis: (``{0, 1}``, default ``0``, meaning over rows): Axis to concatenate over, where ``0`` means over rows (vertically) and ``1`` means over columns (horizontally). .. versionadded:: 1.6.0 """ def to_blocks(table): if isinstance(table, pa.Table): return [[InMemoryTable(table)]] elif isinstance(table, ConcatenationTable): return copy.deepcopy(table.blocks) else: return [[table]] def _split_like(blocks_to_split, blocks_like): splits = [] offset = 0 for block_row in blocks_like: length = block_row[0].num_rows splits.append((offset, length)) offset += length return [ [block.slice(offset=split[0], length=split[1]) for block in blocks_to_split[0]] for split in splits ] def _extend_blocks(result, blocks: List[List[TableBlock]], axis: int = 0): if axis == 0: result.extend(blocks) elif axis == 1: if len(result) == 1 and len(blocks) > 1: result = _split_like(result, blocks) # Split result elif len(blocks) == 1 and len(result) > 1: blocks = _split_like(blocks, result) # Split blocks # TODO: This assumes each block_row has the same num_rows for i, row_blocks in enumerate(blocks): result[i].extend(row_blocks) return result blocks = to_blocks(tables[0]) for table in tables[1:]: table_blocks = to_blocks(table) blocks = _extend_blocks(blocks, table_blocks, axis=axis) return cls.from_blocks(blocks) @property def _slices(self): offset = 0 for tables in self.blocks: length = len(tables[0]) yield (offset, length) offset += length @inject_arrow_table_documentation(pa.Table.slice) def slice(self, offset=0, length=None): table = self.table.slice(offset, length=length) length = length if length is not None else self.num_rows - offset blocks = [] for tables in self.blocks: n_rows = len(tables[0]) if length == 0: break elif n_rows <= offset: offset = offset - n_rows elif n_rows <= offset + length: blocks.append([t.slice(offset) for t in tables]) length, offset = length + offset - n_rows, 0 else: blocks.append([t.slice(offset, length) for t in tables]) length, offset = 0, 0 return ConcatenationTable(table, blocks) @inject_arrow_table_documentation(pa.Table.filter) def filter(self, mask, *args, **kwargs): table = self.table.filter(mask, *args, **kwargs) blocks = [] for (offset, length), tables in zip(self._slices, self.blocks): submask = mask.slice(offset, length) blocks.append([t.filter(submask, *args, **kwargs) for t in tables]) return ConcatenationTable(table, blocks) @inject_arrow_table_documentation(pa.Table.flatten) def flatten(self, *args, **kwargs): table = self.table.flatten(*args, **kwargs) blocks = [] for tables in self.blocks: blocks.append([t.flatten(*args, **kwargs) for t in tables]) return ConcatenationTable(table, blocks) @inject_arrow_table_documentation(pa.Table.combine_chunks) def combine_chunks(self, *args, **kwargs): table = self.table.combine_chunks(*args, **kwargs) blocks = [] for tables in self.blocks: blocks.append([t.combine_chunks(*args, **kwargs) for t in tables]) return ConcatenationTable(table, blocks) @inject_arrow_table_documentation(pa.Table.cast) def cast(self, target_schema, *args, **kwargs): table = self.table.cast(target_schema, *args, **kwargs) blocks = [] for subtables in self.blocks: new_tables = [] fields = list(target_schema) for subtable in subtables: subfields = [] for name in subtable.column_names: subfields.append(fields.pop(next(i for i, field in enumerate(fields) if field.name == name))) subschema = pa.schema(subfields) new_tables.append(subtable.cast(subschema, *args, **kwargs)) blocks.append(new_tables) return ConcatenationTable(table, blocks) @inject_arrow_table_documentation(pa.Table.add_column) def add_column(self, *args, **kwargs): raise NotImplementedError() @inject_arrow_table_documentation(pa.Table.append_column) def append_column(self, *args, **kwargs): raise NotImplementedError() @inject_arrow_table_documentation(pa.Table.remove_column) def remove_column(self, i, *args, **kwargs): table = self.table.remove_column(i, *args, **kwargs) name = self.table.column_names[i] blocks = [] for tables in self.blocks: blocks.append( [ t.remove_column(t.column_names.index(name), *args, **kwargs) if name in t.column_names else t for t in tables ] ) return ConcatenationTable(table, blocks) @inject_arrow_table_documentation(pa.Table.set_column) def set_column(self, *args, **kwargs): raise NotImplementedError() @inject_arrow_table_documentation(pa.Table.rename_columns) def rename_columns(self, names, *args, **kwargs): table = self.table.rename_columns(names, *args, **kwargs) names = dict(zip(self.table.column_names, names)) blocks = [] for tables in self.blocks: blocks.append( [t.rename_columns([names[name] for name in t.column_names], *args, **kwargs) for t in tables] ) return ConcatenationTable(table, blocks) @inject_arrow_table_documentation(pa.Table.drop) def drop(self, columns, *args, **kwargs): table = self.table.drop(columns) blocks = [] for tables in self.blocks: blocks.append([t.drop([c for c in columns if c in t.column_names], *args, **kwargs) for t in tables]) return ConcatenationTable(table, blocks) def concat_tables(tables: List[Table], axis: int = 0) -> Table: """ Concatenate tables. Args: tables (list of :class:`Table`): List of tables to be concatenated. axis (``{0, 1}``, default ``0``, meaning over rows): Axis to concatenate over, where ``0`` means over rows (vertically) and ``1`` means over columns (horizontally). .. versionadded:: 1.6.0 Returns: :obj:`datasets.table.Table` that is the concatenated table: If the number of input tables is > 1, then the returned table is a :obj:`datasets.table.ConcatenationTable`. Otherwise if there's only one table, it is returned as is. """ tables = list(tables) if len(tables) == 1: return tables[0] return ConcatenationTable.from_tables(tables, axis=axis) def list_table_cache_files(table: Table) -> List[str]: """ Get the cache files that are loaded by the table. Cache file are used when parts of the table come from the disk via memory mapping. Returns: :obj:`List[str]`: a list of paths to the cache files loaded by the table """ if isinstance(table, ConcatenationTable): cache_files = [] for subtables in table.blocks: for subtable in subtables: cache_files += list_table_cache_files(subtable) return cache_files elif isinstance(table, MemoryMappedTable): return [table.path] else: return []
#!/usr/bin/env python3 import logging import os import shutil import sys from datetime import datetime import pytest from src.dependency import check_dependencies from src.exif import Exif from src.phockup import Phockup os.chdir(os.path.dirname(__file__)) def test_check_dependencies(mocker): mocker.patch('shutil.which', return_value='exiftool') mocker.patch('sys.exit') check_dependencies() assert not sys.exit.called def test_check_dependencies_missing(mocker): mocker.patch('shutil.which', return_value=None) mocker.patch('sys.exit') with pytest.raises(Exception, match="Exiftool is not installed. \ Visit http://www.sno.phy.queensu.ca/~phil/exiftool/"): check_dependencies() def test_exception_if_missing_input_directory(mocker): mocker.patch('os.makedirs') mocker.patch('sys.exit') with pytest.raises(RuntimeError, match="Input directory 'in' does not exist"): Phockup('in', 'out') def test_exception_if_input_not_directory(mocker): mocker.patch('os.makedirs') mocker.patch('sys.exit') with pytest.raises(RuntimeError, match="Input directory 'input/exif.jpg' is not a directory"): Phockup('input/exif.jpg', 'out') def test_removing_trailing_slash_for_input_output(mocker): mocker.patch('os.makedirs') mocker.patch('sys.exit') mocker.patch.object(Phockup, 'check_directories') if sys.platform == 'win32': phockup = Phockup('in\\', 'out\\') else: phockup = Phockup('in/', 'out/') assert phockup.input_dir == 'in' assert phockup.output_dir == 'out' def test_exception_for_no_write_access_when_creating_output_dir(mocker): mocker.patch.object(Phockup, 'walk_directory') if sys.platform == 'win32': protected_dir = f"{os.getenv("WINDIR")}/phockup" else: protected_dir = '/root/phockup' with pytest.raises(OSError, match="Cannot create output.*"): Phockup('input', protected_dir) def test_walking_directory(): shutil.rmtree('output', ignore_errors=True) Phockup('input', 'output') validate_copy_operation() shutil.rmtree('output', ignore_errors=True) def test_dry_run(): shutil.rmtree('output', ignore_errors=True) Phockup('input', 'output', dry_run=True) assert not os.path.isdir('output') dir1 = 'output/2017/01/01' dir2 = 'output/2017/10/06' dir3 = 'output/unknown' dir4 = 'output/2018/01/01/' assert not os.path.isdir(dir1) assert not os.path.isdir(dir2) assert not os.path.isdir(dir3) assert not os.path.isdir(dir4) def test_progress(): shutil.rmtree('output', ignore_errors=True) Phockup('input', 'output', progress=True) dir1 = 'output/2017/01/01' dir2 = 'output/2017/10/06' dir3 = 'output/unknown' dir4 = 'output/2018/01/01/' assert os.path.isdir(dir1) assert os.path.isdir(dir2) assert os.path.isdir(dir3) assert os.path.isdir(dir4) assert len([name for name in os.listdir(dir1) if os.path.isfile(os.path.join(dir1, name))]) == 3 assert len([name for name in os.listdir(dir2) if os.path.isfile(os.path.join(dir2, name))]) == 1 assert len([name for name in os.listdir(dir3) if os.path.isfile(os.path.join(dir3, name))]) == 1 assert len([name for name in os.listdir(dir4) if os.path.isfile(os.path.join(dir4, name))]) == 1 shutil.rmtree('output', ignore_errors=True) def test_get_file_type(mocker): mocker.patch.object(Phockup, 'check_directories') assert Phockup('in', '.').get_file_type("image/jpeg") assert Phockup('in', '.').get_file_type("video/mp4") assert not Phockup('in', '.').get_file_type("foo/bar") def test_get_file_name(mocker): mocker.patch.object(Phockup, 'check_directories') mocker.patch.object(Phockup, 'walk_directory') date = { "date": datetime(2017, 1, 1, 1, 1, 1), "subseconds": "20" } assert Phockup('in', 'out').get_file_name("Bar/Foo.jpg", date) == \ "20170101-01010120.jpg" def test_get_file_name_is_original_on_exception(mocker): mocker.patch.object(Phockup, 'check_directories') mocker.patch.object(Phockup, 'walk_directory') assert Phockup('in', 'out').get_file_name("Bar/Foo.jpg", None) == "Foo.jpg" def test_process_file_with_filename_date(mocker): shutil.rmtree('output', ignore_errors=True) mocker.patch.object(Phockup, 'check_directories') mocker.patch.object(Phockup, 'walk_directory') mocker.patch.object(Exif, 'data') Exif.data.return_value = { "MIMEType": "image/jpeg" } Phockup('input', 'output').process_file("input/date_20170101_010101.jpg") assert os.path.isfile("output/2017/01/01/20170101-010101.jpg") shutil.rmtree('output', ignore_errors=True) def test_process_link_to_file_with_filename_date(mocker): shutil.rmtree('output', ignore_errors=True) mocker.patch.object(Phockup, 'check_directories') mocker.patch.object(Phockup, 'walk_directory') Phockup('input', 'output').process_file( "input/link_to_date_20170101_010101.jpg") assert os.path.isfile("output/2017/01/01/20170101-010101.jpg") shutil.rmtree('output', ignore_errors=True) def test_process_broken_link(mocker, caplog): shutil.rmtree('output', ignore_errors=True) mocker.patch.object(Phockup, 'check_directories') mocker.patch.object(Phockup, 'walk_directory') with caplog.at_level(logging.WARNING): Phockup('input', 'output').process_file("input/not_a_file.jpg") assert 'skipped, no such file or directory' in caplog.text shutil.rmtree('output', ignore_errors=True) def test_process_broken_link_move(mocker, caplog): shutil.rmtree('output', ignore_errors=True) mocker.patch.object(Phockup, 'check_directories') mocker.patch.object(Phockup, 'walk_directory') phockup = Phockup('input', 'output', move=True) phockup.process_file("input/not_a_file.jpg") with caplog.at_level(logging.WARNING): Phockup('input', 'output').process_file("input/not_a_file.jpg") assert 'skipped, no such file or directory' in caplog.text shutil.rmtree('output', ignore_errors=True) def test_process_image_exif_date(mocker): shutil.rmtree('output', ignore_errors=True) mocker.patch.object(Phockup, 'check_directories') mocker.patch.object(Phockup, 'walk_directory') Phockup('input', 'output').process_file("input/exif.jpg") assert os.path.isfile("output/2017/01/01/20170101-010101.jpg") shutil.rmtree('output', ignore_errors=True) def test_process_image_xmp(mocker): shutil.rmtree('output', ignore_errors=True) mocker.patch.object(Phockup, 'check_directories') mocker.patch.object(Phockup, 'walk_directory') Phockup('input', 'output').process_file("input/xmp.jpg") assert os.path.isfile("output/2017/01/01/20170101-010101.jpg") assert os.path.isfile("output/2017/01/01/20170101-010101.jpg.xmp") shutil.rmtree('output', ignore_errors=True) def test_process_image_xmp_noext(mocker): shutil.rmtree('output', ignore_errors=True) mocker.patch.object(Phockup, 'check_directories') mocker.patch.object(Phockup, 'walk_directory') Phockup('input', 'output').process_file("input/xmp_noext.jpg") assert os.path.isfile("output/2017/01/01/20170101-010101.jpg") assert os.path.isfile("output/2017/01/01/20170101-010101.xmp") shutil.rmtree('output', ignore_errors=True) def test_process_image_xmp_ext_and_noext(mocker): shutil.rmtree('output', ignore_errors=True) mocker.patch.object(Phockup, 'check_directories') mocker.patch.object(Phockup, 'walk_directory') Phockup('input', 'output').process_file("input/xmp_ext.jpg") assert os.path.isfile("output/2017/01/01/20170101-010101.jpg") assert os.path.isfile("output/2017/01/01/20170101-010101.xmp") assert os.path.isfile("output/2017/01/01/20170101-010101.jpg.xmp") shutil.rmtree('output', ignore_errors=True) def test_process_image_unknown(mocker): shutil.rmtree('output', ignore_errors=True) mocker.patch.object(Phockup, 'check_directories') mocker.patch.object(Phockup, 'walk_directory') mocker.patch.object(Exif, 'data') Exif.data.return_value = { "MIMEType": "image/jpeg" } Phockup('input', 'output').process_file("input/UNKNOWN.jpg") assert os.path.isfile("output/unknown/unknown.jpg") shutil.rmtree('output', ignore_errors=True) def test_process_other(mocker): shutil.rmtree('output', ignore_errors=True) mocker.patch.object(Phockup, 'check_directories') mocker.patch.object(Phockup, 'walk_directory') Phockup('input', 'output').process_file("input/other.txt") assert os.path.isfile("output/unknown/other.txt") shutil.rmtree('output', ignore_errors=True) def test_process_move(mocker): shutil.rmtree('output', ignore_errors=True) mocker.patch.object(Phockup, 'check_directories') mocker.patch.object(Phockup, 'walk_directory') mocker.patch.object(Exif, 'data') Exif.data.return_value = { "MIMEType": "image/jpeg" } phockup = Phockup('input', 'output', move=True) open("input/tmp_20170101_010101.jpg", "w").close() open("input/tmp_20170101_010101.xmp", "w").close() phockup.process_file("input/tmp_20170101_010101.jpg") phockup.process_file("input/tmp_20170101_010101.xmp") assert not os.path.isfile("input/tmp_20170101_010101.jpg") assert not os.path.isfile("input/tmp_20170101_010101.xmp") assert os.path.isfile("output/2017/01/01/20170101-010101.jpg") assert os.path.isfile("output/2017/01/01/20170101-010101.xmp") shutil.rmtree('output', ignore_errors=True) def test_process_link(mocker): shutil.rmtree('output', ignore_errors=True) mocker.patch.object(Phockup, 'check_directories') mocker.patch.object(Phockup, 'walk_directory') mocker.patch.object(Exif, 'data') Exif.data.return_value = { "MIMEType": "image/jpeg" } phockup = Phockup('input', 'output', link=True) open("input/tmp_20170101_010101.jpg", "w").close() open("input/tmp_20170101_010101.xmp", "w").close() phockup.process_file("input/tmp_20170101_010101.jpg") phockup.process_file("input/tmp_20170101_010101.xmp") assert os.path.isfile("input/tmp_20170101_010101.jpg") assert os.path.isfile("input/tmp_20170101_010101.xmp") assert os.path.isfile("output/2017/01/01/20170101-010101.jpg") assert os.path.isfile("output/2017/01/01/20170101-010101.xmp") shutil.rmtree('output', ignore_errors=True) os.remove("input/tmp_20170101_010101.jpg") os.remove("input/tmp_20170101_010101.xmp") def test_process_exists_same(mocker, caplog): shutil.rmtree('output', ignore_errors=True) mocker.patch.object(Phockup, 'check_directories') mocker.patch.object(Phockup, 'walk_directory') phockup = Phockup('input', 'output') phockup.process_file("input/exif.jpg") assert os.path.isfile("output/2017/01/01/20170101-010101.jpg") with caplog.at_level(logging.INFO): phockup.process_file("input/exif.jpg") assert 'skipped, duplicated file' in caplog.text shutil.rmtree('output', ignore_errors=True) def test_process_same_date_different_files_rename(mocker): shutil.rmtree('output', ignore_errors=True) mocker.patch.object(Phockup, 'check_directories') mocker.patch.object(Phockup, 'walk_directory') phockup = Phockup('input', 'output') phockup.process_file("input/exif.jpg") mocker.patch.object(Exif, 'data') Exif.data.return_value = { "MIMEType": "image/jpeg", "CreateDate": "2017:01:01 01:01:01" } phockup.process_file("input/date_20170101_010101.jpg") assert os.path.isfile("output/2017/01/01/20170101-010101-2.jpg") shutil.rmtree('output', ignore_errors=True) def test_process_skip_xmp(mocker): # Assume no errors == skip XMP file mocker.patch.object(Phockup, 'check_directories') mocker.patch.object(Phockup, 'walk_directory') phockup = Phockup('input', 'output') phockup.process_file("skip.xmp") def test_process_skip_ignored_file(): shutil.rmtree('output', ignore_errors=True) shutil.rmtree('input_ignored', ignore_errors=True) os.mkdir('input_ignored') open("input_ignored/.DS_Store", "w").close() Phockup('input_ignored', 'output') assert not os.path.isfile("output/unknown/.DS_Store") shutil.rmtree('output', ignore_errors=True) shutil.rmtree('input_ignored', ignore_errors=True) def test_keep_original_filenames(mocker): shutil.rmtree('output', ignore_errors=True) mocker.patch.object(Phockup, 'check_directories') mocker.patch.object(Phockup, 'walk_directory') Phockup('input', 'output', original_filenames=True).process_file( "input/exif.jpg") assert os.path.isfile("output/2017/01/01/exif.jpg") assert not os.path.isfile("output/2017/01/01/20170101-010101.jpg") shutil.rmtree('output', ignore_errors=True) def test_keep_original_filenames_and_filenames_case(mocker): shutil.rmtree('output', ignore_errors=True) mocker.patch.object(Phockup, 'check_directories') mocker.patch.object(Phockup, 'walk_directory') Phockup('input', 'output', original_filenames=True).process_file( "input/UNKNOWN.jpg") assert os.path.isfile("output/2017/10/06/UNKNOWN.jpg") assert 'unknown.jpg' not in os.listdir("output/2017/10/06") shutil.rmtree('output', ignore_errors=True) def test_maxdepth_zero(): shutil.rmtree('output', ignore_errors=True) Phockup('input', 'output', maxdepth=0) dir1 = 'output/2017/01/01' dir2 = 'output/2017/10/06' dir3 = 'output/unknown' assert os.path.isdir(dir1) assert os.path.isdir(dir2) assert os.path.isdir(dir3) assert len([name for name in os.listdir(dir1) if os.path.isfile(os.path.join(dir1, name))]) == 3 assert len([name for name in os.listdir(dir2) if os.path.isfile(os.path.join(dir2, name))]) == 1 assert len([name for name in os.listdir(dir3) if os.path.isfile(os.path.join(dir3, name))]) == 1 shutil.rmtree('output', ignore_errors=True) def test_maxdepth_one(): shutil.rmtree('output', ignore_errors=True) Phockup('input', 'output', maxdepth=1) validate_copy_operation() shutil.rmtree('output', ignore_errors=True) def test_maxconcurrency_none(): shutil.rmtree('output', ignore_errors=True) Phockup('input', 'output', max_concurrency=0) validate_copy_operation() shutil.rmtree('output', ignore_errors=True) def test_maxconcurrency_five(): shutil.rmtree('output', ignore_errors=True) Phockup('input', 'output', max_concurrency=5) validate_copy_operation() shutil.rmtree('output', ignore_errors=True) def validate_copy_operation(): dir1 = 'output/2017/01/01' dir2 = 'output/2017/10/06' dir3 = 'output/unknown' dir4 = 'output/2018/01/01/' assert os.path.isdir(dir1) assert os.path.isdir(dir2) assert os.path.isdir(dir3) assert os.path.isdir(dir4) assert len([name for name in os.listdir(dir1) if os.path.isfile(os.path.join(dir1, name))]) == 3 assert len([name for name in os.listdir(dir2) if os.path.isfile(os.path.join(dir2, name))]) == 1 assert len([name for name in os.listdir(dir3) if os.path.isfile(os.path.join(dir3, name))]) == 1 assert len([name for name in os.listdir(dir4) if os.path.isfile(os.path.join(dir4, name))]) == 1
#!/usr/bin/env python3 import logging import os import shutil import sys from datetime import datetime import pytest from src.dependency import check_dependencies from src.exif import Exif from src.phockup import Phockup os.chdir(os.path.dirname(__file__)) def test_check_dependencies(mocker): mocker.patch('shutil.which', return_value='exiftool') mocker.patch('sys.exit') check_dependencies() assert not sys.exit.called def test_check_dependencies_missing(mocker): mocker.patch('shutil.which', return_value=None) mocker.patch('sys.exit') with pytest.raises(Exception, match="Exiftool is not installed. \ Visit http://www.sno.phy.queensu.ca/~phil/exiftool/"): check_dependencies() def test_exception_if_missing_input_directory(mocker): mocker.patch('os.makedirs') mocker.patch('sys.exit') with pytest.raises(RuntimeError, match="Input directory 'in' does not exist"): Phockup('in', 'out') def test_exception_if_input_not_directory(mocker): mocker.patch('os.makedirs') mocker.patch('sys.exit') with pytest.raises(RuntimeError, match="Input directory 'input/exif.jpg' is not a directory"): Phockup('input/exif.jpg', 'out') def test_removing_trailing_slash_for_input_output(mocker): mocker.patch('os.makedirs') mocker.patch('sys.exit') mocker.patch.object(Phockup, 'check_directories') if sys.platform == 'win32': phockup = Phockup('in\\', 'out\\') else: phockup = Phockup('in/', 'out/') assert phockup.input_dir == 'in' assert phockup.output_dir == 'out' def test_exception_for_no_write_access_when_creating_output_dir(mocker): mocker.patch.object(Phockup, 'walk_directory') if sys.platform == 'win32': protected_dir = f"{os.getenv('WINDIR')}/phockup" else: protected_dir = '/root/phockup' with pytest.raises(OSError, match="Cannot create output.*"): Phockup('input', protected_dir) def test_walking_directory(): shutil.rmtree('output', ignore_errors=True) Phockup('input', 'output') validate_copy_operation() shutil.rmtree('output', ignore_errors=True) def test_dry_run(): shutil.rmtree('output', ignore_errors=True) Phockup('input', 'output', dry_run=True) assert not os.path.isdir('output') dir1 = 'output/2017/01/01' dir2 = 'output/2017/10/06' dir3 = 'output/unknown' dir4 = 'output/2018/01/01/' assert not os.path.isdir(dir1) assert not os.path.isdir(dir2) assert not os.path.isdir(dir3) assert not os.path.isdir(dir4) def test_progress(): shutil.rmtree('output', ignore_errors=True) Phockup('input', 'output', progress=True) dir1 = 'output/2017/01/01' dir2 = 'output/2017/10/06' dir3 = 'output/unknown' dir4 = 'output/2018/01/01/' assert os.path.isdir(dir1) assert os.path.isdir(dir2) assert os.path.isdir(dir3) assert os.path.isdir(dir4) assert len([name for name in os.listdir(dir1) if os.path.isfile(os.path.join(dir1, name))]) == 3 assert len([name for name in os.listdir(dir2) if os.path.isfile(os.path.join(dir2, name))]) == 1 assert len([name for name in os.listdir(dir3) if os.path.isfile(os.path.join(dir3, name))]) == 1 assert len([name for name in os.listdir(dir4) if os.path.isfile(os.path.join(dir4, name))]) == 1 shutil.rmtree('output', ignore_errors=True) def test_get_file_type(mocker): mocker.patch.object(Phockup, 'check_directories') assert Phockup('in', '.').get_file_type("image/jpeg") assert Phockup('in', '.').get_file_type("video/mp4") assert not Phockup('in', '.').get_file_type("foo/bar") def test_get_file_name(mocker): mocker.patch.object(Phockup, 'check_directories') mocker.patch.object(Phockup, 'walk_directory') date = { "date": datetime(2017, 1, 1, 1, 1, 1), "subseconds": "20" } assert Phockup('in', 'out').get_file_name("Bar/Foo.jpg", date) == \ "20170101-01010120.jpg" def test_get_file_name_is_original_on_exception(mocker): mocker.patch.object(Phockup, 'check_directories') mocker.patch.object(Phockup, 'walk_directory') assert Phockup('in', 'out').get_file_name("Bar/Foo.jpg", None) == "Foo.jpg" def test_process_file_with_filename_date(mocker): shutil.rmtree('output', ignore_errors=True) mocker.patch.object(Phockup, 'check_directories') mocker.patch.object(Phockup, 'walk_directory') mocker.patch.object(Exif, 'data') Exif.data.return_value = { "MIMEType": "image/jpeg" } Phockup('input', 'output').process_file("input/date_20170101_010101.jpg") assert os.path.isfile("output/2017/01/01/20170101-010101.jpg") shutil.rmtree('output', ignore_errors=True) def test_process_link_to_file_with_filename_date(mocker): shutil.rmtree('output', ignore_errors=True) mocker.patch.object(Phockup, 'check_directories') mocker.patch.object(Phockup, 'walk_directory') Phockup('input', 'output').process_file( "input/link_to_date_20170101_010101.jpg") assert os.path.isfile("output/2017/01/01/20170101-010101.jpg") shutil.rmtree('output', ignore_errors=True) def test_process_broken_link(mocker, caplog): shutil.rmtree('output', ignore_errors=True) mocker.patch.object(Phockup, 'check_directories') mocker.patch.object(Phockup, 'walk_directory') with caplog.at_level(logging.WARNING): Phockup('input', 'output').process_file("input/not_a_file.jpg") assert 'skipped, no such file or directory' in caplog.text shutil.rmtree('output', ignore_errors=True) def test_process_broken_link_move(mocker, caplog): shutil.rmtree('output', ignore_errors=True) mocker.patch.object(Phockup, 'check_directories') mocker.patch.object(Phockup, 'walk_directory') phockup = Phockup('input', 'output', move=True) phockup.process_file("input/not_a_file.jpg") with caplog.at_level(logging.WARNING): Phockup('input', 'output').process_file("input/not_a_file.jpg") assert 'skipped, no such file or directory' in caplog.text shutil.rmtree('output', ignore_errors=True) def test_process_image_exif_date(mocker): shutil.rmtree('output', ignore_errors=True) mocker.patch.object(Phockup, 'check_directories') mocker.patch.object(Phockup, 'walk_directory') Phockup('input', 'output').process_file("input/exif.jpg") assert os.path.isfile("output/2017/01/01/20170101-010101.jpg") shutil.rmtree('output', ignore_errors=True) def test_process_image_xmp(mocker): shutil.rmtree('output', ignore_errors=True) mocker.patch.object(Phockup, 'check_directories') mocker.patch.object(Phockup, 'walk_directory') Phockup('input', 'output').process_file("input/xmp.jpg") assert os.path.isfile("output/2017/01/01/20170101-010101.jpg") assert os.path.isfile("output/2017/01/01/20170101-010101.jpg.xmp") shutil.rmtree('output', ignore_errors=True) def test_process_image_xmp_noext(mocker): shutil.rmtree('output', ignore_errors=True) mocker.patch.object(Phockup, 'check_directories') mocker.patch.object(Phockup, 'walk_directory') Phockup('input', 'output').process_file("input/xmp_noext.jpg") assert os.path.isfile("output/2017/01/01/20170101-010101.jpg") assert os.path.isfile("output/2017/01/01/20170101-010101.xmp") shutil.rmtree('output', ignore_errors=True) def test_process_image_xmp_ext_and_noext(mocker): shutil.rmtree('output', ignore_errors=True) mocker.patch.object(Phockup, 'check_directories') mocker.patch.object(Phockup, 'walk_directory') Phockup('input', 'output').process_file("input/xmp_ext.jpg") assert os.path.isfile("output/2017/01/01/20170101-010101.jpg") assert os.path.isfile("output/2017/01/01/20170101-010101.xmp") assert os.path.isfile("output/2017/01/01/20170101-010101.jpg.xmp") shutil.rmtree('output', ignore_errors=True) def test_process_image_unknown(mocker): shutil.rmtree('output', ignore_errors=True) mocker.patch.object(Phockup, 'check_directories') mocker.patch.object(Phockup, 'walk_directory') mocker.patch.object(Exif, 'data') Exif.data.return_value = { "MIMEType": "image/jpeg" } Phockup('input', 'output').process_file("input/UNKNOWN.jpg") assert os.path.isfile("output/unknown/unknown.jpg") shutil.rmtree('output', ignore_errors=True) def test_process_other(mocker): shutil.rmtree('output', ignore_errors=True) mocker.patch.object(Phockup, 'check_directories') mocker.patch.object(Phockup, 'walk_directory') Phockup('input', 'output').process_file("input/other.txt") assert os.path.isfile("output/unknown/other.txt") shutil.rmtree('output', ignore_errors=True) def test_process_move(mocker): shutil.rmtree('output', ignore_errors=True) mocker.patch.object(Phockup, 'check_directories') mocker.patch.object(Phockup, 'walk_directory') mocker.patch.object(Exif, 'data') Exif.data.return_value = { "MIMEType": "image/jpeg" } phockup = Phockup('input', 'output', move=True) open("input/tmp_20170101_010101.jpg", "w").close() open("input/tmp_20170101_010101.xmp", "w").close() phockup.process_file("input/tmp_20170101_010101.jpg") phockup.process_file("input/tmp_20170101_010101.xmp") assert not os.path.isfile("input/tmp_20170101_010101.jpg") assert not os.path.isfile("input/tmp_20170101_010101.xmp") assert os.path.isfile("output/2017/01/01/20170101-010101.jpg") assert os.path.isfile("output/2017/01/01/20170101-010101.xmp") shutil.rmtree('output', ignore_errors=True) def test_process_link(mocker): shutil.rmtree('output', ignore_errors=True) mocker.patch.object(Phockup, 'check_directories') mocker.patch.object(Phockup, 'walk_directory') mocker.patch.object(Exif, 'data') Exif.data.return_value = { "MIMEType": "image/jpeg" } phockup = Phockup('input', 'output', link=True) open("input/tmp_20170101_010101.jpg", "w").close() open("input/tmp_20170101_010101.xmp", "w").close() phockup.process_file("input/tmp_20170101_010101.jpg") phockup.process_file("input/tmp_20170101_010101.xmp") assert os.path.isfile("input/tmp_20170101_010101.jpg") assert os.path.isfile("input/tmp_20170101_010101.xmp") assert os.path.isfile("output/2017/01/01/20170101-010101.jpg") assert os.path.isfile("output/2017/01/01/20170101-010101.xmp") shutil.rmtree('output', ignore_errors=True) os.remove("input/tmp_20170101_010101.jpg") os.remove("input/tmp_20170101_010101.xmp") def test_process_exists_same(mocker, caplog): shutil.rmtree('output', ignore_errors=True) mocker.patch.object(Phockup, 'check_directories') mocker.patch.object(Phockup, 'walk_directory') phockup = Phockup('input', 'output') phockup.process_file("input/exif.jpg") assert os.path.isfile("output/2017/01/01/20170101-010101.jpg") with caplog.at_level(logging.INFO): phockup.process_file("input/exif.jpg") assert 'skipped, duplicated file' in caplog.text shutil.rmtree('output', ignore_errors=True) def test_process_same_date_different_files_rename(mocker): shutil.rmtree('output', ignore_errors=True) mocker.patch.object(Phockup, 'check_directories') mocker.patch.object(Phockup, 'walk_directory') phockup = Phockup('input', 'output') phockup.process_file("input/exif.jpg") mocker.patch.object(Exif, 'data') Exif.data.return_value = { "MIMEType": "image/jpeg", "CreateDate": "2017:01:01 01:01:01" } phockup.process_file("input/date_20170101_010101.jpg") assert os.path.isfile("output/2017/01/01/20170101-010101-2.jpg") shutil.rmtree('output', ignore_errors=True) def test_process_skip_xmp(mocker): # Assume no errors == skip XMP file mocker.patch.object(Phockup, 'check_directories') mocker.patch.object(Phockup, 'walk_directory') phockup = Phockup('input', 'output') phockup.process_file("skip.xmp") def test_process_skip_ignored_file(): shutil.rmtree('output', ignore_errors=True) shutil.rmtree('input_ignored', ignore_errors=True) os.mkdir('input_ignored') open("input_ignored/.DS_Store", "w").close() Phockup('input_ignored', 'output') assert not os.path.isfile("output/unknown/.DS_Store") shutil.rmtree('output', ignore_errors=True) shutil.rmtree('input_ignored', ignore_errors=True) def test_keep_original_filenames(mocker): shutil.rmtree('output', ignore_errors=True) mocker.patch.object(Phockup, 'check_directories') mocker.patch.object(Phockup, 'walk_directory') Phockup('input', 'output', original_filenames=True).process_file( "input/exif.jpg") assert os.path.isfile("output/2017/01/01/exif.jpg") assert not os.path.isfile("output/2017/01/01/20170101-010101.jpg") shutil.rmtree('output', ignore_errors=True) def test_keep_original_filenames_and_filenames_case(mocker): shutil.rmtree('output', ignore_errors=True) mocker.patch.object(Phockup, 'check_directories') mocker.patch.object(Phockup, 'walk_directory') Phockup('input', 'output', original_filenames=True).process_file( "input/UNKNOWN.jpg") assert os.path.isfile("output/2017/10/06/UNKNOWN.jpg") assert 'unknown.jpg' not in os.listdir("output/2017/10/06") shutil.rmtree('output', ignore_errors=True) def test_maxdepth_zero(): shutil.rmtree('output', ignore_errors=True) Phockup('input', 'output', maxdepth=0) dir1 = 'output/2017/01/01' dir2 = 'output/2017/10/06' dir3 = 'output/unknown' assert os.path.isdir(dir1) assert os.path.isdir(dir2) assert os.path.isdir(dir3) assert len([name for name in os.listdir(dir1) if os.path.isfile(os.path.join(dir1, name))]) == 3 assert len([name for name in os.listdir(dir2) if os.path.isfile(os.path.join(dir2, name))]) == 1 assert len([name for name in os.listdir(dir3) if os.path.isfile(os.path.join(dir3, name))]) == 1 shutil.rmtree('output', ignore_errors=True) def test_maxdepth_one(): shutil.rmtree('output', ignore_errors=True) Phockup('input', 'output', maxdepth=1) validate_copy_operation() shutil.rmtree('output', ignore_errors=True) def test_maxconcurrency_none(): shutil.rmtree('output', ignore_errors=True) Phockup('input', 'output', max_concurrency=0) validate_copy_operation() shutil.rmtree('output', ignore_errors=True) def test_maxconcurrency_five(): shutil.rmtree('output', ignore_errors=True) Phockup('input', 'output', max_concurrency=5) validate_copy_operation() shutil.rmtree('output', ignore_errors=True) def validate_copy_operation(): dir1 = 'output/2017/01/01' dir2 = 'output/2017/10/06' dir3 = 'output/unknown' dir4 = 'output/2018/01/01/' assert os.path.isdir(dir1) assert os.path.isdir(dir2) assert os.path.isdir(dir3) assert os.path.isdir(dir4) assert len([name for name in os.listdir(dir1) if os.path.isfile(os.path.join(dir1, name))]) == 3 assert len([name for name in os.listdir(dir2) if os.path.isfile(os.path.join(dir2, name))]) == 1 assert len([name for name in os.listdir(dir3) if os.path.isfile(os.path.join(dir3, name))]) == 1 assert len([name for name in os.listdir(dir4) if os.path.isfile(os.path.join(dir4, name))]) == 1
__package__ = "blackhat.bin" from hashlib import sha224 from ..helpers import Result, ResultMessages from ..lib.input import ArgParser from ..lib.output import output __COMMAND__ = "sha256sum" __DESCRIPTION__ = "compute and check SHA224 message digest" __DESCRIPTION_LONG__ = "Print or check SHA224 (224-bit) checksums." __VERSION__ = "1.2" from ..lib.unistd import read def parse_args(args=[], doc=False): """ Handle parsing of arguments and flags. Generates docs using help from `ArgParser` Args: args (list): argv passed to the binary doc (bool): If the function should generate and return manpage Returns: Processed args and a copy of the `ArgParser` object if not `doc` else a `string` containing the generated manpage """ parser = ArgParser(prog=__COMMAND__, description=f"{__COMMAND__} - {__DESCRIPTION__}") parser.add_argument("files", nargs="+") parser.add_argument("--tag", action="store_true", help="create a BSD-style checksum") parser.add_argument("-z", "--zero", action="store_true", help="Remove newline from the end of the file") parser.add_argument("--version", action="store_true", help=f"output version information and exit") args = parser.parse_args(args) arg_helps_with_dups = parser._actions arg_helps = [] [arg_helps.append(x) for x in arg_helps_with_dups if x not in arg_helps] NAME = f"**NAME*/\n\t{__COMMAND__} - {__DESCRIPTION__}" SYNOPSIS = f"**SYNOPSIS*/\n\t{__COMMAND__} [OPTION]... " DESCRIPTION = f"**DESCRIPTION*/\n\t{__DESCRIPTION_LONG__}\n\n" for item in arg_helps: # Its a positional argument if len(item.option_strings) == 0: # If the argument is optional: if item.nargs == "?": SYNOPSIS += f"[{item.dest.upper()}] " elif item.nargs == "+": SYNOPSIS += f"[{item.dest.upper()}]... " else: SYNOPSIS += f"{item.dest.upper()} " else: # Boolean flag if item.nargs == 0: if len(item.option_strings) == 1: DESCRIPTION += f"\t**{" ".join(item.option_strings)}*/\t{item.help}\n\n" else: DESCRIPTION += f"\t**{" ".join(item.option_strings)}*/\n\t\t{item.help}\n\n" elif item.nargs == "+": DESCRIPTION += f"\t**{" ".join(item.option_strings)}*/=[{item.dest.upper()}]...\n\t\t{item.help}\n\n" else: DESCRIPTION += f"\t**{" ".join(item.option_strings)}*/={item.dest.upper()}\n\t\t{item.help}\n\n" if doc: return f"{NAME}\n\n{SYNOPSIS}\n\n{DESCRIPTION}\n\n" else: return args, parser def main(args: list, pipe: bool) -> Result: args, parser = parse_args(args) if parser.error_message: if not args.version: return output(f"{__COMMAND__}: {parser.error_message}", pipe, success=False) # If we specific -h/--help, args will be empty, so exit gracefully if not args: return output("", pipe) else: if args.version: return output(f"{__COMMAND__} (blackhat coreutils) {__VERSION__}", pipe) output_text = "" for filename in args.files: find_file_result = read(filename) if not find_file_result.success: if find_file_result.message == ResultMessages.NOT_FOUND: output_text += f"{__COMMAND__}: {filename}: No such file or directory\n" elif find_file_result.message == ResultMessages.NOT_ALLOWED_READ: output_text += f"{__COMMAND__}: {filename}: Permission denied\n" elif find_file_result.message == ResultMessages.IS_DIRECTORY: output_text += f"{__COMMAND__}: {filename}: Is a directory\n" to_hash = find_file_result.data[:-1] if find_file_result.data.endswith( "\n") and args.zero else find_file_result.data hash = sha224(to_hash.encode()).hexdigest() if args.tag: output_text += f"SHA224 ({filename}) = {hash}\n" else: output_text += f"{hash} {filename}\n" return output(output_text, pipe)
__package__ = "blackhat.bin" from hashlib import sha224 from ..helpers import Result, ResultMessages from ..lib.input import ArgParser from ..lib.output import output __COMMAND__ = "sha256sum" __DESCRIPTION__ = "compute and check SHA224 message digest" __DESCRIPTION_LONG__ = "Print or check SHA224 (224-bit) checksums." __VERSION__ = "1.2" from ..lib.unistd import read def parse_args(args=[], doc=False): """ Handle parsing of arguments and flags. Generates docs using help from `ArgParser` Args: args (list): argv passed to the binary doc (bool): If the function should generate and return manpage Returns: Processed args and a copy of the `ArgParser` object if not `doc` else a `string` containing the generated manpage """ parser = ArgParser(prog=__COMMAND__, description=f"{__COMMAND__} - {__DESCRIPTION__}") parser.add_argument("files", nargs="+") parser.add_argument("--tag", action="store_true", help="create a BSD-style checksum") parser.add_argument("-z", "--zero", action="store_true", help="Remove newline from the end of the file") parser.add_argument("--version", action="store_true", help=f"output version information and exit") args = parser.parse_args(args) arg_helps_with_dups = parser._actions arg_helps = [] [arg_helps.append(x) for x in arg_helps_with_dups if x not in arg_helps] NAME = f"**NAME*/\n\t{__COMMAND__} - {__DESCRIPTION__}" SYNOPSIS = f"**SYNOPSIS*/\n\t{__COMMAND__} [OPTION]... " DESCRIPTION = f"**DESCRIPTION*/\n\t{__DESCRIPTION_LONG__}\n\n" for item in arg_helps: # Its a positional argument if len(item.option_strings) == 0: # If the argument is optional: if item.nargs == "?": SYNOPSIS += f"[{item.dest.upper()}] " elif item.nargs == "+": SYNOPSIS += f"[{item.dest.upper()}]... " else: SYNOPSIS += f"{item.dest.upper()} " else: # Boolean flag if item.nargs == 0: if len(item.option_strings) == 1: DESCRIPTION += f"\t**{' '.join(item.option_strings)}*/\t{item.help}\n\n" else: DESCRIPTION += f"\t**{' '.join(item.option_strings)}*/\n\t\t{item.help}\n\n" elif item.nargs == "+": DESCRIPTION += f"\t**{' '.join(item.option_strings)}*/=[{item.dest.upper()}]...\n\t\t{item.help}\n\n" else: DESCRIPTION += f"\t**{' '.join(item.option_strings)}*/={item.dest.upper()}\n\t\t{item.help}\n\n" if doc: return f"{NAME}\n\n{SYNOPSIS}\n\n{DESCRIPTION}\n\n" else: return args, parser def main(args: list, pipe: bool) -> Result: args, parser = parse_args(args) if parser.error_message: if not args.version: return output(f"{__COMMAND__}: {parser.error_message}", pipe, success=False) # If we specific -h/--help, args will be empty, so exit gracefully if not args: return output("", pipe) else: if args.version: return output(f"{__COMMAND__} (blackhat coreutils) {__VERSION__}", pipe) output_text = "" for filename in args.files: find_file_result = read(filename) if not find_file_result.success: if find_file_result.message == ResultMessages.NOT_FOUND: output_text += f"{__COMMAND__}: {filename}: No such file or directory\n" elif find_file_result.message == ResultMessages.NOT_ALLOWED_READ: output_text += f"{__COMMAND__}: {filename}: Permission denied\n" elif find_file_result.message == ResultMessages.IS_DIRECTORY: output_text += f"{__COMMAND__}: {filename}: Is a directory\n" to_hash = find_file_result.data[:-1] if find_file_result.data.endswith( "\n") and args.zero else find_file_result.data hash = sha224(to_hash.encode()).hexdigest() if args.tag: output_text += f"SHA224 ({filename}) = {hash}\n" else: output_text += f"{hash} {filename}\n" return output(output_text, pipe)
""" Map is a generic Map class from which all other Map classes inherit from. """ import copy import html import textwrap import warnings import webbrowser from io import BytesIO from base64 import b64encode from tempfile import NamedTemporaryFile from collections import namedtuple import matplotlib.pyplot as plt import numpy as np from matplotlib import cm from matplotlib.backend_bases import FigureCanvasBase from matplotlib.figure import Figure import astropy.units as u import astropy.wcs from astropy.coordinates import Longitude, SkyCoord, UnitSphericalRepresentation from astropy.nddata import NDData from astropy.visualization import AsymmetricPercentileInterval, HistEqStretch, ImageNormalize from astropy.visualization.wcsaxes import WCSAxes # The next two are not used but are called to register functions with external modules import sunpy.coordinates import sunpy.io as io import sunpy.visualization.colormaps from sunpy import config from sunpy.coordinates import HeliographicCarrington, HeliographicStonyhurst, get_earth, sun from sunpy.coordinates.utils import get_rectangle_coordinates from sunpy.image.resample import resample as sunpy_image_resample from sunpy.image.resample import reshape_image_to_4d_superpixel from sunpy.sun import constants from sunpy.time import is_time, parse_time from sunpy.util import MetaDict, expand_list from sunpy.util.decorators import cached_property_based_on, deprecated from sunpy.util.exceptions import SunpyDeprecationWarning, SunpyMetadataWarning, SunpyUserWarning from sunpy.util.functools import seconddispatch from sunpy.visualization import axis_labels_from_ctype, peek_show, wcsaxes_compat TIME_FORMAT = config.get("general", "time_format") PixelPair = namedtuple('PixelPair', 'x y') SpatialPair = namedtuple('SpatialPair', 'axis1 axis2') _META_FIX_URL = 'https://docs.sunpy.org/en/stable/code_ref/map.html#fixing-map-metadata' __all__ = ['GenericMap'] class MapMetaValidationError(AttributeError): pass class GenericMap(NDData): """ A Generic spatially-aware 2D data array Parameters ---------- data : `numpy.ndarray`, list A 2d list or ndarray containing the map data. header : dict A dictionary of the original image header tags. plot_settings : dict, optional Plot settings. Other Parameters ---------------- **kwargs : Additional keyword arguments are passed to `~astropy.nddata.NDData` init. Examples -------- >>> import sunpy.map >>> import sunpy.data.sample # doctest: +REMOTE_DATA >>> aia = sunpy.map.Map(sunpy.data.sample.AIA_171_IMAGE) # doctest: +REMOTE_DATA >>> aia # doctest: +REMOTE_DATA <sunpy.map.sources.sdo.AIAMap object at ...> SunPy Map --------- Observatory: SDO Instrument: AIA 3 Detector: AIA Measurement: 171.0 Angstrom Wavelength: 171.0 Angstrom Observation Date: 2011-06-07 06:33:02 Exposure Time: 0.234256 s Dimension: [1024. 1024.] pix Coordinate System: helioprojective Scale: [2.402792 2.402792] arcsec / pix Reference Pixel: [511.5 511.5] pix Reference Coord: [3.22309951 1.38578135] arcsec array([[ -95.92475 , 7.076416 , -1.9656711, ..., -127.96519 , -127.96519 , -127.96519 ], [ -96.97533 , -5.1167884, 0. , ..., -98.924576 , -104.04137 , -127.919716 ], [ -93.99607 , 1.0189276, -4.0757103, ..., -5.094638 , -37.95505 , -127.87541 ], ..., [-128.01454 , -128.01454 , -128.01454 , ..., -128.01454 , -128.01454 , -128.01454 ], [-127.899666 , -127.899666 , -127.899666 , ..., -127.899666 , -127.899666 , -127.899666 ], [-128.03072 , -128.03072 , -128.03072 , ..., -128.03072 , -128.03072 , -128.03072 ]], dtype=float32) >>> aia.spatial_units # doctest: +REMOTE_DATA SpatialPair(axis1=Unit("arcsec"), axis2=Unit("arcsec")) >>> aia.peek() # doctest: +SKIP Notes ----- A number of the properties of this class are returned as two-value named tuples that can either be indexed by position ([0] or [1]) or be accessed by the names (.x and .y) or (.axis1 and .axis2). Things that refer to pixel axes use the ``.x``, ``.y`` convention, where x and y refer to the FITS axes (x for columns y for rows). Spatial axes use ``.axis1`` and ``.axis2`` which correspond to the first and second axes in the header. ``axis1`` corresponds to the coordinate axis for ``x`` and ``axis2`` corresponds to ``y``. This class makes some assumptions about the WCS information contained in the meta data. The first and most extensive assumption is that it is FITS-like WCS information as defined in the FITS WCS papers. Within this scope it also makes some other assumptions. * In the case of APIS convention headers where the CROTAi/j arguments are provided it assumes that these can be converted to the standard PCi_j notation using equations 32 in Thompson (2006). * If a CDi_j matrix is provided it is assumed that it can be converted to a PCi_j matrix and CDELT keywords as described in `Greisen & Calabretta (2002) <https://doi.org/10.1051/0004-6361:20021327>`_ * The 'standard' FITS keywords that are used by this class are the PCi_j matrix and CDELT, along with the other keywords specified in the WCS papers. All subclasses of this class must convert their header information to this formalism. The CROTA to PCi_j conversion is done in this class. .. warning:: This class currently assumes that a header with the CDi_j matrix information also includes the CDELT keywords, without these keywords this class will not process the WCS. Also the rotation_matrix does not work if the CDELT1 and CDELT2 keywords are exactly equal. Also, if a file with more than two dimensions is feed into the class, only the first two dimensions (NAXIS1, NAXIS2) will be loaded and the rest will be discarded. """ _registry = dict() def __init_subclass__(cls, **kwargs): """ An __init_subclass__ hook initializes all of the subclasses of a given class. So for each subclass, it will call this block of code on import. This replicates some metaclass magic without the need to be aware of metaclasses. Here we use this to register each subclass in a dict that has the `is_datasource_for` attribute. This is then passed into the Map Factory so we can register them. """ super().__init_subclass__(**kwargs) if hasattr(cls, 'is_datasource_for'): cls._registry[cls] = cls.is_datasource_for def __init__(self, data, header, plot_settings=None, **kwargs): # If the data has more than two dimensions, the first dimensions # (NAXIS1, NAXIS2) are used and the rest are discarded. ndim = data.ndim if ndim > 2: # We create a slice that removes all but the 'last' two # dimensions. (Note dimensions in ndarray are in reverse order) new_2d_slice = [0]*(ndim-2) new_2d_slice.extend([slice(None), slice(None)]) data = data[tuple(new_2d_slice)] # Warn the user that the data has been truncated warnings.warn("This file contains more than 2 dimensions. " "Data will be truncated to the first two dimensions.", SunpyUserWarning) super().__init__(data, meta=MetaDict(header), **kwargs) # Correct possibly missing meta keywords self._fix_date() self._fix_naxis() # Setup some attributes self._nickname = None # These are palceholders for default attributes, which are only set # once if their data isn't present in the map metadata. self._default_time = None self._default_dsun = None self._default_carrington_longitude = None self._default_heliographic_latitude = None self._default_heliographic_longitude = None # Validate header # TODO: This should be a function of the header, not of the map self._validate_meta() self._shift = SpatialPair(0 * u.arcsec, 0 * u.arcsec) if self.dtype == np.uint8: norm = None else: # Put import here to reduce sunpy.map import time from matplotlib import colors norm = colors.Normalize() # Visualization attributes self.plot_settings = {'cmap': 'gray', 'norm': norm, 'interpolation': 'nearest', 'origin': 'lower' } if plot_settings: self.plot_settings.update(plot_settings) def __getitem__(self, key): """ This should allow indexing by physical coordinate """ raise NotImplementedError( "The ability to index Map by physical" " coordinate is not yet implemented.") def _text_summary(self): return textwrap.dedent("""\ SunPy Map --------- Observatory:\t\t {obs} Instrument:\t\t {inst} Detector:\t\t {det} Measurement:\t\t {meas} Wavelength:\t\t {wave} Observation Date:\t {date} Exposure Time:\t\t {dt:f} Dimension:\t\t {dim} Coordinate System:\t {coord} Scale:\t\t\t {scale} Reference Pixel:\t {refpix} Reference Coord:\t {refcoord}\ """).format(obs=self.observatory, inst=self.instrument, det=self.detector, meas=self.measurement, wave=self.wavelength, date=self.date.strftime(TIME_FORMAT), dt=self.exposure_time, dim=u.Quantity(self.dimensions), scale=u.Quantity(self.scale), coord=self._coordinate_frame_name, refpix=u.Quantity(self.reference_pixel), refcoord=u.Quantity((self._reference_longitude, self._reference_latitude)), tmf=TIME_FORMAT) def __str__(self): return f"{self._text_summary()}\n{self.data.__repr__()}" def __repr__(self): return f"{object.__repr__(self)}\n{self}" def _repr_html_(self): """ Produce an HTML summary with plots for use in Jupyter notebooks. """ # Convert the text repr to an HTML table partial_html = self._text_summary()[20:].replace('\n', '</td></tr><tr><th>')\ .replace(':\t', '</th><td>') text_to_table = textwrap.dedent(f"""\ <table style='text-align:left'> <tr><th>{partial_html}</td></tr> </table>""").replace('\n', '') # Handle bad values (infinite and NaN) in the data array finite_data = self.data[np.isfinite(self.data)] count_nan = np.isnan(self.data).sum() count_inf = np.isinf(self.data).sum() # Assemble an informational string with the counts of bad pixels bad_pixel_text = "" if count_nan + count_inf > 0: bad_pixel_text = "Bad pixels are shown in red: " text_list = [] if count_nan > 0: text_list.append(f"{count_nan} NaN") if count_inf > 0: text_list.append(f"{count_inf} infinite") bad_pixel_text += ", ".join(text_list) # Use a grayscale colormap with histogram equalization (and red for bad values) # Make a copy of the colormap to avoid modifying the matplotlib instance when # doing set_bad() cmap = copy.copy(cm.get_cmap('gray')) cmap.set_bad(color='red') norm = ImageNormalize(stretch=HistEqStretch(finite_data)) # Plot the image in pixel space fig = Figure(figsize=(5.2, 4.8)) # Figure instances in matplotlib<3.1 do not create a canvas by default if fig.canvas is None: FigureCanvasBase(fig) ax = fig.subplots() ax.imshow(self.data, origin='lower', interpolation='nearest', cmap=cmap, norm=norm) ax.set_xlabel('X pixel') ax.set_ylabel('Y pixel') ax.set_title('In pixel space') pixel_src = _figure_to_base64(fig) bounds = ax.get_position().bounds # save these axes bounds for later use # Plot the image using WCS information, with the same axes bounds as above fig = Figure(figsize=(5.2, 4.8)) # Figure instances in matplotlib<3.1 do not create a canvas by default if fig.canvas is None: FigureCanvasBase(fig) # Create the WCSAxes manually because we need to avoid using pyplot ax = WCSAxes(fig, bounds, aspect='equal', wcs=self.wcs) fig.add_axes(ax) self.plot(axes=ax, cmap=cmap, norm=norm) ax.set_title('In coordinate space using WCS information') wcs_src = _figure_to_base64(fig) # Plot the histogram of pixel values fig = Figure(figsize=(4.8, 2.4), constrained_layout=True) # Figure instances in matplotlib<3.1 do not create a canvas by default if fig.canvas is None: FigureCanvasBase(fig) ax = fig.subplots() ax.hist(finite_data.ravel(), bins=100, histtype='stepfilled') ax.set_facecolor('white') ax.semilogy() # Explicitly set the power limits for the X axis formatter to avoid text overlaps ax.xaxis.get_major_formatter().set_powerlimits((-3, 4)) ax.set_xlabel('Pixel value') ax.set_ylabel('# of pixels') ax.set_title('Distribution of pixels with finite values') hist_src = _figure_to_base64(fig) return textwrap.dedent(f"""\ <pre>{html.escape(object.__repr__(self))}</pre> <table> <tr> <td>{text_to_table}</td> <td rowspan=3> <div align=center> Image colormap uses histogram equalization<br> Click on the image to toggle between units </div> <img src='data:image/png;base64,{wcs_src}' src2='data:image/png;base64,{pixel_src}' onClick='var temp = this.src; this.src = this.getAttribute("src2"); this.setAttribute("src2", temp)' /> <div align=center> {bad_pixel_text} </div> </td> </tr> <tr> </tr> <tr> <td><img src='data:image/png;base64,{hist_src}'/></td> </tr> </table>""") def quicklook(self): """ Display a quicklook summary of the Map instance using the default web browser. Notes ----- The image colormap uses `histogram equalization <https://en.wikipedia.org/wiki/Histogram_equalization>`__. Clicking on the image to switch between pixel space and coordinate space requires Javascript support to be enabled in the web browser. Examples -------- >>> from sunpy.map import Map >>> import sunpy.data.sample # doctest: +REMOTE_DATA >>> smap = Map(sunpy.data.sample.AIA_171_IMAGE) # doctest: +REMOTE_DATA >>> smap.quicklook() # doctest: +SKIP (which will open the following content in the default web browser) .. generate:: html :html_border: from sunpy.map import Map import sunpy.data.sample smap = Map(sunpy.data.sample.AIA_171_IMAGE) print(smap._repr_html_()) """ with NamedTemporaryFile('w', delete=False, prefix='sunpy.map.', suffix='.html') as f: url = 'file://' + f.name f.write(textwrap.dedent(f"""\ <html> <title>Quicklook summary for {html.escape(object.__repr__(self))}</title> <body>{self._repr_html_()}</body> </html>""")) webbrowser.open_new_tab(url) @classmethod def _new_instance(cls, data, meta, plot_settings=None, **kwargs): """ Instantiate a new instance of this class using given data. This is a shortcut for ``type(self)(data, meta, plot_settings)``. """ return cls(data, meta, plot_settings=plot_settings, **kwargs) def _get_lon_lat(self, frame): """ Given a coordinate frame, extract the lon and lat by casting to SphericalRepresentation first. """ r = frame.represent_as(UnitSphericalRepresentation) return r.lon.to(self.spatial_units[0]), r.lat.to(self.spatial_units[1]) @property def _meta_hash(self): return self.meta.item_hash() @property @cached_property_based_on('_meta_hash') def wcs(self): """ The `~astropy.wcs.WCS` property of the map. """ # Construct the WCS based on the FITS header, but don't "do_set" which # analyses the FITS header for correctness. with warnings.catch_warnings(): # Ignore warnings we may raise when constructing the fits header about dropped keys. warnings.simplefilter("ignore", SunpyUserWarning) try: w2 = astropy.wcs.WCS(header=self.fits_header, _do_set=False) except Exception as e: warnings.warn("Unable to treat `.meta` as a FITS header, assuming a simple WCS. " f"The exception raised was:\n{e}") w2 = astropy.wcs.WCS(naxis=2) # If the FITS header is > 2D pick the first 2 and move on. # This will require the FITS header to be valid. if w2.naxis > 2: # We have to change this or else the WCS doesn't parse properly, even # though we don't care about the third dimension. This applies to both # EIT and IRIS data, it is here to reduce the chances of silly errors. if self.meta.get('cdelt3', None) == 0: w2.wcs.cdelt[2] = 1e-10 w2 = w2.sub([1, 2]) # Add one to go from zero-based to one-based indexing w2.wcs.crpix = u.Quantity(self.reference_pixel) + 1 * u.pix # Make these a quantity array to prevent the numpy setting element of # array with sequence error. w2.wcs.cdelt = u.Quantity(self.scale) w2.wcs.crval = u.Quantity([self._reference_longitude, self._reference_latitude]) w2.wcs.ctype = self.coordinate_system w2.wcs.pc = self.rotation_matrix w2.wcs.cunit = self.spatial_units w2.wcs.dateobs = self.date.isot w2.wcs.aux.rsun_ref = self.rsun_meters.to_value(u.m) # Astropy WCS does not understand the SOHO default of "solar-x" and # "solar-y" ctypes. This overrides the default assignment and # changes it to a ctype that is understood. See Thompson, 2006, A.&A., # 449, 791. if w2.wcs.ctype[0].lower() in ("solar-x", "solar_x"): w2.wcs.ctype[0] = 'HPLN-TAN' if w2.wcs.ctype[1].lower() in ("solar-y", "solar_y"): w2.wcs.ctype[1] = 'HPLT-TAN' # Set observer coordinate information # # Clear all the aux information that was set earlier. This is to avoid # issues with maps that store multiple observer coordinate keywords. # Note that we have to create a new WCS as it's not possible to modify # wcs.wcs.aux in place. header = w2.to_header() for kw in ['crln_obs', 'dsun_obs', 'hgln_obs', 'hglt_obs']: header.pop(kw, None) w2 = astropy.wcs.WCS(header) # Get observer coord, and transform if needed obs_coord = self.observer_coordinate if not isinstance(obs_coord.frame, (HeliographicStonyhurst, HeliographicCarrington)): obs_coord = obs_coord.transform_to(HeliographicStonyhurst(obstime=self.date)) sunpy.coordinates.wcs_utils._set_wcs_aux_obs_coord(w2, obs_coord) # Validate the WCS here. w2.wcs.set() return w2 @property def coordinate_frame(self): """ An `astropy.coordinates.BaseCoordinateFrame` instance created from the coordinate information for this Map, or None if the frame cannot be determined. """ try: return astropy.wcs.utils.wcs_to_celestial_frame(self.wcs) except ValueError as e: warnings.warn(f'Could not determine coordinate frame from map metadata.\n{e}', SunpyUserWarning) return None @property def _coordinate_frame_name(self): if self.coordinate_frame is None: return 'Unknown' return self.coordinate_frame.name def _as_mpl_axes(self): """ Compatibility hook for Matplotlib and WCSAxes. This functionality requires the WCSAxes package to work. The reason we include this here is that it allows users to use WCSAxes without having to explicitly import WCSAxes With this method, one can do:: import matplotlib.pyplot as plt import sunpy.map amap = sunpy.map.Map('filename.fits') fig = plt.figure() ax = plt.subplot(projection=amap) ... and this will generate a plot with the correct WCS coordinates on the axes. See https://wcsaxes.readthedocs.io for more information. """ # This code is reused from Astropy return WCSAxes, {'wcs': self.wcs} # Some numpy extraction @property def dimensions(self): """ The dimensions of the array (x axis first, y axis second). """ return PixelPair(*u.Quantity(np.flipud(self.data.shape), 'pixel')) @property def dtype(self): """ The `numpy.dtype` of the array of the map. """ return self.data.dtype @property @deprecated(since="2.1", message="Use map.data.size instead", alternative="map.data.size") def size(self): """ The number of pixels in the array of the map. """ return u.Quantity(self.data.size, 'pixel') @property def ndim(self): """ The value of `numpy.ndarray.ndim` of the data array of the map. """ return self.data.ndim def std(self, *args, **kwargs): """ Calculate the standard deviation of the data array. """ return self.data.std(*args, **kwargs) def mean(self, *args, **kwargs): """ Calculate the mean of the data array. """ return self.data.mean(*args, **kwargs) def min(self, *args, **kwargs): """ Calculate the minimum value of the data array. """ return self.data.min(*args, **kwargs) def max(self, *args, **kwargs): """ Calculate the maximum value of the data array. """ return self.data.max(*args, **kwargs) @property def unit(self): """ Unit of the map data. This is taken from the 'BUNIT' FITS keyword. If no 'BUNIT' entry is present in the metadata then this returns `None`. If the 'BUNIT' value cannot be parsed into a unit a warning is raised, and `None` returned. """ unit_str = self.meta.get('bunit', None) if unit_str is None: return unit = u.Unit(unit_str, format='fits', parse_strict='silent') if isinstance(unit, u.UnrecognizedUnit): warnings.warn(f'Could not parse unit string "{unit_str}" as a valid FITS unit.\n' f'See {_META_FIX_URL} for how to fix metadata before loading it ' 'with sunpy.map.Map.\n' 'See https://fits.gsfc.nasa.gov/fits_standard.html for' 'the FITS unit standards.', SunpyMetadataWarning) unit = None return unit # #### Keyword attribute and other attribute definitions #### # def _base_name(self): """Abstract the shared bit between name and latex_name""" return "{nickname} {{measurement}} {date}".format( nickname=self.nickname, date=parse_time(self.date).strftime(TIME_FORMAT) ) @property def name(self): """Human-readable description of the Map.""" return self._base_name().format(measurement=self.measurement) @property def latex_name(self): """LaTeX formatted description of the Map.""" if isinstance(self.measurement, u.Quantity): return self._base_name().format(measurement=self.measurement._repr_latex_()) else: return self.name @property def nickname(self): """An abbreviated human-readable description of the map-type; part of the Helioviewer data model.""" return self._nickname if self._nickname else self.detector @nickname.setter def nickname(self, n): self._nickname = n @property def date(self): """ Image observation time. This is taken from the 'DATE-OBS' FITS keyword. """ time = self.meta.get('date-obs', None) if time is None: if self._default_time is None: warnings.warn("Missing metadata for observation time, " "setting observation time to current time. " "Set the 'DATE-OBS' FITS keyword to prevent this warning.", SunpyUserWarning) self._default_time = parse_time('now') time = self._default_time return parse_time(time) @property def detector(self): """ Detector name. This is taken from the 'DETECTOR' FITS keyword. """ return self.meta.get('detector', "") @property def timeunit(self): """ The `~astropy.units.Unit` of the exposure time of this observation. Taken from the "TIMEUNIT" FITS keyword, and defaults to seconds (as per) the FITS standard). """ return u.Unit(self.meta.get('timeunit', 's')) @property def exposure_time(self): """ Exposure time of the image in seconds. This is taken from the 'EXPTIME' FITS keyword. """ return self.meta.get('exptime', 0.0) * self.timeunit @property def instrument(self): """Instrument name.""" return self.meta.get('instrume', "").replace("_", " ") @property def measurement(self): """ Measurement wavelength. This is taken from the 'WAVELNTH' FITS keyword. If the keyword is not present, defaults to 0. """ return u.Quantity(self.meta.get('wavelnth', 0), self.waveunit) @property def waveunit(self): """ The `~astropy.units.Unit` of the wavelength of this observation. This is taken from the 'WAVEUNIT' FITS keyword. """ unit = self.meta.get("waveunit") if unit is None: return u.one return u.Unit(unit) @property def wavelength(self): """ Wavelength of the observation. This is taken from the 'WAVELNTH' FITS keyword. """ return u.Quantity(self.meta.get('wavelnth', 0), self.waveunit) @property def observatory(self): """ Observatory or Telescope name. This is taken from the 'OBSRVTRY' FITS keyword. """ return self.meta.get('obsrvtry', self.meta.get('telescop', "")).replace("_", " ") @property def processing_level(self): """ Returns the FITS processing level if present. This is taken from the 'LVL_NUM' FITS keyword. """ return self.meta.get('lvl_num', None) @property def bottom_left_coord(self): """ The physical coordinate at the center of the bottom left ([0, 0]) pixel. """ return self.pixel_to_world(0*u.pix, 0*u.pix) @property def top_right_coord(self): """ The physical coordinate at the center of the the top right ([-1, -1]) pixel. """ top_right = u.Quantity(self.dimensions) - 1 * u.pix return self.pixel_to_world(*top_right) @property def center(self): """ Return a coordinate object for the center pixel of the array. If the array has an even number of pixels in a given dimension, the coordinate returned lies on the edge between the two central pixels. """ center = (u.Quantity(self.dimensions) - 1 * u.pix) / 2. return self.pixel_to_world(*center) @property def shifted_value(self): """The total shift applied to the reference coordinate by past applications of `~sunpy.map.GenericMap.shift`.""" return self._shift @u.quantity_input def shift(self, axis1: u.deg, axis2: u.deg): """ Returns a map shifted by a specified amount to, for example, correct for a bad map location. These values are applied directly to the `~sunpy.map.GenericMap.reference_coordinate`. To check how much shift has already been applied see `~sunpy.map.GenericMap.shifted_value` Parameters ---------- axis1 : `~astropy.units.Quantity` The shift to apply to the Longitude (solar-x) coordinate. axis2 : `~astropy.units.Quantity` The shift to apply to the Latitude (solar-y) coordinate Returns ------- out : `~sunpy.map.GenericMap` or subclass A new shifted Map. """ new_meta = self.meta.copy() # Update crvals new_meta['crval1'] = ((self.meta['crval1'] * self.spatial_units[0] + axis1).to(self.spatial_units[0])).value new_meta['crval2'] = ((self.meta['crval2'] * self.spatial_units[1] + axis2).to(self.spatial_units[1])).value # Create new map with the modification new_map = self._new_instance(self.data, new_meta, self.plot_settings) new_map._shift = SpatialPair(self.shifted_value[0] + axis1, self.shifted_value[1] + axis2) return new_map @property def rsun_meters(self): """Radius of the sun in meters.""" return u.Quantity(self.meta.get('rsun_ref', constants.radius), 'meter') @property def rsun_obs(self): """ Angular radius of the Sun. Notes ----- This value is taken the ``'rsun_obs'``, ``'solar_r'``, or ``radius`` FITS keywords. If none of these keys are present the photospheric limb as seen from the observer coordinate is returned. """ rsun_arcseconds = self.meta.get('rsun_obs', self.meta.get('solar_r', self.meta.get('radius', None))) if rsun_arcseconds is None: warnings.warn("Missing metadata for solar angular radius: assuming photospheric limb " "as seen from observer coordinate.", SunpyUserWarning) dsun = self.dsun rsun = sun._angular_radius(constants.radius, dsun) else: rsun = rsun_arcseconds * u.arcsec return rsun @property def coordinate_system(self): """ Coordinate system used for x and y axes (ctype1/2). If not present, defaults to (HPLN-TAN, HPLT-TAN), and emits a warning. """ ctype1 = self.meta.get('ctype1', None) if ctype1 is None: warnings.warn("Missing CTYPE1 from metadata, assuming CTYPE1 is HPLN-TAN", SunpyUserWarning) ctype1 = 'HPLN-TAN' ctype2 = self.meta.get('ctype2', None) if ctype2 is None: warnings.warn("Missing CTYPE2 from metadata, assuming CTYPE2 is HPLT-TAN", SunpyUserWarning) ctype2 = 'HPLT-TAN' return SpatialPair(ctype1, ctype2) @property def _supported_observer_coordinates(self): """ A list of supported coordinate systems. This is a list so it can easily maintain a strict order. The list of two element tuples, the first item in the tuple is the keys that need to be in the header to use this coordinate system and the second is the kwargs to SkyCoord. """ return [(('hgln_obs', 'hglt_obs', 'dsun_obs'), {'lon': self.meta.get('hgln_obs'), 'lat': self.meta.get('hglt_obs'), 'radius': self.meta.get('dsun_obs'), 'unit': (u.deg, u.deg, u.m), 'frame': "heliographic_stonyhurst"}), (('crln_obs', 'crlt_obs', 'dsun_obs'), {'lon': self.meta.get('crln_obs'), 'lat': self.meta.get('crlt_obs'), 'radius': self.meta.get('dsun_obs'), 'unit': (u.deg, u.deg, u.m), 'frame': "heliographic_carrington"}), ] def _remove_existing_observer_location(self): """ Remove all keys that this map might use for observer location. """ all_keys = expand_list([e[0] for e in self._supported_observer_coordinates]) for key in all_keys: self.meta.pop(key) @property def observer_coordinate(self): """ The Heliographic Stonyhurst Coordinate of the observer. """ missing_meta = {} for keys, kwargs in self._supported_observer_coordinates: meta_list = [k in self.meta for k in keys] if all(meta_list): sc = SkyCoord(obstime=self.date, **kwargs) # If the observer location is supplied in Carrington coordinates, # the coordinate's `observer` attribute should be set to "self" if isinstance(sc.frame, HeliographicCarrington): sc.frame._observer = "self" return sc.heliographic_stonyhurst elif any(meta_list) and not set(keys).isdisjoint(self.meta.keys()): if not isinstance(kwargs['frame'], str): kwargs['frame'] = kwargs['frame'].name missing_meta[kwargs['frame']] = set(keys).difference(self.meta.keys()) warning_message = "".join( [f"For frame '{frame}" the following metadata is missing: {",".join(keys)}\n" for frame, keys in missing_meta.items()]) warning_message = "Missing metadata for observer: assuming Earth-based observer.\n" + warning_message warnings.warn(warning_message, SunpyMetadataWarning, stacklevel=3) return get_earth(self.date) @property def heliographic_latitude(self): """Observer heliographic latitude.""" return self.observer_coordinate.lat @property def heliographic_longitude(self): """Observer heliographic longitude.""" return self.observer_coordinate.lon @property def carrington_latitude(self): """Observer Carrington latitude.""" hgc_frame = HeliographicCarrington(observer=self.observer_coordinate, obstime=self.date) return self.observer_coordinate.transform_to(hgc_frame).lat @property def carrington_longitude(self): """Observer Carrington longitude.""" hgc_frame = HeliographicCarrington(observer=self.observer_coordinate, obstime=self.date) return self.observer_coordinate.transform_to(hgc_frame).lon @property def dsun(self): """Observer distance from the center of the Sun.""" return self.observer_coordinate.radius.to('m') @property def _reference_longitude(self): """ FITS-WCS compatible longitude. Used in self.wcs and self.reference_coordinate. """ return self.meta.get('crval1', 0.) * self.spatial_units[0] @property def _reference_latitude(self): return self.meta.get('crval2', 0.) * self.spatial_units[1] @property def reference_coordinate(self): """Reference point WCS axes in data units (i.e. crval1, crval2). This value includes a shift if one is set.""" return SkyCoord(self._reference_longitude, self._reference_latitude, frame=self.coordinate_frame) @property def reference_pixel(self): """ Pixel of reference coordinate. The pixel returned uses zero-based indexing, so will be 1 pixel less than the FITS CRPIX values. """ return PixelPair((self.meta.get('crpix1', (self.meta.get('naxis1') + 1) / 2.) - 1) * u.pixel, (self.meta.get('crpix2', (self.meta.get('naxis2') + 1) / 2.) - 1) * u.pixel) @property def scale(self): """ Image scale along the x and y axes in units/pixel (i.e. cdelt1, cdelt2). """ # TODO: Fix this if only CDi_j matrix is provided return SpatialPair(self.meta.get('cdelt1', 1.) * self.spatial_units[0] / u.pixel, self.meta.get('cdelt2', 1.) * self.spatial_units[1] / u.pixel) @property def spatial_units(self): """ Image coordinate units along the x and y axes (i.e. cunit1, cunit2). """ return SpatialPair(u.Unit(self.meta.get('cunit1')), u.Unit(self.meta.get('cunit2'))) @property def rotation_matrix(self): r""" Matrix describing the rotation required to align solar North with the top of the image. The order or precendence of FITS keywords which this is taken from is: - PC\*_\* - CD\*_\* - CROTA\* """ if 'PC1_1' in self.meta: return np.array([[self.meta['PC1_1'], self.meta['PC1_2']], [self.meta['PC2_1'], self.meta['PC2_2']]]) elif 'CD1_1' in self.meta: cd = np.array([[self.meta['CD1_1'], self.meta['CD1_2']], [self.meta['CD2_1'], self.meta['CD2_2']]]) cdelt = u.Quantity(self.scale).value return cd / cdelt else: return self._rotation_matrix_from_crota() def _rotation_matrix_from_crota(self): """ This method converts the deprecated CROTA FITS kwargs to the new PC rotation matrix. This method can be overriden if an instruments header does not use this conversion. """ lam = self.scale[0] / self.scale[1] p = np.deg2rad(self.meta.get('CROTA2', 0)) return np.array([[np.cos(p), -1 * lam * np.sin(p)], [1/lam * np.sin(p), np.cos(p)]]) @property def fits_header(self): """ A `~astropy.io.fits.Header` representation of the ``meta`` attribute. """ return sunpy.io.fits.header_to_fits(self.meta) # #### Miscellaneous #### # def _fix_date(self): # Check commonly used but non-standard FITS keyword for observation # time and correct the keyword if we can. Keep updating old one for # backwards compatibility. if is_time(self.meta.get('date_obs', None)): self.meta['date-obs'] = self.meta['date_obs'] def _fix_naxis(self): # If naxis is not specified, get it from the array shape if 'naxis1' not in self.meta: self.meta['naxis1'] = self.data.shape[1] if 'naxis2' not in self.meta: self.meta['naxis2'] = self.data.shape[0] if 'naxis' not in self.meta: self.meta['naxis'] = self.ndim def _fix_bitpix(self): # Bit-depth # # 8 Character or unsigned binary integer # 16 16-bit twos-complement binary integer # 32 32-bit twos-complement binary integer # -32 IEEE single precision floating point # -64 IEEE double precision floating point # if 'bitpix' not in self.meta: float_fac = -1 if self.dtype.kind == "f" else 1 self.meta['bitpix'] = float_fac * 8 * self.dtype.itemsize def _get_cmap_name(self): """Build the default color map name.""" cmap_string = (self.observatory + self.detector + str(int(self.wavelength.to('angstrom').value))) return cmap_string.lower() def _validate_meta(self): """ Validates the meta-information associated with a Map. This method includes very basic validation checks which apply to all of the kinds of files that SunPy can read. Datasource-specific validation should be handled in the relevant file in the sunpy.map.sources package. Allows for default unit assignment for: CUNIT1, CUNIT2, WAVEUNIT """ msg = ('Image coordinate units for axis {} not present in metadata.') err_message = [] for i in [1, 2]: if self.meta.get(f'cunit{i}') is None: err_message.append(msg.format(i, i)) if err_message: err_message.append( f'See {_META_FIX_URL} for instructions on how to add missing metadata.') raise MapMetaValidationError('\n'.join(err_message)) for meta_property in ('waveunit', ): if (self.meta.get(meta_property) and u.Unit(self.meta.get(meta_property), parse_strict='silent').physical_type == 'unknown'): warnings.warn(f"Unknown value for {meta_property.upper()}.", SunpyUserWarning) if (self.coordinate_system[0].startswith(('SOLX', 'SOLY')) or self.coordinate_system[1].startswith(('SOLX', 'SOLY'))): warnings.warn("SunPy Map does not support three dimensional data " "and therefore cannot represent heliocentric coordinates. Proceed at your own risk.", SunpyUserWarning) # #### Data conversion routines #### # @staticmethod def _check_origin(origin): """ Check origin is valid, and raise a deprecation warning if it's not None. """ if origin is not None: warnings.warn('The origin argument is deprecated. If using origin=1, ' 'manually subtract 1 from your pixels do not pass a value for origin.', SunpyDeprecationWarning) if origin not in [None, 0, 1]: raise ValueError('origin must be 0 or 1.') def world_to_pixel(self, coordinate, origin=None): """ Convert a world (data) coordinate to a pixel coordinate. Parameters ---------- coordinate : `~astropy.coordinates.SkyCoord` or `~astropy.coordinates.BaseCoordinateFrame` The coordinate object to convert to pixel coordinates. origin : int Deprecated. Origin of the top-left corner. i.e. count from 0 or 1. Normally, origin should be 0 when passing numpy indices, or 1 if passing values from FITS header or map attributes. Returns ------- x : `~astropy.units.Quantity` Pixel coordinate on the CTYPE1 axis. y : `~astropy.units.Quantity` Pixel coordinate on the CTYPE2 axis. """ self._check_origin(origin) x, y = self.wcs.world_to_pixel(coordinate) if origin == 1: x += 1 y += 1 return PixelPair(x * u.pixel, y * u.pixel) @u.quantity_input def pixel_to_world(self, x: u.pixel, y: u.pixel, origin=None): """ Convert a pixel coordinate to a data (world) coordinate. Parameters ---------- x : `~astropy.units.Quantity` Pixel coordinate of the CTYPE1 axis. (Normally solar-x). y : `~astropy.units.Quantity` Pixel coordinate of the CTYPE2 axis. (Normally solar-y). origin : int Deprecated. Origin of the top-left corner. i.e. count from 0 or 1. Normally, origin should be 0 when passing numpy indices, or 1 if passing values from FITS header or map attributes. Returns ------- coord : `astropy.coordinates.SkyCoord` A coordinate object representing the output coordinate. """ self._check_origin(origin) if origin == 1: x = x - 1 * u.pixel y = y - 1 * u.pixel return self.wcs.pixel_to_world(x, y) # #### I/O routines #### # def save(self, filepath, filetype='auto', **kwargs): """Saves the SunPy Map object to a file. Currently SunPy can only save files in the FITS format. In the future support will be added for saving to other formats. Parameters ---------- filepath : str Location to save file to. filetype : str 'auto' or any supported file extension. hdu_type: None, `~astropy.io.fits.CompImageHDU` `None` will return a normal FITS file. `~astropy.io.fits.CompImageHDU` will rice compress the FITS file. kwargs : Any additional keyword arguments are passed to `~sunpy.io.write_file`. """ io.write_file(filepath, self.data, self.meta, filetype=filetype, **kwargs) # #### Image processing routines #### # @u.quantity_input def resample(self, dimensions: u.pixel, method='linear'): """ Resample to new dimension sizes. Uses the same parameters and creates the same co-ordinate lookup points as IDL''s congrid routine, which apparently originally came from a VAX/VMS routine of the same name. Parameters ---------- dimensions : `~astropy.units.Quantity` Output pixel dimensions. The first argument corresponds to the 'x' axis and the second argument corresponds to the 'y' axis. method : str Method to use for resampling interpolation. * ``'neighbor'`` - Take closest value from original data. * ``'nearest'`` and ``'linear'`` - Use n x 1-D interpolations using `scipy.interpolate.interp1d`. * ``'spline'`` - Uses piecewise polynomials (splines) for mapping the input array to new coordinates by interpolation using `scipy.ndimage.map_coordinates`. Returns ------- out : `~sunpy.map.GenericMap` or subclass Resampled map References ---------- `Rebinning <https://scipy-cookbook.readthedocs.io/items/Rebinning.html>`_ """ # Note: because the underlying ndarray is transposed in sense when # compared to the Map, the ndarray is transposed, resampled, then # transposed back # Note: "center" defaults to True in this function because data # coordinates in a Map are at pixel centers # Make a copy of the original data and perform resample new_data = sunpy_image_resample(self.data.copy().T, dimensions, method, center=True) new_data = new_data.T scale_factor_x = float(self.dimensions[0] / dimensions[0]) scale_factor_y = float(self.dimensions[1] / dimensions[1]) # Update image scale and number of pixels new_meta = self.meta.copy() # Update metadata new_meta['cdelt1'] *= scale_factor_x new_meta['cdelt2'] *= scale_factor_y if 'CD1_1' in new_meta: new_meta['CD1_1'] *= scale_factor_x new_meta['CD2_1'] *= scale_factor_x new_meta['CD1_2'] *= scale_factor_y new_meta['CD2_2'] *= scale_factor_y new_meta['crpix1'] = (dimensions[0].value + 1) / 2. new_meta['crpix2'] = (dimensions[1].value + 1) / 2. lon, lat = self._get_lon_lat(self.center.frame) new_meta['crval1'] = lon.value new_meta['crval2'] = lat.value new_meta['naxis1'] = new_data.shape[1] new_meta['naxis2'] = new_data.shape[0] # Create new map instance new_map = self._new_instance(new_data, new_meta, self.plot_settings) return new_map @u.quantity_input def rotate(self, angle: u.deg = None, rmatrix=None, order=4, scale=1.0, recenter=False, missing=0.0, use_scipy=False): """ Returns a new rotated and rescaled map. Specify either a rotation angle or a rotation matrix, but not both. If neither an angle or a rotation matrix are specified, the map will be rotated by the rotation angle in the metadata. The map will be rotated around the reference coordinate defined in the meta data. This method also updates the ``rotation_matrix`` attribute and any appropriate header data so that they correctly describe the new map. Parameters ---------- angle : `~astropy.units.Quantity` The angle (degrees) to rotate counterclockwise. rmatrix : array-like 2x2 linear transformation rotation matrix. order : int Interpolation order to be used. Must be in the range 0-5. When using scikit-image this parameter is passed into :func:`skimage.transform.warp` (e.g., 4 corresponds to bi-quartic interpolation). When using scipy it is passed into :func:`scipy.ndimage.affine_transform` where it controls the order of the spline. Faster performance may be obtained at the cost of accuracy by using lower values. Default: 4 scale : float A scale factor for the image, default is no scaling recenter : bool If True, position the axis of rotation at the center of the new map Default: False missing : float The numerical value to fill any missing points after rotation. Default: 0.0 use_scipy : bool If True, forces the rotation to use :func:`scipy.ndimage.affine_transform`, otherwise it uses the :func:`skimage.transform.warp`. Default: False, unless scikit-image can't be imported Returns ------- out : `~sunpy.map.GenericMap` or subclass A new Map instance containing the rotated and rescaled data of the original map. See Also -------- sunpy.image.transform.affine_transform : The routine this method calls for the rotation. Notes ----- This function will remove old CROTA keywords from the header. This function will also convert a CDi_j matrix to a PCi_j matrix. See :func:`sunpy.image.transform.affine_transform` for details on the transformations, situations when the underlying data is modified prior to rotation, and differences from IDL's rot(). """ # Put the import here to reduce sunpy.map import time from sunpy.image.transform import affine_transform if angle is not None and rmatrix is not None: raise ValueError("You cannot specify both an angle and a rotation matrix.") elif angle is None and rmatrix is None: rmatrix = self.rotation_matrix if order not in range(6): raise ValueError("Order must be between 0 and 5.") # The FITS-WCS transform is by definition defined around the # reference coordinate in the header. lon, lat = self._get_lon_lat(self.reference_coordinate.frame) rotation_center = u.Quantity([lon, lat]) # Copy meta data new_meta = self.meta.copy() if angle is not None: # Calculate the parameters for the affine_transform c = np.cos(np.deg2rad(angle)) s = np.sin(np.deg2rad(angle)) rmatrix = np.array([[c, -s], [s, c]]) # Calculate the shape in pixels to contain all of the image data extent = np.max(np.abs(np.vstack((self.data.shape @ rmatrix, self.data.shape @ rmatrix.T))), axis=0) # Calculate the needed padding or unpadding diff = np.asarray(np.ceil((extent - self.data.shape) / 2), dtype=int).ravel() # Pad the image array pad_x = int(np.max((diff[1], 0))) pad_y = int(np.max((diff[0], 0))) new_data = np.pad(self.data, ((pad_y, pad_y), (pad_x, pad_x)), mode='constant', constant_values=(missing, missing)) new_meta['crpix1'] += pad_x new_meta['crpix2'] += pad_y # All of the following pixel calculations use a pixel origin of 0 pixel_array_center = (np.flipud(new_data.shape) - 1) / 2.0 # Create a temporary map so we can use it for the data to pixel calculation. temp_map = self._new_instance(new_data, new_meta, self.plot_settings) # Convert the axis of rotation from data coordinates to pixel coordinates pixel_rotation_center = u.Quantity(temp_map.world_to_pixel(self.reference_coordinate)).value del temp_map if recenter: pixel_center = pixel_rotation_center else: pixel_center = pixel_array_center # Apply the rotation to the image data new_data = affine_transform(new_data.T, np.asarray(rmatrix), order=order, scale=scale, image_center=np.flipud(pixel_center), recenter=recenter, missing=missing, use_scipy=use_scipy).T if recenter: new_reference_pixel = pixel_array_center else: # Calculate new pixel coordinates for the rotation center new_reference_pixel = pixel_center + np.dot(rmatrix, pixel_rotation_center - pixel_center) new_reference_pixel = np.array(new_reference_pixel).ravel() # Define the new reference_pixel new_meta['crval1'] = rotation_center[0].value new_meta['crval2'] = rotation_center[1].value new_meta['crpix1'] = new_reference_pixel[0] + 1 # FITS pixel origin is 1 new_meta['crpix2'] = new_reference_pixel[1] + 1 # FITS pixel origin is 1 # Unpad the array if necessary unpad_x = -np.min((diff[1], 0)) if unpad_x > 0: new_data = new_data[:, unpad_x:-unpad_x] new_meta['crpix1'] -= unpad_x unpad_y = -np.min((diff[0], 0)) if unpad_y > 0: new_data = new_data[unpad_y:-unpad_y, :] new_meta['crpix2'] -= unpad_y # Calculate the new rotation matrix to store in the header by # "subtracting" the rotation matrix used in the rotate from the old one # That being calculate the dot product of the old header data with the # inverse of the rotation matrix. pc_C = np.dot(self.rotation_matrix, np.linalg.inv(rmatrix)) new_meta['PC1_1'] = pc_C[0, 0] new_meta['PC1_2'] = pc_C[0, 1] new_meta['PC2_1'] = pc_C[1, 0] new_meta['PC2_2'] = pc_C[1, 1] # Update pixel size if image has been scaled. if scale != 1.0: new_meta['cdelt1'] = (self.scale[0] / scale).value new_meta['cdelt2'] = (self.scale[1] / scale).value # Remove old CROTA kwargs because we have saved a new PCi_j matrix. new_meta.pop('CROTA1', None) new_meta.pop('CROTA2', None) # Remove CDi_j header new_meta.pop('CD1_1', None) new_meta.pop('CD1_2', None) new_meta.pop('CD2_1', None) new_meta.pop('CD2_2', None) # Create new map with the modification new_map = self._new_instance(new_data, new_meta, self.plot_settings) return new_map @u.quantity_input def submap(self, bottom_left, *, top_right=None, width: (u.deg, u.pix) = None, height: (u.deg, u.pix) = None): """ Returns a submap defined by a rectangle. Any pixels which have at least part of their area inside the rectangle are returned. If the rectangle is defined in world coordinates, the smallest array which contains all four corners of the rectangle as defined in world coordinates is returned. Parameters ---------- bottom_left : `astropy.units.Quantity` or `~astropy.coordinates.SkyCoord` The bottom-left coordinate of the rectangle. If a `~astropy.coordinates.SkyCoord` it can have shape ``(2,)`` and simultaneously define ``top_right``. If specifying pixel coordinates it must be given as an `~astropy.units.Quantity` object with units of `~astropy.units.si.pix`. top_right : `astropy.units.Quantity` or `~astropy.coordinates.SkyCoord`, optional The top-right coordinate of the rectangle. If ``top_right`` is specified ``width`` and ``height`` must be omitted. width : `astropy.units.Quantity`, optional The width of the rectangle. Required if ``top_right`` is omitted. height : `astropy.units.Quantity` The height of the rectangle. Required if ``top_right`` is omitted. Returns ------- out : `~sunpy.map.GenericMap` or subclass A new map instance is returned representing to specified sub-region. Notes ----- When specifying pixel coordinates, they are specified in Cartesian order not in numpy order. So, for example, the ``bottom_left=`` argument should be ``[left, bottom]``. Examples -------- >>> import astropy.units as u >>> from astropy.coordinates import SkyCoord >>> import sunpy.map >>> import sunpy.data.sample # doctest: +REMOTE_DATA >>> aia = sunpy.map.Map(sunpy.data.sample.AIA_171_IMAGE) # doctest: +REMOTE_DATA >>> bl = SkyCoord(-300*u.arcsec, -300*u.arcsec, frame=aia.coordinate_frame) # doctest: +REMOTE_DATA >>> tr = SkyCoord(500*u.arcsec, 500*u.arcsec, frame=aia.coordinate_frame) # doctest: +REMOTE_DATA >>> aia.submap(bl, top_right=tr) # doctest: +REMOTE_DATA <sunpy.map.sources.sdo.AIAMap object at ...> SunPy Map --------- Observatory: SDO Instrument: AIA 3 Detector: AIA Measurement: 171.0 Angstrom Wavelength: 171.0 Angstrom Observation Date: 2011-06-07 06:33:02 Exposure Time: 0.234256 s Dimension: [335. 335.] pix Coordinate System: helioprojective Scale: [2.402792 2.402792] arcsec / pix Reference Pixel: [126.5 125.5] pix Reference Coord: [3.22309951 1.38578135] arcsec ... >>> aia.submap([0,0]*u.pixel, top_right=[5,5]*u.pixel) # doctest: +REMOTE_DATA <sunpy.map.sources.sdo.AIAMap object at ...> SunPy Map --------- Observatory: SDO Instrument: AIA 3 Detector: AIA Measurement: 171.0 Angstrom Wavelength: 171.0 Angstrom Observation Date: 2011-06-07 06:33:02 Exposure Time: 0.234256 s Dimension: [6. 6.] pix Coordinate System: helioprojective Scale: [2.402792 2.402792] arcsec / pix Reference Pixel: [511.5 511.5] pix Reference Coord: [3.22309951 1.38578135] arcsec ... >>> width = 10 * u.arcsec >>> height = 10 * u.arcsec >>> aia.submap(bl, width=width, height=height) # doctest: +REMOTE_DATA <sunpy.map.sources.sdo.AIAMap object at ...> SunPy Map --------- Observatory: SDO Instrument: AIA 3 Detector: AIA Measurement: 171.0 Angstrom Wavelength: 171.0 Angstrom Observation Date: 2011-06-07 06:33:02 Exposure Time: 0.234256 s Dimension: [5. 5.] pix Coordinate System: helioprojective Scale: [2.402792 2.402792] arcsec / pix Reference Pixel: [125.5 125.5] pix Reference Coord: [3.22309951 1.38578135] arcsec ... >>> bottom_left_vector = SkyCoord([0, 10] * u.deg, [0, 10] * u.deg, frame='heliographic_stonyhurst') >>> aia.submap(bottom_left_vector) # doctest: +REMOTE_DATA <sunpy.map.sources.sdo.AIAMap object at ...> SunPy Map --------- Observatory: SDO Instrument: AIA 3 Detector: AIA Measurement: 171.0 Angstrom Wavelength: 171.0 Angstrom Observation Date: 2011-06-07 06:33:02 Exposure Time: 0.234256 s Dimension: [70. 69.] pix Coordinate System: helioprojective Scale: [2.402792 2.402792] arcsec / pix Reference Pixel: [1.5 0.5] pix Reference Coord: [3.22309951 1.38578135] arcsec ... """ # Check that we have been given a valid combination of inputs # [False, False, False] is valid if bottom_left contains the two corner coords if ([arg is not None for arg in (top_right, width, height)] not in [[True, False, False], [False, False, False], [False, True, True]]): raise ValueError("Either top_right alone or both width and height must be specified.") # parse input arguments pixel_corners = u.Quantity(self._parse_submap_input( bottom_left, top_right, width, height)).T # The pixel corners result is in Cartesian order, so the first index is # columns and the second is rows. bottom = np.min(pixel_corners[1]).to_value(u.pix) top = np.max(pixel_corners[1]).to_value(u.pix) left = np.min(pixel_corners[0]).to_value(u.pix) right = np.max(pixel_corners[0]).to_value(u.pix) # Round the lower left pixel to the nearest integer # We want 0.5 to be rounded up to 1, so use floor(x + 0.5) bottom = np.floor(bottom + 0.5) left = np.floor(left + 0.5) # Round the top right pixel to the nearest integer, then add 1 for array indexing # We want e.g. 2.5 to be rounded down to 2, so use ceil(x - 0.5) top = np.ceil(top - 0.5) + 1 right = np.ceil(right - 0.5) + 1 # Clip pixel values to max of array, prevents negative # indexing bottom = int(np.clip(bottom, 0, self.data.shape[0])) top = int(np.clip(top, 0, self.data.shape[0])) left = int(np.clip(left, 0, self.data.shape[1])) right = int(np.clip(right, 0, self.data.shape[1])) arr_slice = np.s_[bottom:top, left:right] # Get ndarray representation of submap new_data = self.data[arr_slice].copy() # Make a copy of the header with updated centering information new_meta = self.meta.copy() # Add one to go from zero-based to one-based indexing new_meta['crpix1'] = self.reference_pixel.x.to_value(u.pix) + 1 - left new_meta['crpix2'] = self.reference_pixel.y.to_value(u.pix) + 1 - bottom new_meta['naxis1'] = new_data.shape[1] new_meta['naxis2'] = new_data.shape[0] # Create new map instance if self.mask is not None: new_mask = self.mask[arr_slice].copy() # Create new map with the modification new_map = self._new_instance(new_data, new_meta, self.plot_settings, mask=new_mask) return new_map # Create new map with the modification new_map = self._new_instance(new_data, new_meta, self.plot_settings) return new_map @seconddispatch def _parse_submap_input(self, bottom_left, top_right, width, height): """ Should take any valid input to submap() and return bottom_left and top_right in pixel coordinates. """ @_parse_submap_input.register(u.Quantity) def _parse_submap_quantity_input(self, bottom_left, top_right, width, height): if top_right is None and width is None: raise ValueError('Either top_right alone or both width and height must be specified ' 'when bottom_left is a Quantity') if bottom_left.shape != (2, ): raise ValueError('bottom_left must have shape (2, ) when specified as a Quantity') if top_right is not None: if top_right.shape != (2, ): raise ValueError('top_right must have shape (2, ) when specified as a Quantity') if not top_right.unit.is_equivalent(u.pix): raise TypeError("When bottom_left is a Quantity, top_right " "must be a Quantity in units of pixels.") # Have bottom_left and top_right in pixels already, so no need to do # anything else else: if not (width.unit.is_equivalent(u.pix) and height.unit.is_equivalent(u.pix)): raise TypeError("When bottom_left is a Quantity, width and height " "must be a Quantity in units of pixels.") # Add width and height to get top_right top_right = u.Quantity([bottom_left[0] + width, bottom_left[1] + height]) top_left = u.Quantity([top_right[0], bottom_left[1]]) bottom_right = u.Quantity([bottom_left[0], top_right[1]]) return bottom_left, top_left, top_right, bottom_right @_parse_submap_input.register(SkyCoord) def _parse_submap_coord_input(self, bottom_left, top_right, width, height): # Use helper function to get top_right as a SkyCoord bottom_left, top_right = get_rectangle_coordinates(bottom_left, top_right=top_right, width=width, height=height) frame = bottom_left.frame left_lon, bottom_lat = self._get_lon_lat(bottom_left) right_lon, top_lat = self._get_lon_lat(top_right) corners = SkyCoord([left_lon, left_lon, right_lon, right_lon], [bottom_lat, top_lat, top_lat, bottom_lat], frame=frame) return tuple(u.Quantity(self.wcs.world_to_pixel(corners), u.pix).T) @u.quantity_input def superpixel(self, dimensions: u.pixel, offset: u.pixel = (0, 0)*u.pixel, func=np.sum): """Returns a new map consisting of superpixels formed by applying 'func' to the original map data. Parameters ---------- dimensions : tuple One superpixel in the new map is equal to (dimension[0], dimension[1]) pixels of the original map. Note: the first argument corresponds to the 'x' axis and the second argument corresponds to the 'y' axis. offset : tuple Offset from (0,0) in original map pixels used to calculate where the data used to make the resulting superpixel map starts. func : Function applied to the original data. The function 'func' must take a numpy array as its first argument, and support the axis keyword with the meaning of a numpy axis keyword (see the description of `~numpy.sum` for an example.) The default value of 'func' is `~numpy.sum`; using this causes superpixel to sum over (dimension[0], dimension[1]) pixels of the original map. Returns ------- out : `~sunpy.map.GenericMap` or subclass A new Map which has superpixels of the required size. References ---------- | `Summarizing blocks of an array using a moving window <https://mail.scipy.org/pipermail/numpy-discussion/2010-July/051760.html>`_ """ # Note: because the underlying ndarray is transposed in sense when # compared to the Map, the ndarray is transposed, resampled, then # transposed back. # Note: "center" defaults to True in this function because data # coordinates in a Map are at pixel centers. if (offset.value[0] < 0) or (offset.value[1] < 0): raise ValueError("Offset is strictly non-negative.") # Make a copy of the original data, perform reshaping, and apply the # function. if self.mask is not None: reshaped = reshape_image_to_4d_superpixel(np.ma.array(self.data.copy(), mask=self.mask), [dimensions.value[1], dimensions.value[0]], [offset.value[1], offset.value[0]]) else: reshaped = reshape_image_to_4d_superpixel(self.data.copy(), [dimensions.value[1], dimensions.value[0]], [offset.value[1], offset.value[0]]) new_array = func(func(reshaped, axis=3), axis=1) # Update image scale and number of pixels # create copy of new meta data new_meta = self.meta.copy() new_nx = new_array.shape[1] new_ny = new_array.shape[0] # Update metadata new_meta['cdelt1'] = (dimensions[0] * self.scale[0]).value new_meta['cdelt2'] = (dimensions[1] * self.scale[1]).value if 'CD1_1' in new_meta: new_meta['CD1_1'] *= dimensions[0].value new_meta['CD2_1'] *= dimensions[0].value new_meta['CD1_2'] *= dimensions[1].value new_meta['CD2_2'] *= dimensions[1].value new_meta['crpix1'] = (new_nx + 1) / 2. new_meta['crpix2'] = (new_ny + 1) / 2. lon, lat = self._get_lon_lat(self.center.frame) new_meta['crval1'] = lon.to(self.spatial_units[0]).value + 0.5 * \ (offset[0]*self.scale[0]).to(self.spatial_units[0]).value new_meta['crval2'] = lat.to(self.spatial_units[1]).value + 0.5 * \ (offset[1]*self.scale[1]).to(self.spatial_units[1]).value # Create new map instance if self.mask is not None: new_data = np.ma.getdata(new_array) new_mask = np.ma.getmask(new_array) else: new_data = new_array new_mask = None # Create new map with the modified data new_map = self._new_instance(new_data, new_meta, self.plot_settings, mask=new_mask) return new_map # #### Visualization #### # @property def cmap(self): """ Return the `matplotlib.colors.Colormap` instance this map uses. """ cmap = self.plot_settings['cmap'] if isinstance(cmap, str): cmap = plt.get_cmap(cmap) # Set the colormap to be this specific instance so we are not # returning a copy self.plot_settings['cmap'] = cmap return cmap @u.quantity_input def draw_grid(self, axes=None, grid_spacing: u.deg = 15*u.deg, annotate=True, **kwargs): """ Draws a coordinate overlay on the plot in the Heliographic Stonyhurst coordinate system. To overlay other coordinate systems see the `WCSAxes Documentation <https://docs.astropy.org/en/stable/visualization/wcsaxes/overlaying_coordinate_systems.html>`_ Parameters ---------- axes: `~matplotlib.axes` or `None` Axes to plot limb on, or `None` to use current axes. grid_spacing: `~astropy.units.Quantity` Spacing for longitude and latitude grid, if length two it specifies (lon, lat) spacing. annotate : `bool` Passing `False` disables the axes labels and the ticks on the top and right axes. Returns ------- overlay: `~astropy.visualization.wcsaxes.CoordinatesMap` The wcsaxes coordinate overlay instance. Notes ----- Keyword arguments are passed onto the `sunpy.visualization.wcsaxes_compat.wcsaxes_heliographic_overlay` function. """ if not axes: axes = wcsaxes_compat.gca_wcs(self.wcs) if not wcsaxes_compat.is_wcsaxes(axes): raise TypeError("Overlay grids can only be plotted on WCSAxes plots.") return wcsaxes_compat.wcsaxes_heliographic_overlay(axes, grid_spacing=grid_spacing, annotate=annotate, **kwargs) def draw_limb(self, axes=None, **kwargs): """ Draws a circle representing the solar limb Parameters ---------- axes: `~matplotlib.axes` or None Axes to plot limb on or None to use current axes. Returns ------- circ: list A list containing the `~matplotlib.patches.Circle` object that has been added to the axes. Notes ----- Keyword arguments are passed onto `matplotlib.patches.Circle`. """ # Put import here to reduce sunpy.map import time from matplotlib import patches if not axes: axes = wcsaxes_compat.gca_wcs(self.wcs) transform = wcsaxes_compat.get_world_transform(axes) if wcsaxes_compat.is_wcsaxes(axes): radius = self.rsun_obs.to(u.deg).value else: radius = self.rsun_obs.value c_kw = {'radius': radius, 'fill': False, 'color': 'white', 'zorder': 100, 'transform': transform } c_kw.update(kwargs) circ = patches.Circle([0, 0], **c_kw) axes.add_artist(circ) return [circ] @u.quantity_input def draw_rectangle(self, bottom_left, *, width: u.deg = None, height: u.deg = None, axes=None, top_right=None, **kwargs): """ Draw a rectangle defined in world coordinates on the plot. This draws a rectangle that has corners at ``(bottom_left, top_right)``, and has sides parallel to coordinate axes of the map. If ``width`` and ``height`` are specified, they are respectively added to the longitude and latitude of the ``bottom_left`` coordinate to calculate a ``top_right`` coordinate. Parameters ---------- bottom_left : `~astropy.coordinates.SkyCoord` The bottom-left coordinate of the rectangle. It can have shape ``(2,)`` to simultaneously define ``top_right``. top_right : `~astropy.coordinates.SkyCoord` The top-right coordinate of the rectangle. width : `astropy.units.Quantity`, optional The width of the rectangle. Required if ``top_right`` is omitted. height : `astropy.units.Quantity` The height of the rectangle. Required if ``top_right`` is omitted. axes : `matplotlib.axes.Axes` The axes on which to plot the rectangle, defaults to the current axes. Returns ------- rect : `list` A list containing the `~matplotlib.patches.Rectangle` object, after it has been added to ``axes``. Notes ----- Extra keyword arguments to this function are passed through to the `~matplotlib.patches.Rectangle` instance. """ bottom_left, top_right = get_rectangle_coordinates(bottom_left, top_right=top_right, width=width, height=height) bottom_left = bottom_left.transform_to(self.coordinate_frame) top_right = top_right.transform_to(self.coordinate_frame) width = Longitude(top_right.spherical.lon - bottom_left.spherical.lon) height = top_right.spherical.lat - bottom_left.spherical.lat if not axes: axes = plt.gca() if wcsaxes_compat.is_wcsaxes(axes): axes_unit = u.deg else: axes_unit = self.spatial_units[0] bottom_left = u.Quantity(self._get_lon_lat(bottom_left), unit=axes_unit).value width = width.to(axes_unit).value height = height.to(axes_unit).value kwergs = {'transform': wcsaxes_compat.get_world_transform(axes), 'edgecolor': 'white', 'fill': False} kwergs.update(kwargs) rect = plt.Rectangle(bottom_left, width, height, **kwergs) axes.add_artist(rect) return [rect] @u.quantity_input def draw_contours(self, levels: u.percent, axes=None, **contour_args): """ Draw contours of the data. Parameters ---------- levels : `~astropy.units.Quantity` A list of numbers indicating the contours to draw. These are given as a percentage of the maximum value of the map data. axes : `matplotlib.axes.Axes` The axes on which to plot the contours. Defaults to the current axes. Returns ------- cs : `list` The `~matplotlib.contour.QuadContourSet` object, after it has been added to ``axes``. Notes ----- Extra keyword arguments to this function are passed through to the `~matplotlib.pyplot.contour` function. """ if not axes: axes = wcsaxes_compat.gca_wcs(self.wcs) # TODO: allow for use of direct input of contours but requires units of # map flux which is not yet implemented cs = axes.contour(self.data, 0.01 * levels.to('percent').value * self.data.max(), **contour_args) return cs @peek_show def peek(self, draw_limb=False, draw_grid=False, colorbar=True, **matplot_args): """ Displays a graphical overview of the data in this object for user evaluation. For the creation of plots, users should instead use the `~sunpy.map.GenericMap.plot` method and Matplotlib's pyplot framework. Parameters ---------- draw_limb : bool Whether the solar limb should be plotted. draw_grid : bool or `~astropy.units.Quantity` Whether solar meridians and parallels are plotted. If `~astropy.units.Quantity` then sets degree difference between parallels and meridians. colorbar : bool Whether to display a colorbar next to the plot. **matplot_args : dict Matplotlib Any additional imshow arguments that should be used when plotting. """ figure = plt.figure() axes = wcsaxes_compat.gca_wcs(self.wcs) im = self.plot(axes=axes, **matplot_args) grid_spacing = None # Handle case where draw_grid is actually the grid sapcing if isinstance(draw_grid, u.Quantity): grid_spacing = draw_grid draw_grid = True elif not isinstance(draw_grid, bool): raise TypeError("draw_grid should be a bool or an astropy Quantity.") if colorbar: if draw_grid: pad = 0.12 # Pad to compensate for ticks and axes labels else: pad = 0.05 # Default value for vertical colorbar colorbar_label = str(self.unit) if self.unit is not None else "" figure.colorbar(im, pad=pad).set_label(colorbar_label, rotation=0, labelpad=-50, y=-0.02, size=12) if draw_limb: self.draw_limb(axes=axes) if draw_grid: if grid_spacing is None: self.draw_grid(axes=axes) else: self.draw_grid(axes=axes, grid_spacing=grid_spacing) return figure @u.quantity_input def plot(self, annotate=True, axes=None, title=True, clip_interval: u.percent = None, **imshow_kwargs): """ Plots the map object using matplotlib, in a method equivalent to plt.imshow() using nearest neighbour interpolation. Parameters ---------- annotate : `bool`, optional If `True`, the data is plotted at its natural scale; with title and axis labels. axes: `~matplotlib.axes` or None If provided the image will be plotted on the given axes. Else the current matplotlib axes will be used. title : `str`, `bool`, optional The plot title. If `True`, uses the default title for this map. clip_interval : two-element `~astropy.units.Quantity`, optional If provided, the data will be clipped to the percentile interval bounded by the two numbers. **imshow_kwargs : `dict` Any additional imshow arguments are passed to `~matplotlib.axes.Axes.imshow`. Examples -------- >>> # Simple Plot with color bar >>> aia.plot() # doctest: +SKIP >>> plt.colorbar() # doctest: +SKIP >>> # Add a limb line and grid >>> aia.plot() # doctest: +SKIP >>> aia.draw_limb() # doctest: +SKIP >>> aia.draw_grid() # doctest: +SKIP """ # Get current axes if not axes: axes = wcsaxes_compat.gca_wcs(self.wcs) if not wcsaxes_compat.is_wcsaxes(axes): warnings.warn("WCSAxes not being used as the axes object for this plot." " Plots may have unexpected behaviour. To fix this pass " "'projection=map' when creating the axes", SunpyUserWarning) # Check if the image is properly oriented if not np.array_equal(self.rotation_matrix, np.identity(2)): warnings.warn("The axes of this map are not aligned to the pixel grid. Plot axes may be incorrect.", SunpyUserWarning) # Normal plot plot_settings = copy.deepcopy(self.plot_settings) if 'title' in plot_settings: plot_settings_title = plot_settings.pop('title') else: plot_settings_title = self.latex_name # Anything left in plot_settings is given to imshow imshow_args = plot_settings if annotate: if title is True: title = plot_settings_title if title: axes.set_title(title) axes.set_xlabel(axis_labels_from_ctype(self.coordinate_system[0], self.spatial_units[0])) axes.set_ylabel(axis_labels_from_ctype(self.coordinate_system[1], self.spatial_units[1])) if not wcsaxes_compat.is_wcsaxes(axes): bl = self._get_lon_lat(self.bottom_left_coord) tr = self._get_lon_lat(self.top_right_coord) x_range = list(u.Quantity([bl[0], tr[0]]).to(self.spatial_units[0]).value) y_range = list(u.Quantity([bl[1], tr[1]]).to(self.spatial_units[1]).value) imshow_args.update({'extent': x_range + y_range}) # Take a deep copy here so that a norm in imshow_kwargs doesn't get modified # by setting it's vmin and vmax imshow_args.update(copy.deepcopy(imshow_kwargs)) if clip_interval is not None: if len(clip_interval) == 2: clip_percentages = clip_interval.to('%').value vmin, vmax = AsymmetricPercentileInterval(*clip_percentages).get_limits(self.data) else: raise ValueError("Clip percentile interval must be specified as two numbers.") imshow_args['vmin'] = vmin imshow_args['vmax'] = vmax if 'norm' in imshow_args: norm = imshow_args['norm'] if 'vmin' in imshow_args: if norm.vmin is not None: raise ValueError('Cannot manually specify vmin, as the norm ' 'already has vmin set') norm.vmin = imshow_args.pop('vmin') if 'vmax' in imshow_args: if norm.vmax is not None: raise ValueError('Cannot manually specify vmax, as the norm ' 'already has vmax set') norm.vmax = imshow_args.pop('vmax') if self.mask is None: ret = axes.imshow(self.data, **imshow_args) else: ret = axes.imshow(np.ma.array(np.asarray(self.data), mask=self.mask), **imshow_args) if wcsaxes_compat.is_wcsaxes(axes): wcsaxes_compat.default_wcs_grid(axes) # Set current axes/image if pyplot is being used (makes colorbar work) for i in plt.get_fignums(): if axes in plt.figure(i).axes: plt.sca(axes) plt.sci(ret) return ret def contour(self, level, **kwargs): """ Returns coordinates of the contours for a given level value. For details of the contouring algorithm see `skimage.measure.find_contours`. Parameters ---------- level : float, astropy.units.Quantity Value along which to find contours in the array. If the map unit attribute is not `None`, this must be a `~astropy.units.Quantity` with units equivalent to the map data units. kwargs : Additional keyword arguments are passed to `skimage.measure.find_contours`. Returns ------- contours: list of (n,2) `~astropy.coordinates.SkyCoord` Coordinates of each contour. Examples -------- >>> import astropy.units as u >>> import sunpy.map >>> import sunpy.data.sample # doctest: +REMOTE_DATA >>> aia = sunpy.map.Map(sunpy.data.sample.AIA_171_IMAGE) # doctest: +REMOTE_DATA >>> contours = aia.contour(50000 * u.ct) # doctest: +REMOTE_DATA >>> print(contours[0]) # doctest: +REMOTE_DATA <SkyCoord (Helioprojective: obstime=2011-06-07T06:33:02.770, rsun=696000000.0 m, observer=<HeliographicStonyhurst Coordinate (obstime=2011-06-07T06:33:02.770): (lon, lat, radius) in (deg, deg, m) (-0.00406308, 0.04787238, 1.51846026e+11)>): (Tx, Ty) in arcsec [(719.59798458, -352.60839064), (717.19243987, -353.75348121), ... See also -------- `skimage.measure.find_contours` """ from skimage import measure if self.unit is not None: try: level = level.to_value(self.unit) # Catch cases where level can't be converted or isn't a Quantity except (AttributeError, u.UnitConversionError) as e: raise u.UnitsError( f'level must be an astropy quantity convertible to {self.unit}') from e contours = measure.find_contours(self.data, level=level, **kwargs) contours = [self.wcs.array_index_to_world(c[:, 0], c[:, 1]) for c in contours] return contours class InvalidHeaderInformation(ValueError): """Exception to raise when an invalid header tag value is encountered for a FITS/JPEG 2000 file.""" def _figure_to_base64(fig): # Converts a matplotlib Figure to a base64 UTF-8 string buf = BytesIO() fig.savefig(buf, format='png', facecolor='none') # works better than transparent=True return b64encode(buf.getvalue()).decode('utf-8')
""" Map is a generic Map class from which all other Map classes inherit from. """ import copy import html import textwrap import warnings import webbrowser from io import BytesIO from base64 import b64encode from tempfile import NamedTemporaryFile from collections import namedtuple import matplotlib.pyplot as plt import numpy as np from matplotlib import cm from matplotlib.backend_bases import FigureCanvasBase from matplotlib.figure import Figure import astropy.units as u import astropy.wcs from astropy.coordinates import Longitude, SkyCoord, UnitSphericalRepresentation from astropy.nddata import NDData from astropy.visualization import AsymmetricPercentileInterval, HistEqStretch, ImageNormalize from astropy.visualization.wcsaxes import WCSAxes # The next two are not used but are called to register functions with external modules import sunpy.coordinates import sunpy.io as io import sunpy.visualization.colormaps from sunpy import config from sunpy.coordinates import HeliographicCarrington, HeliographicStonyhurst, get_earth, sun from sunpy.coordinates.utils import get_rectangle_coordinates from sunpy.image.resample import resample as sunpy_image_resample from sunpy.image.resample import reshape_image_to_4d_superpixel from sunpy.sun import constants from sunpy.time import is_time, parse_time from sunpy.util import MetaDict, expand_list from sunpy.util.decorators import cached_property_based_on, deprecated from sunpy.util.exceptions import SunpyDeprecationWarning, SunpyMetadataWarning, SunpyUserWarning from sunpy.util.functools import seconddispatch from sunpy.visualization import axis_labels_from_ctype, peek_show, wcsaxes_compat TIME_FORMAT = config.get("general", "time_format") PixelPair = namedtuple('PixelPair', 'x y') SpatialPair = namedtuple('SpatialPair', 'axis1 axis2') _META_FIX_URL = 'https://docs.sunpy.org/en/stable/code_ref/map.html#fixing-map-metadata' __all__ = ['GenericMap'] class MapMetaValidationError(AttributeError): pass class GenericMap(NDData): """ A Generic spatially-aware 2D data array Parameters ---------- data : `numpy.ndarray`, list A 2d list or ndarray containing the map data. header : dict A dictionary of the original image header tags. plot_settings : dict, optional Plot settings. Other Parameters ---------------- **kwargs : Additional keyword arguments are passed to `~astropy.nddata.NDData` init. Examples -------- >>> import sunpy.map >>> import sunpy.data.sample # doctest: +REMOTE_DATA >>> aia = sunpy.map.Map(sunpy.data.sample.AIA_171_IMAGE) # doctest: +REMOTE_DATA >>> aia # doctest: +REMOTE_DATA <sunpy.map.sources.sdo.AIAMap object at ...> SunPy Map --------- Observatory: SDO Instrument: AIA 3 Detector: AIA Measurement: 171.0 Angstrom Wavelength: 171.0 Angstrom Observation Date: 2011-06-07 06:33:02 Exposure Time: 0.234256 s Dimension: [1024. 1024.] pix Coordinate System: helioprojective Scale: [2.402792 2.402792] arcsec / pix Reference Pixel: [511.5 511.5] pix Reference Coord: [3.22309951 1.38578135] arcsec array([[ -95.92475 , 7.076416 , -1.9656711, ..., -127.96519 , -127.96519 , -127.96519 ], [ -96.97533 , -5.1167884, 0. , ..., -98.924576 , -104.04137 , -127.919716 ], [ -93.99607 , 1.0189276, -4.0757103, ..., -5.094638 , -37.95505 , -127.87541 ], ..., [-128.01454 , -128.01454 , -128.01454 , ..., -128.01454 , -128.01454 , -128.01454 ], [-127.899666 , -127.899666 , -127.899666 , ..., -127.899666 , -127.899666 , -127.899666 ], [-128.03072 , -128.03072 , -128.03072 , ..., -128.03072 , -128.03072 , -128.03072 ]], dtype=float32) >>> aia.spatial_units # doctest: +REMOTE_DATA SpatialPair(axis1=Unit("arcsec"), axis2=Unit("arcsec")) >>> aia.peek() # doctest: +SKIP Notes ----- A number of the properties of this class are returned as two-value named tuples that can either be indexed by position ([0] or [1]) or be accessed by the names (.x and .y) or (.axis1 and .axis2). Things that refer to pixel axes use the ``.x``, ``.y`` convention, where x and y refer to the FITS axes (x for columns y for rows). Spatial axes use ``.axis1`` and ``.axis2`` which correspond to the first and second axes in the header. ``axis1`` corresponds to the coordinate axis for ``x`` and ``axis2`` corresponds to ``y``. This class makes some assumptions about the WCS information contained in the meta data. The first and most extensive assumption is that it is FITS-like WCS information as defined in the FITS WCS papers. Within this scope it also makes some other assumptions. * In the case of APIS convention headers where the CROTAi/j arguments are provided it assumes that these can be converted to the standard PCi_j notation using equations 32 in Thompson (2006). * If a CDi_j matrix is provided it is assumed that it can be converted to a PCi_j matrix and CDELT keywords as described in `Greisen & Calabretta (2002) <https://doi.org/10.1051/0004-6361:20021327>`_ * The 'standard' FITS keywords that are used by this class are the PCi_j matrix and CDELT, along with the other keywords specified in the WCS papers. All subclasses of this class must convert their header information to this formalism. The CROTA to PCi_j conversion is done in this class. .. warning:: This class currently assumes that a header with the CDi_j matrix information also includes the CDELT keywords, without these keywords this class will not process the WCS. Also the rotation_matrix does not work if the CDELT1 and CDELT2 keywords are exactly equal. Also, if a file with more than two dimensions is feed into the class, only the first two dimensions (NAXIS1, NAXIS2) will be loaded and the rest will be discarded. """ _registry = dict() def __init_subclass__(cls, **kwargs): """ An __init_subclass__ hook initializes all of the subclasses of a given class. So for each subclass, it will call this block of code on import. This replicates some metaclass magic without the need to be aware of metaclasses. Here we use this to register each subclass in a dict that has the `is_datasource_for` attribute. This is then passed into the Map Factory so we can register them. """ super().__init_subclass__(**kwargs) if hasattr(cls, 'is_datasource_for'): cls._registry[cls] = cls.is_datasource_for def __init__(self, data, header, plot_settings=None, **kwargs): # If the data has more than two dimensions, the first dimensions # (NAXIS1, NAXIS2) are used and the rest are discarded. ndim = data.ndim if ndim > 2: # We create a slice that removes all but the 'last' two # dimensions. (Note dimensions in ndarray are in reverse order) new_2d_slice = [0]*(ndim-2) new_2d_slice.extend([slice(None), slice(None)]) data = data[tuple(new_2d_slice)] # Warn the user that the data has been truncated warnings.warn("This file contains more than 2 dimensions. " "Data will be truncated to the first two dimensions.", SunpyUserWarning) super().__init__(data, meta=MetaDict(header), **kwargs) # Correct possibly missing meta keywords self._fix_date() self._fix_naxis() # Setup some attributes self._nickname = None # These are palceholders for default attributes, which are only set # once if their data isn't present in the map metadata. self._default_time = None self._default_dsun = None self._default_carrington_longitude = None self._default_heliographic_latitude = None self._default_heliographic_longitude = None # Validate header # TODO: This should be a function of the header, not of the map self._validate_meta() self._shift = SpatialPair(0 * u.arcsec, 0 * u.arcsec) if self.dtype == np.uint8: norm = None else: # Put import here to reduce sunpy.map import time from matplotlib import colors norm = colors.Normalize() # Visualization attributes self.plot_settings = {'cmap': 'gray', 'norm': norm, 'interpolation': 'nearest', 'origin': 'lower' } if plot_settings: self.plot_settings.update(plot_settings) def __getitem__(self, key): """ This should allow indexing by physical coordinate """ raise NotImplementedError( "The ability to index Map by physical" " coordinate is not yet implemented.") def _text_summary(self): return textwrap.dedent("""\ SunPy Map --------- Observatory:\t\t {obs} Instrument:\t\t {inst} Detector:\t\t {det} Measurement:\t\t {meas} Wavelength:\t\t {wave} Observation Date:\t {date} Exposure Time:\t\t {dt:f} Dimension:\t\t {dim} Coordinate System:\t {coord} Scale:\t\t\t {scale} Reference Pixel:\t {refpix} Reference Coord:\t {refcoord}\ """).format(obs=self.observatory, inst=self.instrument, det=self.detector, meas=self.measurement, wave=self.wavelength, date=self.date.strftime(TIME_FORMAT), dt=self.exposure_time, dim=u.Quantity(self.dimensions), scale=u.Quantity(self.scale), coord=self._coordinate_frame_name, refpix=u.Quantity(self.reference_pixel), refcoord=u.Quantity((self._reference_longitude, self._reference_latitude)), tmf=TIME_FORMAT) def __str__(self): return f"{self._text_summary()}\n{self.data.__repr__()}" def __repr__(self): return f"{object.__repr__(self)}\n{self}" def _repr_html_(self): """ Produce an HTML summary with plots for use in Jupyter notebooks. """ # Convert the text repr to an HTML table partial_html = self._text_summary()[20:].replace('\n', '</td></tr><tr><th>')\ .replace(':\t', '</th><td>') text_to_table = textwrap.dedent(f"""\ <table style='text-align:left'> <tr><th>{partial_html}</td></tr> </table>""").replace('\n', '') # Handle bad values (infinite and NaN) in the data array finite_data = self.data[np.isfinite(self.data)] count_nan = np.isnan(self.data).sum() count_inf = np.isinf(self.data).sum() # Assemble an informational string with the counts of bad pixels bad_pixel_text = "" if count_nan + count_inf > 0: bad_pixel_text = "Bad pixels are shown in red: " text_list = [] if count_nan > 0: text_list.append(f"{count_nan} NaN") if count_inf > 0: text_list.append(f"{count_inf} infinite") bad_pixel_text += ", ".join(text_list) # Use a grayscale colormap with histogram equalization (and red for bad values) # Make a copy of the colormap to avoid modifying the matplotlib instance when # doing set_bad() cmap = copy.copy(cm.get_cmap('gray')) cmap.set_bad(color='red') norm = ImageNormalize(stretch=HistEqStretch(finite_data)) # Plot the image in pixel space fig = Figure(figsize=(5.2, 4.8)) # Figure instances in matplotlib<3.1 do not create a canvas by default if fig.canvas is None: FigureCanvasBase(fig) ax = fig.subplots() ax.imshow(self.data, origin='lower', interpolation='nearest', cmap=cmap, norm=norm) ax.set_xlabel('X pixel') ax.set_ylabel('Y pixel') ax.set_title('In pixel space') pixel_src = _figure_to_base64(fig) bounds = ax.get_position().bounds # save these axes bounds for later use # Plot the image using WCS information, with the same axes bounds as above fig = Figure(figsize=(5.2, 4.8)) # Figure instances in matplotlib<3.1 do not create a canvas by default if fig.canvas is None: FigureCanvasBase(fig) # Create the WCSAxes manually because we need to avoid using pyplot ax = WCSAxes(fig, bounds, aspect='equal', wcs=self.wcs) fig.add_axes(ax) self.plot(axes=ax, cmap=cmap, norm=norm) ax.set_title('In coordinate space using WCS information') wcs_src = _figure_to_base64(fig) # Plot the histogram of pixel values fig = Figure(figsize=(4.8, 2.4), constrained_layout=True) # Figure instances in matplotlib<3.1 do not create a canvas by default if fig.canvas is None: FigureCanvasBase(fig) ax = fig.subplots() ax.hist(finite_data.ravel(), bins=100, histtype='stepfilled') ax.set_facecolor('white') ax.semilogy() # Explicitly set the power limits for the X axis formatter to avoid text overlaps ax.xaxis.get_major_formatter().set_powerlimits((-3, 4)) ax.set_xlabel('Pixel value') ax.set_ylabel('# of pixels') ax.set_title('Distribution of pixels with finite values') hist_src = _figure_to_base64(fig) return textwrap.dedent(f"""\ <pre>{html.escape(object.__repr__(self))}</pre> <table> <tr> <td>{text_to_table}</td> <td rowspan=3> <div align=center> Image colormap uses histogram equalization<br> Click on the image to toggle between units </div> <img src='data:image/png;base64,{wcs_src}' src2='data:image/png;base64,{pixel_src}' onClick='var temp = this.src; this.src = this.getAttribute("src2"); this.setAttribute("src2", temp)' /> <div align=center> {bad_pixel_text} </div> </td> </tr> <tr> </tr> <tr> <td><img src='data:image/png;base64,{hist_src}'/></td> </tr> </table>""") def quicklook(self): """ Display a quicklook summary of the Map instance using the default web browser. Notes ----- The image colormap uses `histogram equalization <https://en.wikipedia.org/wiki/Histogram_equalization>`__. Clicking on the image to switch between pixel space and coordinate space requires Javascript support to be enabled in the web browser. Examples -------- >>> from sunpy.map import Map >>> import sunpy.data.sample # doctest: +REMOTE_DATA >>> smap = Map(sunpy.data.sample.AIA_171_IMAGE) # doctest: +REMOTE_DATA >>> smap.quicklook() # doctest: +SKIP (which will open the following content in the default web browser) .. generate:: html :html_border: from sunpy.map import Map import sunpy.data.sample smap = Map(sunpy.data.sample.AIA_171_IMAGE) print(smap._repr_html_()) """ with NamedTemporaryFile('w', delete=False, prefix='sunpy.map.', suffix='.html') as f: url = 'file://' + f.name f.write(textwrap.dedent(f"""\ <html> <title>Quicklook summary for {html.escape(object.__repr__(self))}</title> <body>{self._repr_html_()}</body> </html>""")) webbrowser.open_new_tab(url) @classmethod def _new_instance(cls, data, meta, plot_settings=None, **kwargs): """ Instantiate a new instance of this class using given data. This is a shortcut for ``type(self)(data, meta, plot_settings)``. """ return cls(data, meta, plot_settings=plot_settings, **kwargs) def _get_lon_lat(self, frame): """ Given a coordinate frame, extract the lon and lat by casting to SphericalRepresentation first. """ r = frame.represent_as(UnitSphericalRepresentation) return r.lon.to(self.spatial_units[0]), r.lat.to(self.spatial_units[1]) @property def _meta_hash(self): return self.meta.item_hash() @property @cached_property_based_on('_meta_hash') def wcs(self): """ The `~astropy.wcs.WCS` property of the map. """ # Construct the WCS based on the FITS header, but don't "do_set" which # analyses the FITS header for correctness. with warnings.catch_warnings(): # Ignore warnings we may raise when constructing the fits header about dropped keys. warnings.simplefilter("ignore", SunpyUserWarning) try: w2 = astropy.wcs.WCS(header=self.fits_header, _do_set=False) except Exception as e: warnings.warn("Unable to treat `.meta` as a FITS header, assuming a simple WCS. " f"The exception raised was:\n{e}") w2 = astropy.wcs.WCS(naxis=2) # If the FITS header is > 2D pick the first 2 and move on. # This will require the FITS header to be valid. if w2.naxis > 2: # We have to change this or else the WCS doesn't parse properly, even # though we don't care about the third dimension. This applies to both # EIT and IRIS data, it is here to reduce the chances of silly errors. if self.meta.get('cdelt3', None) == 0: w2.wcs.cdelt[2] = 1e-10 w2 = w2.sub([1, 2]) # Add one to go from zero-based to one-based indexing w2.wcs.crpix = u.Quantity(self.reference_pixel) + 1 * u.pix # Make these a quantity array to prevent the numpy setting element of # array with sequence error. w2.wcs.cdelt = u.Quantity(self.scale) w2.wcs.crval = u.Quantity([self._reference_longitude, self._reference_latitude]) w2.wcs.ctype = self.coordinate_system w2.wcs.pc = self.rotation_matrix w2.wcs.cunit = self.spatial_units w2.wcs.dateobs = self.date.isot w2.wcs.aux.rsun_ref = self.rsun_meters.to_value(u.m) # Astropy WCS does not understand the SOHO default of "solar-x" and # "solar-y" ctypes. This overrides the default assignment and # changes it to a ctype that is understood. See Thompson, 2006, A.&A., # 449, 791. if w2.wcs.ctype[0].lower() in ("solar-x", "solar_x"): w2.wcs.ctype[0] = 'HPLN-TAN' if w2.wcs.ctype[1].lower() in ("solar-y", "solar_y"): w2.wcs.ctype[1] = 'HPLT-TAN' # Set observer coordinate information # # Clear all the aux information that was set earlier. This is to avoid # issues with maps that store multiple observer coordinate keywords. # Note that we have to create a new WCS as it's not possible to modify # wcs.wcs.aux in place. header = w2.to_header() for kw in ['crln_obs', 'dsun_obs', 'hgln_obs', 'hglt_obs']: header.pop(kw, None) w2 = astropy.wcs.WCS(header) # Get observer coord, and transform if needed obs_coord = self.observer_coordinate if not isinstance(obs_coord.frame, (HeliographicStonyhurst, HeliographicCarrington)): obs_coord = obs_coord.transform_to(HeliographicStonyhurst(obstime=self.date)) sunpy.coordinates.wcs_utils._set_wcs_aux_obs_coord(w2, obs_coord) # Validate the WCS here. w2.wcs.set() return w2 @property def coordinate_frame(self): """ An `astropy.coordinates.BaseCoordinateFrame` instance created from the coordinate information for this Map, or None if the frame cannot be determined. """ try: return astropy.wcs.utils.wcs_to_celestial_frame(self.wcs) except ValueError as e: warnings.warn(f'Could not determine coordinate frame from map metadata.\n{e}', SunpyUserWarning) return None @property def _coordinate_frame_name(self): if self.coordinate_frame is None: return 'Unknown' return self.coordinate_frame.name def _as_mpl_axes(self): """ Compatibility hook for Matplotlib and WCSAxes. This functionality requires the WCSAxes package to work. The reason we include this here is that it allows users to use WCSAxes without having to explicitly import WCSAxes With this method, one can do:: import matplotlib.pyplot as plt import sunpy.map amap = sunpy.map.Map('filename.fits') fig = plt.figure() ax = plt.subplot(projection=amap) ... and this will generate a plot with the correct WCS coordinates on the axes. See https://wcsaxes.readthedocs.io for more information. """ # This code is reused from Astropy return WCSAxes, {'wcs': self.wcs} # Some numpy extraction @property def dimensions(self): """ The dimensions of the array (x axis first, y axis second). """ return PixelPair(*u.Quantity(np.flipud(self.data.shape), 'pixel')) @property def dtype(self): """ The `numpy.dtype` of the array of the map. """ return self.data.dtype @property @deprecated(since="2.1", message="Use map.data.size instead", alternative="map.data.size") def size(self): """ The number of pixels in the array of the map. """ return u.Quantity(self.data.size, 'pixel') @property def ndim(self): """ The value of `numpy.ndarray.ndim` of the data array of the map. """ return self.data.ndim def std(self, *args, **kwargs): """ Calculate the standard deviation of the data array. """ return self.data.std(*args, **kwargs) def mean(self, *args, **kwargs): """ Calculate the mean of the data array. """ return self.data.mean(*args, **kwargs) def min(self, *args, **kwargs): """ Calculate the minimum value of the data array. """ return self.data.min(*args, **kwargs) def max(self, *args, **kwargs): """ Calculate the maximum value of the data array. """ return self.data.max(*args, **kwargs) @property def unit(self): """ Unit of the map data. This is taken from the 'BUNIT' FITS keyword. If no 'BUNIT' entry is present in the metadata then this returns `None`. If the 'BUNIT' value cannot be parsed into a unit a warning is raised, and `None` returned. """ unit_str = self.meta.get('bunit', None) if unit_str is None: return unit = u.Unit(unit_str, format='fits', parse_strict='silent') if isinstance(unit, u.UnrecognizedUnit): warnings.warn(f'Could not parse unit string "{unit_str}" as a valid FITS unit.\n' f'See {_META_FIX_URL} for how to fix metadata before loading it ' 'with sunpy.map.Map.\n' 'See https://fits.gsfc.nasa.gov/fits_standard.html for' 'the FITS unit standards.', SunpyMetadataWarning) unit = None return unit # #### Keyword attribute and other attribute definitions #### # def _base_name(self): """Abstract the shared bit between name and latex_name""" return "{nickname} {{measurement}} {date}".format( nickname=self.nickname, date=parse_time(self.date).strftime(TIME_FORMAT) ) @property def name(self): """Human-readable description of the Map.""" return self._base_name().format(measurement=self.measurement) @property def latex_name(self): """LaTeX formatted description of the Map.""" if isinstance(self.measurement, u.Quantity): return self._base_name().format(measurement=self.measurement._repr_latex_()) else: return self.name @property def nickname(self): """An abbreviated human-readable description of the map-type; part of the Helioviewer data model.""" return self._nickname if self._nickname else self.detector @nickname.setter def nickname(self, n): self._nickname = n @property def date(self): """ Image observation time. This is taken from the 'DATE-OBS' FITS keyword. """ time = self.meta.get('date-obs', None) if time is None: if self._default_time is None: warnings.warn("Missing metadata for observation time, " "setting observation time to current time. " "Set the 'DATE-OBS' FITS keyword to prevent this warning.", SunpyUserWarning) self._default_time = parse_time('now') time = self._default_time return parse_time(time) @property def detector(self): """ Detector name. This is taken from the 'DETECTOR' FITS keyword. """ return self.meta.get('detector', "") @property def timeunit(self): """ The `~astropy.units.Unit` of the exposure time of this observation. Taken from the "TIMEUNIT" FITS keyword, and defaults to seconds (as per) the FITS standard). """ return u.Unit(self.meta.get('timeunit', 's')) @property def exposure_time(self): """ Exposure time of the image in seconds. This is taken from the 'EXPTIME' FITS keyword. """ return self.meta.get('exptime', 0.0) * self.timeunit @property def instrument(self): """Instrument name.""" return self.meta.get('instrume', "").replace("_", " ") @property def measurement(self): """ Measurement wavelength. This is taken from the 'WAVELNTH' FITS keyword. If the keyword is not present, defaults to 0. """ return u.Quantity(self.meta.get('wavelnth', 0), self.waveunit) @property def waveunit(self): """ The `~astropy.units.Unit` of the wavelength of this observation. This is taken from the 'WAVEUNIT' FITS keyword. """ unit = self.meta.get("waveunit") if unit is None: return u.one return u.Unit(unit) @property def wavelength(self): """ Wavelength of the observation. This is taken from the 'WAVELNTH' FITS keyword. """ return u.Quantity(self.meta.get('wavelnth', 0), self.waveunit) @property def observatory(self): """ Observatory or Telescope name. This is taken from the 'OBSRVTRY' FITS keyword. """ return self.meta.get('obsrvtry', self.meta.get('telescop', "")).replace("_", " ") @property def processing_level(self): """ Returns the FITS processing level if present. This is taken from the 'LVL_NUM' FITS keyword. """ return self.meta.get('lvl_num', None) @property def bottom_left_coord(self): """ The physical coordinate at the center of the bottom left ([0, 0]) pixel. """ return self.pixel_to_world(0*u.pix, 0*u.pix) @property def top_right_coord(self): """ The physical coordinate at the center of the the top right ([-1, -1]) pixel. """ top_right = u.Quantity(self.dimensions) - 1 * u.pix return self.pixel_to_world(*top_right) @property def center(self): """ Return a coordinate object for the center pixel of the array. If the array has an even number of pixels in a given dimension, the coordinate returned lies on the edge between the two central pixels. """ center = (u.Quantity(self.dimensions) - 1 * u.pix) / 2. return self.pixel_to_world(*center) @property def shifted_value(self): """The total shift applied to the reference coordinate by past applications of `~sunpy.map.GenericMap.shift`.""" return self._shift @u.quantity_input def shift(self, axis1: u.deg, axis2: u.deg): """ Returns a map shifted by a specified amount to, for example, correct for a bad map location. These values are applied directly to the `~sunpy.map.GenericMap.reference_coordinate`. To check how much shift has already been applied see `~sunpy.map.GenericMap.shifted_value` Parameters ---------- axis1 : `~astropy.units.Quantity` The shift to apply to the Longitude (solar-x) coordinate. axis2 : `~astropy.units.Quantity` The shift to apply to the Latitude (solar-y) coordinate Returns ------- out : `~sunpy.map.GenericMap` or subclass A new shifted Map. """ new_meta = self.meta.copy() # Update crvals new_meta['crval1'] = ((self.meta['crval1'] * self.spatial_units[0] + axis1).to(self.spatial_units[0])).value new_meta['crval2'] = ((self.meta['crval2'] * self.spatial_units[1] + axis2).to(self.spatial_units[1])).value # Create new map with the modification new_map = self._new_instance(self.data, new_meta, self.plot_settings) new_map._shift = SpatialPair(self.shifted_value[0] + axis1, self.shifted_value[1] + axis2) return new_map @property def rsun_meters(self): """Radius of the sun in meters.""" return u.Quantity(self.meta.get('rsun_ref', constants.radius), 'meter') @property def rsun_obs(self): """ Angular radius of the Sun. Notes ----- This value is taken the ``'rsun_obs'``, ``'solar_r'``, or ``radius`` FITS keywords. If none of these keys are present the photospheric limb as seen from the observer coordinate is returned. """ rsun_arcseconds = self.meta.get('rsun_obs', self.meta.get('solar_r', self.meta.get('radius', None))) if rsun_arcseconds is None: warnings.warn("Missing metadata for solar angular radius: assuming photospheric limb " "as seen from observer coordinate.", SunpyUserWarning) dsun = self.dsun rsun = sun._angular_radius(constants.radius, dsun) else: rsun = rsun_arcseconds * u.arcsec return rsun @property def coordinate_system(self): """ Coordinate system used for x and y axes (ctype1/2). If not present, defaults to (HPLN-TAN, HPLT-TAN), and emits a warning. """ ctype1 = self.meta.get('ctype1', None) if ctype1 is None: warnings.warn("Missing CTYPE1 from metadata, assuming CTYPE1 is HPLN-TAN", SunpyUserWarning) ctype1 = 'HPLN-TAN' ctype2 = self.meta.get('ctype2', None) if ctype2 is None: warnings.warn("Missing CTYPE2 from metadata, assuming CTYPE2 is HPLT-TAN", SunpyUserWarning) ctype2 = 'HPLT-TAN' return SpatialPair(ctype1, ctype2) @property def _supported_observer_coordinates(self): """ A list of supported coordinate systems. This is a list so it can easily maintain a strict order. The list of two element tuples, the first item in the tuple is the keys that need to be in the header to use this coordinate system and the second is the kwargs to SkyCoord. """ return [(('hgln_obs', 'hglt_obs', 'dsun_obs'), {'lon': self.meta.get('hgln_obs'), 'lat': self.meta.get('hglt_obs'), 'radius': self.meta.get('dsun_obs'), 'unit': (u.deg, u.deg, u.m), 'frame': "heliographic_stonyhurst"}), (('crln_obs', 'crlt_obs', 'dsun_obs'), {'lon': self.meta.get('crln_obs'), 'lat': self.meta.get('crlt_obs'), 'radius': self.meta.get('dsun_obs'), 'unit': (u.deg, u.deg, u.m), 'frame': "heliographic_carrington"}), ] def _remove_existing_observer_location(self): """ Remove all keys that this map might use for observer location. """ all_keys = expand_list([e[0] for e in self._supported_observer_coordinates]) for key in all_keys: self.meta.pop(key) @property def observer_coordinate(self): """ The Heliographic Stonyhurst Coordinate of the observer. """ missing_meta = {} for keys, kwargs in self._supported_observer_coordinates: meta_list = [k in self.meta for k in keys] if all(meta_list): sc = SkyCoord(obstime=self.date, **kwargs) # If the observer location is supplied in Carrington coordinates, # the coordinate's `observer` attribute should be set to "self" if isinstance(sc.frame, HeliographicCarrington): sc.frame._observer = "self" return sc.heliographic_stonyhurst elif any(meta_list) and not set(keys).isdisjoint(self.meta.keys()): if not isinstance(kwargs['frame'], str): kwargs['frame'] = kwargs['frame'].name missing_meta[kwargs['frame']] = set(keys).difference(self.meta.keys()) warning_message = "".join( [f"For frame '{frame}' the following metadata is missing: {','.join(keys)}\n" for frame, keys in missing_meta.items()]) warning_message = "Missing metadata for observer: assuming Earth-based observer.\n" + warning_message warnings.warn(warning_message, SunpyMetadataWarning, stacklevel=3) return get_earth(self.date) @property def heliographic_latitude(self): """Observer heliographic latitude.""" return self.observer_coordinate.lat @property def heliographic_longitude(self): """Observer heliographic longitude.""" return self.observer_coordinate.lon @property def carrington_latitude(self): """Observer Carrington latitude.""" hgc_frame = HeliographicCarrington(observer=self.observer_coordinate, obstime=self.date) return self.observer_coordinate.transform_to(hgc_frame).lat @property def carrington_longitude(self): """Observer Carrington longitude.""" hgc_frame = HeliographicCarrington(observer=self.observer_coordinate, obstime=self.date) return self.observer_coordinate.transform_to(hgc_frame).lon @property def dsun(self): """Observer distance from the center of the Sun.""" return self.observer_coordinate.radius.to('m') @property def _reference_longitude(self): """ FITS-WCS compatible longitude. Used in self.wcs and self.reference_coordinate. """ return self.meta.get('crval1', 0.) * self.spatial_units[0] @property def _reference_latitude(self): return self.meta.get('crval2', 0.) * self.spatial_units[1] @property def reference_coordinate(self): """Reference point WCS axes in data units (i.e. crval1, crval2). This value includes a shift if one is set.""" return SkyCoord(self._reference_longitude, self._reference_latitude, frame=self.coordinate_frame) @property def reference_pixel(self): """ Pixel of reference coordinate. The pixel returned uses zero-based indexing, so will be 1 pixel less than the FITS CRPIX values. """ return PixelPair((self.meta.get('crpix1', (self.meta.get('naxis1') + 1) / 2.) - 1) * u.pixel, (self.meta.get('crpix2', (self.meta.get('naxis2') + 1) / 2.) - 1) * u.pixel) @property def scale(self): """ Image scale along the x and y axes in units/pixel (i.e. cdelt1, cdelt2). """ # TODO: Fix this if only CDi_j matrix is provided return SpatialPair(self.meta.get('cdelt1', 1.) * self.spatial_units[0] / u.pixel, self.meta.get('cdelt2', 1.) * self.spatial_units[1] / u.pixel) @property def spatial_units(self): """ Image coordinate units along the x and y axes (i.e. cunit1, cunit2). """ return SpatialPair(u.Unit(self.meta.get('cunit1')), u.Unit(self.meta.get('cunit2'))) @property def rotation_matrix(self): r""" Matrix describing the rotation required to align solar North with the top of the image. The order or precendence of FITS keywords which this is taken from is: - PC\*_\* - CD\*_\* - CROTA\* """ if 'PC1_1' in self.meta: return np.array([[self.meta['PC1_1'], self.meta['PC1_2']], [self.meta['PC2_1'], self.meta['PC2_2']]]) elif 'CD1_1' in self.meta: cd = np.array([[self.meta['CD1_1'], self.meta['CD1_2']], [self.meta['CD2_1'], self.meta['CD2_2']]]) cdelt = u.Quantity(self.scale).value return cd / cdelt else: return self._rotation_matrix_from_crota() def _rotation_matrix_from_crota(self): """ This method converts the deprecated CROTA FITS kwargs to the new PC rotation matrix. This method can be overriden if an instruments header does not use this conversion. """ lam = self.scale[0] / self.scale[1] p = np.deg2rad(self.meta.get('CROTA2', 0)) return np.array([[np.cos(p), -1 * lam * np.sin(p)], [1/lam * np.sin(p), np.cos(p)]]) @property def fits_header(self): """ A `~astropy.io.fits.Header` representation of the ``meta`` attribute. """ return sunpy.io.fits.header_to_fits(self.meta) # #### Miscellaneous #### # def _fix_date(self): # Check commonly used but non-standard FITS keyword for observation # time and correct the keyword if we can. Keep updating old one for # backwards compatibility. if is_time(self.meta.get('date_obs', None)): self.meta['date-obs'] = self.meta['date_obs'] def _fix_naxis(self): # If naxis is not specified, get it from the array shape if 'naxis1' not in self.meta: self.meta['naxis1'] = self.data.shape[1] if 'naxis2' not in self.meta: self.meta['naxis2'] = self.data.shape[0] if 'naxis' not in self.meta: self.meta['naxis'] = self.ndim def _fix_bitpix(self): # Bit-depth # # 8 Character or unsigned binary integer # 16 16-bit twos-complement binary integer # 32 32-bit twos-complement binary integer # -32 IEEE single precision floating point # -64 IEEE double precision floating point # if 'bitpix' not in self.meta: float_fac = -1 if self.dtype.kind == "f" else 1 self.meta['bitpix'] = float_fac * 8 * self.dtype.itemsize def _get_cmap_name(self): """Build the default color map name.""" cmap_string = (self.observatory + self.detector + str(int(self.wavelength.to('angstrom').value))) return cmap_string.lower() def _validate_meta(self): """ Validates the meta-information associated with a Map. This method includes very basic validation checks which apply to all of the kinds of files that SunPy can read. Datasource-specific validation should be handled in the relevant file in the sunpy.map.sources package. Allows for default unit assignment for: CUNIT1, CUNIT2, WAVEUNIT """ msg = ('Image coordinate units for axis {} not present in metadata.') err_message = [] for i in [1, 2]: if self.meta.get(f'cunit{i}') is None: err_message.append(msg.format(i, i)) if err_message: err_message.append( f'See {_META_FIX_URL} for instructions on how to add missing metadata.') raise MapMetaValidationError('\n'.join(err_message)) for meta_property in ('waveunit', ): if (self.meta.get(meta_property) and u.Unit(self.meta.get(meta_property), parse_strict='silent').physical_type == 'unknown'): warnings.warn(f"Unknown value for {meta_property.upper()}.", SunpyUserWarning) if (self.coordinate_system[0].startswith(('SOLX', 'SOLY')) or self.coordinate_system[1].startswith(('SOLX', 'SOLY'))): warnings.warn("SunPy Map does not support three dimensional data " "and therefore cannot represent heliocentric coordinates. Proceed at your own risk.", SunpyUserWarning) # #### Data conversion routines #### # @staticmethod def _check_origin(origin): """ Check origin is valid, and raise a deprecation warning if it's not None. """ if origin is not None: warnings.warn('The origin argument is deprecated. If using origin=1, ' 'manually subtract 1 from your pixels do not pass a value for origin.', SunpyDeprecationWarning) if origin not in [None, 0, 1]: raise ValueError('origin must be 0 or 1.') def world_to_pixel(self, coordinate, origin=None): """ Convert a world (data) coordinate to a pixel coordinate. Parameters ---------- coordinate : `~astropy.coordinates.SkyCoord` or `~astropy.coordinates.BaseCoordinateFrame` The coordinate object to convert to pixel coordinates. origin : int Deprecated. Origin of the top-left corner. i.e. count from 0 or 1. Normally, origin should be 0 when passing numpy indices, or 1 if passing values from FITS header or map attributes. Returns ------- x : `~astropy.units.Quantity` Pixel coordinate on the CTYPE1 axis. y : `~astropy.units.Quantity` Pixel coordinate on the CTYPE2 axis. """ self._check_origin(origin) x, y = self.wcs.world_to_pixel(coordinate) if origin == 1: x += 1 y += 1 return PixelPair(x * u.pixel, y * u.pixel) @u.quantity_input def pixel_to_world(self, x: u.pixel, y: u.pixel, origin=None): """ Convert a pixel coordinate to a data (world) coordinate. Parameters ---------- x : `~astropy.units.Quantity` Pixel coordinate of the CTYPE1 axis. (Normally solar-x). y : `~astropy.units.Quantity` Pixel coordinate of the CTYPE2 axis. (Normally solar-y). origin : int Deprecated. Origin of the top-left corner. i.e. count from 0 or 1. Normally, origin should be 0 when passing numpy indices, or 1 if passing values from FITS header or map attributes. Returns ------- coord : `astropy.coordinates.SkyCoord` A coordinate object representing the output coordinate. """ self._check_origin(origin) if origin == 1: x = x - 1 * u.pixel y = y - 1 * u.pixel return self.wcs.pixel_to_world(x, y) # #### I/O routines #### # def save(self, filepath, filetype='auto', **kwargs): """Saves the SunPy Map object to a file. Currently SunPy can only save files in the FITS format. In the future support will be added for saving to other formats. Parameters ---------- filepath : str Location to save file to. filetype : str 'auto' or any supported file extension. hdu_type: None, `~astropy.io.fits.CompImageHDU` `None` will return a normal FITS file. `~astropy.io.fits.CompImageHDU` will rice compress the FITS file. kwargs : Any additional keyword arguments are passed to `~sunpy.io.write_file`. """ io.write_file(filepath, self.data, self.meta, filetype=filetype, **kwargs) # #### Image processing routines #### # @u.quantity_input def resample(self, dimensions: u.pixel, method='linear'): """ Resample to new dimension sizes. Uses the same parameters and creates the same co-ordinate lookup points as IDL''s congrid routine, which apparently originally came from a VAX/VMS routine of the same name. Parameters ---------- dimensions : `~astropy.units.Quantity` Output pixel dimensions. The first argument corresponds to the 'x' axis and the second argument corresponds to the 'y' axis. method : str Method to use for resampling interpolation. * ``'neighbor'`` - Take closest value from original data. * ``'nearest'`` and ``'linear'`` - Use n x 1-D interpolations using `scipy.interpolate.interp1d`. * ``'spline'`` - Uses piecewise polynomials (splines) for mapping the input array to new coordinates by interpolation using `scipy.ndimage.map_coordinates`. Returns ------- out : `~sunpy.map.GenericMap` or subclass Resampled map References ---------- `Rebinning <https://scipy-cookbook.readthedocs.io/items/Rebinning.html>`_ """ # Note: because the underlying ndarray is transposed in sense when # compared to the Map, the ndarray is transposed, resampled, then # transposed back # Note: "center" defaults to True in this function because data # coordinates in a Map are at pixel centers # Make a copy of the original data and perform resample new_data = sunpy_image_resample(self.data.copy().T, dimensions, method, center=True) new_data = new_data.T scale_factor_x = float(self.dimensions[0] / dimensions[0]) scale_factor_y = float(self.dimensions[1] / dimensions[1]) # Update image scale and number of pixels new_meta = self.meta.copy() # Update metadata new_meta['cdelt1'] *= scale_factor_x new_meta['cdelt2'] *= scale_factor_y if 'CD1_1' in new_meta: new_meta['CD1_1'] *= scale_factor_x new_meta['CD2_1'] *= scale_factor_x new_meta['CD1_2'] *= scale_factor_y new_meta['CD2_2'] *= scale_factor_y new_meta['crpix1'] = (dimensions[0].value + 1) / 2. new_meta['crpix2'] = (dimensions[1].value + 1) / 2. lon, lat = self._get_lon_lat(self.center.frame) new_meta['crval1'] = lon.value new_meta['crval2'] = lat.value new_meta['naxis1'] = new_data.shape[1] new_meta['naxis2'] = new_data.shape[0] # Create new map instance new_map = self._new_instance(new_data, new_meta, self.plot_settings) return new_map @u.quantity_input def rotate(self, angle: u.deg = None, rmatrix=None, order=4, scale=1.0, recenter=False, missing=0.0, use_scipy=False): """ Returns a new rotated and rescaled map. Specify either a rotation angle or a rotation matrix, but not both. If neither an angle or a rotation matrix are specified, the map will be rotated by the rotation angle in the metadata. The map will be rotated around the reference coordinate defined in the meta data. This method also updates the ``rotation_matrix`` attribute and any appropriate header data so that they correctly describe the new map. Parameters ---------- angle : `~astropy.units.Quantity` The angle (degrees) to rotate counterclockwise. rmatrix : array-like 2x2 linear transformation rotation matrix. order : int Interpolation order to be used. Must be in the range 0-5. When using scikit-image this parameter is passed into :func:`skimage.transform.warp` (e.g., 4 corresponds to bi-quartic interpolation). When using scipy it is passed into :func:`scipy.ndimage.affine_transform` where it controls the order of the spline. Faster performance may be obtained at the cost of accuracy by using lower values. Default: 4 scale : float A scale factor for the image, default is no scaling recenter : bool If True, position the axis of rotation at the center of the new map Default: False missing : float The numerical value to fill any missing points after rotation. Default: 0.0 use_scipy : bool If True, forces the rotation to use :func:`scipy.ndimage.affine_transform`, otherwise it uses the :func:`skimage.transform.warp`. Default: False, unless scikit-image can't be imported Returns ------- out : `~sunpy.map.GenericMap` or subclass A new Map instance containing the rotated and rescaled data of the original map. See Also -------- sunpy.image.transform.affine_transform : The routine this method calls for the rotation. Notes ----- This function will remove old CROTA keywords from the header. This function will also convert a CDi_j matrix to a PCi_j matrix. See :func:`sunpy.image.transform.affine_transform` for details on the transformations, situations when the underlying data is modified prior to rotation, and differences from IDL's rot(). """ # Put the import here to reduce sunpy.map import time from sunpy.image.transform import affine_transform if angle is not None and rmatrix is not None: raise ValueError("You cannot specify both an angle and a rotation matrix.") elif angle is None and rmatrix is None: rmatrix = self.rotation_matrix if order not in range(6): raise ValueError("Order must be between 0 and 5.") # The FITS-WCS transform is by definition defined around the # reference coordinate in the header. lon, lat = self._get_lon_lat(self.reference_coordinate.frame) rotation_center = u.Quantity([lon, lat]) # Copy meta data new_meta = self.meta.copy() if angle is not None: # Calculate the parameters for the affine_transform c = np.cos(np.deg2rad(angle)) s = np.sin(np.deg2rad(angle)) rmatrix = np.array([[c, -s], [s, c]]) # Calculate the shape in pixels to contain all of the image data extent = np.max(np.abs(np.vstack((self.data.shape @ rmatrix, self.data.shape @ rmatrix.T))), axis=0) # Calculate the needed padding or unpadding diff = np.asarray(np.ceil((extent - self.data.shape) / 2), dtype=int).ravel() # Pad the image array pad_x = int(np.max((diff[1], 0))) pad_y = int(np.max((diff[0], 0))) new_data = np.pad(self.data, ((pad_y, pad_y), (pad_x, pad_x)), mode='constant', constant_values=(missing, missing)) new_meta['crpix1'] += pad_x new_meta['crpix2'] += pad_y # All of the following pixel calculations use a pixel origin of 0 pixel_array_center = (np.flipud(new_data.shape) - 1) / 2.0 # Create a temporary map so we can use it for the data to pixel calculation. temp_map = self._new_instance(new_data, new_meta, self.plot_settings) # Convert the axis of rotation from data coordinates to pixel coordinates pixel_rotation_center = u.Quantity(temp_map.world_to_pixel(self.reference_coordinate)).value del temp_map if recenter: pixel_center = pixel_rotation_center else: pixel_center = pixel_array_center # Apply the rotation to the image data new_data = affine_transform(new_data.T, np.asarray(rmatrix), order=order, scale=scale, image_center=np.flipud(pixel_center), recenter=recenter, missing=missing, use_scipy=use_scipy).T if recenter: new_reference_pixel = pixel_array_center else: # Calculate new pixel coordinates for the rotation center new_reference_pixel = pixel_center + np.dot(rmatrix, pixel_rotation_center - pixel_center) new_reference_pixel = np.array(new_reference_pixel).ravel() # Define the new reference_pixel new_meta['crval1'] = rotation_center[0].value new_meta['crval2'] = rotation_center[1].value new_meta['crpix1'] = new_reference_pixel[0] + 1 # FITS pixel origin is 1 new_meta['crpix2'] = new_reference_pixel[1] + 1 # FITS pixel origin is 1 # Unpad the array if necessary unpad_x = -np.min((diff[1], 0)) if unpad_x > 0: new_data = new_data[:, unpad_x:-unpad_x] new_meta['crpix1'] -= unpad_x unpad_y = -np.min((diff[0], 0)) if unpad_y > 0: new_data = new_data[unpad_y:-unpad_y, :] new_meta['crpix2'] -= unpad_y # Calculate the new rotation matrix to store in the header by # "subtracting" the rotation matrix used in the rotate from the old one # That being calculate the dot product of the old header data with the # inverse of the rotation matrix. pc_C = np.dot(self.rotation_matrix, np.linalg.inv(rmatrix)) new_meta['PC1_1'] = pc_C[0, 0] new_meta['PC1_2'] = pc_C[0, 1] new_meta['PC2_1'] = pc_C[1, 0] new_meta['PC2_2'] = pc_C[1, 1] # Update pixel size if image has been scaled. if scale != 1.0: new_meta['cdelt1'] = (self.scale[0] / scale).value new_meta['cdelt2'] = (self.scale[1] / scale).value # Remove old CROTA kwargs because we have saved a new PCi_j matrix. new_meta.pop('CROTA1', None) new_meta.pop('CROTA2', None) # Remove CDi_j header new_meta.pop('CD1_1', None) new_meta.pop('CD1_2', None) new_meta.pop('CD2_1', None) new_meta.pop('CD2_2', None) # Create new map with the modification new_map = self._new_instance(new_data, new_meta, self.plot_settings) return new_map @u.quantity_input def submap(self, bottom_left, *, top_right=None, width: (u.deg, u.pix) = None, height: (u.deg, u.pix) = None): """ Returns a submap defined by a rectangle. Any pixels which have at least part of their area inside the rectangle are returned. If the rectangle is defined in world coordinates, the smallest array which contains all four corners of the rectangle as defined in world coordinates is returned. Parameters ---------- bottom_left : `astropy.units.Quantity` or `~astropy.coordinates.SkyCoord` The bottom-left coordinate of the rectangle. If a `~astropy.coordinates.SkyCoord` it can have shape ``(2,)`` and simultaneously define ``top_right``. If specifying pixel coordinates it must be given as an `~astropy.units.Quantity` object with units of `~astropy.units.si.pix`. top_right : `astropy.units.Quantity` or `~astropy.coordinates.SkyCoord`, optional The top-right coordinate of the rectangle. If ``top_right`` is specified ``width`` and ``height`` must be omitted. width : `astropy.units.Quantity`, optional The width of the rectangle. Required if ``top_right`` is omitted. height : `astropy.units.Quantity` The height of the rectangle. Required if ``top_right`` is omitted. Returns ------- out : `~sunpy.map.GenericMap` or subclass A new map instance is returned representing to specified sub-region. Notes ----- When specifying pixel coordinates, they are specified in Cartesian order not in numpy order. So, for example, the ``bottom_left=`` argument should be ``[left, bottom]``. Examples -------- >>> import astropy.units as u >>> from astropy.coordinates import SkyCoord >>> import sunpy.map >>> import sunpy.data.sample # doctest: +REMOTE_DATA >>> aia = sunpy.map.Map(sunpy.data.sample.AIA_171_IMAGE) # doctest: +REMOTE_DATA >>> bl = SkyCoord(-300*u.arcsec, -300*u.arcsec, frame=aia.coordinate_frame) # doctest: +REMOTE_DATA >>> tr = SkyCoord(500*u.arcsec, 500*u.arcsec, frame=aia.coordinate_frame) # doctest: +REMOTE_DATA >>> aia.submap(bl, top_right=tr) # doctest: +REMOTE_DATA <sunpy.map.sources.sdo.AIAMap object at ...> SunPy Map --------- Observatory: SDO Instrument: AIA 3 Detector: AIA Measurement: 171.0 Angstrom Wavelength: 171.0 Angstrom Observation Date: 2011-06-07 06:33:02 Exposure Time: 0.234256 s Dimension: [335. 335.] pix Coordinate System: helioprojective Scale: [2.402792 2.402792] arcsec / pix Reference Pixel: [126.5 125.5] pix Reference Coord: [3.22309951 1.38578135] arcsec ... >>> aia.submap([0,0]*u.pixel, top_right=[5,5]*u.pixel) # doctest: +REMOTE_DATA <sunpy.map.sources.sdo.AIAMap object at ...> SunPy Map --------- Observatory: SDO Instrument: AIA 3 Detector: AIA Measurement: 171.0 Angstrom Wavelength: 171.0 Angstrom Observation Date: 2011-06-07 06:33:02 Exposure Time: 0.234256 s Dimension: [6. 6.] pix Coordinate System: helioprojective Scale: [2.402792 2.402792] arcsec / pix Reference Pixel: [511.5 511.5] pix Reference Coord: [3.22309951 1.38578135] arcsec ... >>> width = 10 * u.arcsec >>> height = 10 * u.arcsec >>> aia.submap(bl, width=width, height=height) # doctest: +REMOTE_DATA <sunpy.map.sources.sdo.AIAMap object at ...> SunPy Map --------- Observatory: SDO Instrument: AIA 3 Detector: AIA Measurement: 171.0 Angstrom Wavelength: 171.0 Angstrom Observation Date: 2011-06-07 06:33:02 Exposure Time: 0.234256 s Dimension: [5. 5.] pix Coordinate System: helioprojective Scale: [2.402792 2.402792] arcsec / pix Reference Pixel: [125.5 125.5] pix Reference Coord: [3.22309951 1.38578135] arcsec ... >>> bottom_left_vector = SkyCoord([0, 10] * u.deg, [0, 10] * u.deg, frame='heliographic_stonyhurst') >>> aia.submap(bottom_left_vector) # doctest: +REMOTE_DATA <sunpy.map.sources.sdo.AIAMap object at ...> SunPy Map --------- Observatory: SDO Instrument: AIA 3 Detector: AIA Measurement: 171.0 Angstrom Wavelength: 171.0 Angstrom Observation Date: 2011-06-07 06:33:02 Exposure Time: 0.234256 s Dimension: [70. 69.] pix Coordinate System: helioprojective Scale: [2.402792 2.402792] arcsec / pix Reference Pixel: [1.5 0.5] pix Reference Coord: [3.22309951 1.38578135] arcsec ... """ # Check that we have been given a valid combination of inputs # [False, False, False] is valid if bottom_left contains the two corner coords if ([arg is not None for arg in (top_right, width, height)] not in [[True, False, False], [False, False, False], [False, True, True]]): raise ValueError("Either top_right alone or both width and height must be specified.") # parse input arguments pixel_corners = u.Quantity(self._parse_submap_input( bottom_left, top_right, width, height)).T # The pixel corners result is in Cartesian order, so the first index is # columns and the second is rows. bottom = np.min(pixel_corners[1]).to_value(u.pix) top = np.max(pixel_corners[1]).to_value(u.pix) left = np.min(pixel_corners[0]).to_value(u.pix) right = np.max(pixel_corners[0]).to_value(u.pix) # Round the lower left pixel to the nearest integer # We want 0.5 to be rounded up to 1, so use floor(x + 0.5) bottom = np.floor(bottom + 0.5) left = np.floor(left + 0.5) # Round the top right pixel to the nearest integer, then add 1 for array indexing # We want e.g. 2.5 to be rounded down to 2, so use ceil(x - 0.5) top = np.ceil(top - 0.5) + 1 right = np.ceil(right - 0.5) + 1 # Clip pixel values to max of array, prevents negative # indexing bottom = int(np.clip(bottom, 0, self.data.shape[0])) top = int(np.clip(top, 0, self.data.shape[0])) left = int(np.clip(left, 0, self.data.shape[1])) right = int(np.clip(right, 0, self.data.shape[1])) arr_slice = np.s_[bottom:top, left:right] # Get ndarray representation of submap new_data = self.data[arr_slice].copy() # Make a copy of the header with updated centering information new_meta = self.meta.copy() # Add one to go from zero-based to one-based indexing new_meta['crpix1'] = self.reference_pixel.x.to_value(u.pix) + 1 - left new_meta['crpix2'] = self.reference_pixel.y.to_value(u.pix) + 1 - bottom new_meta['naxis1'] = new_data.shape[1] new_meta['naxis2'] = new_data.shape[0] # Create new map instance if self.mask is not None: new_mask = self.mask[arr_slice].copy() # Create new map with the modification new_map = self._new_instance(new_data, new_meta, self.plot_settings, mask=new_mask) return new_map # Create new map with the modification new_map = self._new_instance(new_data, new_meta, self.plot_settings) return new_map @seconddispatch def _parse_submap_input(self, bottom_left, top_right, width, height): """ Should take any valid input to submap() and return bottom_left and top_right in pixel coordinates. """ @_parse_submap_input.register(u.Quantity) def _parse_submap_quantity_input(self, bottom_left, top_right, width, height): if top_right is None and width is None: raise ValueError('Either top_right alone or both width and height must be specified ' 'when bottom_left is a Quantity') if bottom_left.shape != (2, ): raise ValueError('bottom_left must have shape (2, ) when specified as a Quantity') if top_right is not None: if top_right.shape != (2, ): raise ValueError('top_right must have shape (2, ) when specified as a Quantity') if not top_right.unit.is_equivalent(u.pix): raise TypeError("When bottom_left is a Quantity, top_right " "must be a Quantity in units of pixels.") # Have bottom_left and top_right in pixels already, so no need to do # anything else else: if not (width.unit.is_equivalent(u.pix) and height.unit.is_equivalent(u.pix)): raise TypeError("When bottom_left is a Quantity, width and height " "must be a Quantity in units of pixels.") # Add width and height to get top_right top_right = u.Quantity([bottom_left[0] + width, bottom_left[1] + height]) top_left = u.Quantity([top_right[0], bottom_left[1]]) bottom_right = u.Quantity([bottom_left[0], top_right[1]]) return bottom_left, top_left, top_right, bottom_right @_parse_submap_input.register(SkyCoord) def _parse_submap_coord_input(self, bottom_left, top_right, width, height): # Use helper function to get top_right as a SkyCoord bottom_left, top_right = get_rectangle_coordinates(bottom_left, top_right=top_right, width=width, height=height) frame = bottom_left.frame left_lon, bottom_lat = self._get_lon_lat(bottom_left) right_lon, top_lat = self._get_lon_lat(top_right) corners = SkyCoord([left_lon, left_lon, right_lon, right_lon], [bottom_lat, top_lat, top_lat, bottom_lat], frame=frame) return tuple(u.Quantity(self.wcs.world_to_pixel(corners), u.pix).T) @u.quantity_input def superpixel(self, dimensions: u.pixel, offset: u.pixel = (0, 0)*u.pixel, func=np.sum): """Returns a new map consisting of superpixels formed by applying 'func' to the original map data. Parameters ---------- dimensions : tuple One superpixel in the new map is equal to (dimension[0], dimension[1]) pixels of the original map. Note: the first argument corresponds to the 'x' axis and the second argument corresponds to the 'y' axis. offset : tuple Offset from (0,0) in original map pixels used to calculate where the data used to make the resulting superpixel map starts. func : Function applied to the original data. The function 'func' must take a numpy array as its first argument, and support the axis keyword with the meaning of a numpy axis keyword (see the description of `~numpy.sum` for an example.) The default value of 'func' is `~numpy.sum`; using this causes superpixel to sum over (dimension[0], dimension[1]) pixels of the original map. Returns ------- out : `~sunpy.map.GenericMap` or subclass A new Map which has superpixels of the required size. References ---------- | `Summarizing blocks of an array using a moving window <https://mail.scipy.org/pipermail/numpy-discussion/2010-July/051760.html>`_ """ # Note: because the underlying ndarray is transposed in sense when # compared to the Map, the ndarray is transposed, resampled, then # transposed back. # Note: "center" defaults to True in this function because data # coordinates in a Map are at pixel centers. if (offset.value[0] < 0) or (offset.value[1] < 0): raise ValueError("Offset is strictly non-negative.") # Make a copy of the original data, perform reshaping, and apply the # function. if self.mask is not None: reshaped = reshape_image_to_4d_superpixel(np.ma.array(self.data.copy(), mask=self.mask), [dimensions.value[1], dimensions.value[0]], [offset.value[1], offset.value[0]]) else: reshaped = reshape_image_to_4d_superpixel(self.data.copy(), [dimensions.value[1], dimensions.value[0]], [offset.value[1], offset.value[0]]) new_array = func(func(reshaped, axis=3), axis=1) # Update image scale and number of pixels # create copy of new meta data new_meta = self.meta.copy() new_nx = new_array.shape[1] new_ny = new_array.shape[0] # Update metadata new_meta['cdelt1'] = (dimensions[0] * self.scale[0]).value new_meta['cdelt2'] = (dimensions[1] * self.scale[1]).value if 'CD1_1' in new_meta: new_meta['CD1_1'] *= dimensions[0].value new_meta['CD2_1'] *= dimensions[0].value new_meta['CD1_2'] *= dimensions[1].value new_meta['CD2_2'] *= dimensions[1].value new_meta['crpix1'] = (new_nx + 1) / 2. new_meta['crpix2'] = (new_ny + 1) / 2. lon, lat = self._get_lon_lat(self.center.frame) new_meta['crval1'] = lon.to(self.spatial_units[0]).value + 0.5 * \ (offset[0]*self.scale[0]).to(self.spatial_units[0]).value new_meta['crval2'] = lat.to(self.spatial_units[1]).value + 0.5 * \ (offset[1]*self.scale[1]).to(self.spatial_units[1]).value # Create new map instance if self.mask is not None: new_data = np.ma.getdata(new_array) new_mask = np.ma.getmask(new_array) else: new_data = new_array new_mask = None # Create new map with the modified data new_map = self._new_instance(new_data, new_meta, self.plot_settings, mask=new_mask) return new_map # #### Visualization #### # @property def cmap(self): """ Return the `matplotlib.colors.Colormap` instance this map uses. """ cmap = self.plot_settings['cmap'] if isinstance(cmap, str): cmap = plt.get_cmap(cmap) # Set the colormap to be this specific instance so we are not # returning a copy self.plot_settings['cmap'] = cmap return cmap @u.quantity_input def draw_grid(self, axes=None, grid_spacing: u.deg = 15*u.deg, annotate=True, **kwargs): """ Draws a coordinate overlay on the plot in the Heliographic Stonyhurst coordinate system. To overlay other coordinate systems see the `WCSAxes Documentation <https://docs.astropy.org/en/stable/visualization/wcsaxes/overlaying_coordinate_systems.html>`_ Parameters ---------- axes: `~matplotlib.axes` or `None` Axes to plot limb on, or `None` to use current axes. grid_spacing: `~astropy.units.Quantity` Spacing for longitude and latitude grid, if length two it specifies (lon, lat) spacing. annotate : `bool` Passing `False` disables the axes labels and the ticks on the top and right axes. Returns ------- overlay: `~astropy.visualization.wcsaxes.CoordinatesMap` The wcsaxes coordinate overlay instance. Notes ----- Keyword arguments are passed onto the `sunpy.visualization.wcsaxes_compat.wcsaxes_heliographic_overlay` function. """ if not axes: axes = wcsaxes_compat.gca_wcs(self.wcs) if not wcsaxes_compat.is_wcsaxes(axes): raise TypeError("Overlay grids can only be plotted on WCSAxes plots.") return wcsaxes_compat.wcsaxes_heliographic_overlay(axes, grid_spacing=grid_spacing, annotate=annotate, **kwargs) def draw_limb(self, axes=None, **kwargs): """ Draws a circle representing the solar limb Parameters ---------- axes: `~matplotlib.axes` or None Axes to plot limb on or None to use current axes. Returns ------- circ: list A list containing the `~matplotlib.patches.Circle` object that has been added to the axes. Notes ----- Keyword arguments are passed onto `matplotlib.patches.Circle`. """ # Put import here to reduce sunpy.map import time from matplotlib import patches if not axes: axes = wcsaxes_compat.gca_wcs(self.wcs) transform = wcsaxes_compat.get_world_transform(axes) if wcsaxes_compat.is_wcsaxes(axes): radius = self.rsun_obs.to(u.deg).value else: radius = self.rsun_obs.value c_kw = {'radius': radius, 'fill': False, 'color': 'white', 'zorder': 100, 'transform': transform } c_kw.update(kwargs) circ = patches.Circle([0, 0], **c_kw) axes.add_artist(circ) return [circ] @u.quantity_input def draw_rectangle(self, bottom_left, *, width: u.deg = None, height: u.deg = None, axes=None, top_right=None, **kwargs): """ Draw a rectangle defined in world coordinates on the plot. This draws a rectangle that has corners at ``(bottom_left, top_right)``, and has sides parallel to coordinate axes of the map. If ``width`` and ``height`` are specified, they are respectively added to the longitude and latitude of the ``bottom_left`` coordinate to calculate a ``top_right`` coordinate. Parameters ---------- bottom_left : `~astropy.coordinates.SkyCoord` The bottom-left coordinate of the rectangle. It can have shape ``(2,)`` to simultaneously define ``top_right``. top_right : `~astropy.coordinates.SkyCoord` The top-right coordinate of the rectangle. width : `astropy.units.Quantity`, optional The width of the rectangle. Required if ``top_right`` is omitted. height : `astropy.units.Quantity` The height of the rectangle. Required if ``top_right`` is omitted. axes : `matplotlib.axes.Axes` The axes on which to plot the rectangle, defaults to the current axes. Returns ------- rect : `list` A list containing the `~matplotlib.patches.Rectangle` object, after it has been added to ``axes``. Notes ----- Extra keyword arguments to this function are passed through to the `~matplotlib.patches.Rectangle` instance. """ bottom_left, top_right = get_rectangle_coordinates(bottom_left, top_right=top_right, width=width, height=height) bottom_left = bottom_left.transform_to(self.coordinate_frame) top_right = top_right.transform_to(self.coordinate_frame) width = Longitude(top_right.spherical.lon - bottom_left.spherical.lon) height = top_right.spherical.lat - bottom_left.spherical.lat if not axes: axes = plt.gca() if wcsaxes_compat.is_wcsaxes(axes): axes_unit = u.deg else: axes_unit = self.spatial_units[0] bottom_left = u.Quantity(self._get_lon_lat(bottom_left), unit=axes_unit).value width = width.to(axes_unit).value height = height.to(axes_unit).value kwergs = {'transform': wcsaxes_compat.get_world_transform(axes), 'edgecolor': 'white', 'fill': False} kwergs.update(kwargs) rect = plt.Rectangle(bottom_left, width, height, **kwergs) axes.add_artist(rect) return [rect] @u.quantity_input def draw_contours(self, levels: u.percent, axes=None, **contour_args): """ Draw contours of the data. Parameters ---------- levels : `~astropy.units.Quantity` A list of numbers indicating the contours to draw. These are given as a percentage of the maximum value of the map data. axes : `matplotlib.axes.Axes` The axes on which to plot the contours. Defaults to the current axes. Returns ------- cs : `list` The `~matplotlib.contour.QuadContourSet` object, after it has been added to ``axes``. Notes ----- Extra keyword arguments to this function are passed through to the `~matplotlib.pyplot.contour` function. """ if not axes: axes = wcsaxes_compat.gca_wcs(self.wcs) # TODO: allow for use of direct input of contours but requires units of # map flux which is not yet implemented cs = axes.contour(self.data, 0.01 * levels.to('percent').value * self.data.max(), **contour_args) return cs @peek_show def peek(self, draw_limb=False, draw_grid=False, colorbar=True, **matplot_args): """ Displays a graphical overview of the data in this object for user evaluation. For the creation of plots, users should instead use the `~sunpy.map.GenericMap.plot` method and Matplotlib's pyplot framework. Parameters ---------- draw_limb : bool Whether the solar limb should be plotted. draw_grid : bool or `~astropy.units.Quantity` Whether solar meridians and parallels are plotted. If `~astropy.units.Quantity` then sets degree difference between parallels and meridians. colorbar : bool Whether to display a colorbar next to the plot. **matplot_args : dict Matplotlib Any additional imshow arguments that should be used when plotting. """ figure = plt.figure() axes = wcsaxes_compat.gca_wcs(self.wcs) im = self.plot(axes=axes, **matplot_args) grid_spacing = None # Handle case where draw_grid is actually the grid sapcing if isinstance(draw_grid, u.Quantity): grid_spacing = draw_grid draw_grid = True elif not isinstance(draw_grid, bool): raise TypeError("draw_grid should be a bool or an astropy Quantity.") if colorbar: if draw_grid: pad = 0.12 # Pad to compensate for ticks and axes labels else: pad = 0.05 # Default value for vertical colorbar colorbar_label = str(self.unit) if self.unit is not None else "" figure.colorbar(im, pad=pad).set_label(colorbar_label, rotation=0, labelpad=-50, y=-0.02, size=12) if draw_limb: self.draw_limb(axes=axes) if draw_grid: if grid_spacing is None: self.draw_grid(axes=axes) else: self.draw_grid(axes=axes, grid_spacing=grid_spacing) return figure @u.quantity_input def plot(self, annotate=True, axes=None, title=True, clip_interval: u.percent = None, **imshow_kwargs): """ Plots the map object using matplotlib, in a method equivalent to plt.imshow() using nearest neighbour interpolation. Parameters ---------- annotate : `bool`, optional If `True`, the data is plotted at its natural scale; with title and axis labels. axes: `~matplotlib.axes` or None If provided the image will be plotted on the given axes. Else the current matplotlib axes will be used. title : `str`, `bool`, optional The plot title. If `True`, uses the default title for this map. clip_interval : two-element `~astropy.units.Quantity`, optional If provided, the data will be clipped to the percentile interval bounded by the two numbers. **imshow_kwargs : `dict` Any additional imshow arguments are passed to `~matplotlib.axes.Axes.imshow`. Examples -------- >>> # Simple Plot with color bar >>> aia.plot() # doctest: +SKIP >>> plt.colorbar() # doctest: +SKIP >>> # Add a limb line and grid >>> aia.plot() # doctest: +SKIP >>> aia.draw_limb() # doctest: +SKIP >>> aia.draw_grid() # doctest: +SKIP """ # Get current axes if not axes: axes = wcsaxes_compat.gca_wcs(self.wcs) if not wcsaxes_compat.is_wcsaxes(axes): warnings.warn("WCSAxes not being used as the axes object for this plot." " Plots may have unexpected behaviour. To fix this pass " "'projection=map' when creating the axes", SunpyUserWarning) # Check if the image is properly oriented if not np.array_equal(self.rotation_matrix, np.identity(2)): warnings.warn("The axes of this map are not aligned to the pixel grid. Plot axes may be incorrect.", SunpyUserWarning) # Normal plot plot_settings = copy.deepcopy(self.plot_settings) if 'title' in plot_settings: plot_settings_title = plot_settings.pop('title') else: plot_settings_title = self.latex_name # Anything left in plot_settings is given to imshow imshow_args = plot_settings if annotate: if title is True: title = plot_settings_title if title: axes.set_title(title) axes.set_xlabel(axis_labels_from_ctype(self.coordinate_system[0], self.spatial_units[0])) axes.set_ylabel(axis_labels_from_ctype(self.coordinate_system[1], self.spatial_units[1])) if not wcsaxes_compat.is_wcsaxes(axes): bl = self._get_lon_lat(self.bottom_left_coord) tr = self._get_lon_lat(self.top_right_coord) x_range = list(u.Quantity([bl[0], tr[0]]).to(self.spatial_units[0]).value) y_range = list(u.Quantity([bl[1], tr[1]]).to(self.spatial_units[1]).value) imshow_args.update({'extent': x_range + y_range}) # Take a deep copy here so that a norm in imshow_kwargs doesn't get modified # by setting it's vmin and vmax imshow_args.update(copy.deepcopy(imshow_kwargs)) if clip_interval is not None: if len(clip_interval) == 2: clip_percentages = clip_interval.to('%').value vmin, vmax = AsymmetricPercentileInterval(*clip_percentages).get_limits(self.data) else: raise ValueError("Clip percentile interval must be specified as two numbers.") imshow_args['vmin'] = vmin imshow_args['vmax'] = vmax if 'norm' in imshow_args: norm = imshow_args['norm'] if 'vmin' in imshow_args: if norm.vmin is not None: raise ValueError('Cannot manually specify vmin, as the norm ' 'already has vmin set') norm.vmin = imshow_args.pop('vmin') if 'vmax' in imshow_args: if norm.vmax is not None: raise ValueError('Cannot manually specify vmax, as the norm ' 'already has vmax set') norm.vmax = imshow_args.pop('vmax') if self.mask is None: ret = axes.imshow(self.data, **imshow_args) else: ret = axes.imshow(np.ma.array(np.asarray(self.data), mask=self.mask), **imshow_args) if wcsaxes_compat.is_wcsaxes(axes): wcsaxes_compat.default_wcs_grid(axes) # Set current axes/image if pyplot is being used (makes colorbar work) for i in plt.get_fignums(): if axes in plt.figure(i).axes: plt.sca(axes) plt.sci(ret) return ret def contour(self, level, **kwargs): """ Returns coordinates of the contours for a given level value. For details of the contouring algorithm see `skimage.measure.find_contours`. Parameters ---------- level : float, astropy.units.Quantity Value along which to find contours in the array. If the map unit attribute is not `None`, this must be a `~astropy.units.Quantity` with units equivalent to the map data units. kwargs : Additional keyword arguments are passed to `skimage.measure.find_contours`. Returns ------- contours: list of (n,2) `~astropy.coordinates.SkyCoord` Coordinates of each contour. Examples -------- >>> import astropy.units as u >>> import sunpy.map >>> import sunpy.data.sample # doctest: +REMOTE_DATA >>> aia = sunpy.map.Map(sunpy.data.sample.AIA_171_IMAGE) # doctest: +REMOTE_DATA >>> contours = aia.contour(50000 * u.ct) # doctest: +REMOTE_DATA >>> print(contours[0]) # doctest: +REMOTE_DATA <SkyCoord (Helioprojective: obstime=2011-06-07T06:33:02.770, rsun=696000000.0 m, observer=<HeliographicStonyhurst Coordinate (obstime=2011-06-07T06:33:02.770): (lon, lat, radius) in (deg, deg, m) (-0.00406308, 0.04787238, 1.51846026e+11)>): (Tx, Ty) in arcsec [(719.59798458, -352.60839064), (717.19243987, -353.75348121), ... See also -------- `skimage.measure.find_contours` """ from skimage import measure if self.unit is not None: try: level = level.to_value(self.unit) # Catch cases where level can't be converted or isn't a Quantity except (AttributeError, u.UnitConversionError) as e: raise u.UnitsError( f'level must be an astropy quantity convertible to {self.unit}') from e contours = measure.find_contours(self.data, level=level, **kwargs) contours = [self.wcs.array_index_to_world(c[:, 0], c[:, 1]) for c in contours] return contours class InvalidHeaderInformation(ValueError): """Exception to raise when an invalid header tag value is encountered for a FITS/JPEG 2000 file.""" def _figure_to_base64(fig): # Converts a matplotlib Figure to a base64 UTF-8 string buf = BytesIO() fig.savefig(buf, format='png', facecolor='none') # works better than transparent=True return b64encode(buf.getvalue()).decode('utf-8')
""" For the multiprocessing to work property, it's best to pass around pure functions into workers instead of methods of a class. Below functions have been designed with that in mind. """ from math import log10 import jesse.helpers as jh from jesse.research.backtest import _isolated_backtest as isolated_backtest from jesse.services import logger import traceback import os from random import randint, choice import numpy as np def _formatted_inputs_for_isolated_backtest(user_config, routes): return { 'starting_balance': user_config['exchange']['balance'], 'fee': user_config['exchange']['fee'], 'futures_leverage': user_config['exchange']['futures_leverage'], 'futures_leverage_mode': user_config['exchange']['futures_leverage_mode'], 'exchange': routes[0]['exchange'], 'settlement_currency': jh.quote_asset(routes[0]['symbol']), 'warm_up_candles': user_config['warmup_candles_num'] } def get_fitness( optimization_config: dict, routes: list, extra_routes: list, strategy_hp, dna: str, training_candles, testing_candles, optimal_total ) -> tuple: """ Notice that this function is likely to be executed inside workers, hence its inputs must have everything required for it to run. So it cannot access store, config, etc """ hp = jh.dna_to_hp(strategy_hp, dna) # run backtest simulation try: training_data_metrics = isolated_backtest( _formatted_inputs_for_isolated_backtest(optimization_config, routes), routes, extra_routes, training_candles, hyperparameters=hp )['metrics'] except Exception as e: # get the main title of the exception log_text = e log_text = f"Exception in strategy execution:\n {log_text}" logger.log_optimize_mode(log_text) raise e training_log = {'win-rate': None, 'total': None, 'PNL': None} testing_log = {'win-rate': None, 'total': None, 'PNL': None} # TODO: some of these have to be dynamic based on how many days it's trading for like for example "total" if training_data_metrics['total'] > 5: total_effect_rate = log10(training_data_metrics['total']) / log10(optimal_total) total_effect_rate = min(total_effect_rate, 1) ratio_config = jh.get_config('env.optimization.ratio', 'sharpe') if ratio_config == 'sharpe': ratio = training_data_metrics['sharpe_ratio'] ratio_normalized = jh.normalize(ratio, -.5, 5) elif ratio_config == 'calmar': ratio = training_data_metrics['calmar_ratio'] ratio_normalized = jh.normalize(ratio, -.5, 30) elif ratio_config == 'sortino': ratio = training_data_metrics['sortino_ratio'] ratio_normalized = jh.normalize(ratio, -.5, 15) elif ratio_config == 'omega': ratio = training_data_metrics['omega_ratio'] ratio_normalized = jh.normalize(ratio, -.5, 5) elif ratio_config == 'serenity': ratio = training_data_metrics['serenity_index'] ratio_normalized = jh.normalize(ratio, -.5, 15) elif ratio_config == 'smart sharpe': ratio = training_data_metrics['smart_sharpe'] ratio_normalized = jh.normalize(ratio, -.5, 5) elif ratio_config == 'smart sortino': ratio = training_data_metrics['smart_sortino'] ratio_normalized = jh.normalize(ratio, -.5, 15) else: raise ValueError( f'The entered ratio configuration `{ratio_config}` for the optimization is unknown. Choose between sharpe, calmar, sortino, serenity, smart shapre, smart sortino and omega.') if ratio < 0: score = 0.0001 logger.log_optimize_mode(f"NEGATIVE RATIO: DNA is not usable => {ratio_config}: {ratio}, total: {training_data_metrics["total"]}") return score, training_log, testing_log # log for debugging/monitoring training_log = { 'win-rate': int(training_data_metrics['win_rate'] * 100), 'total': training_data_metrics['total'], 'PNL': round(training_data_metrics['net_profit_percentage'], 2) } score = total_effect_rate * ratio_normalized # if score is numpy nan, replace it with 0.0001 if np.isnan(score): logger.log_optimize_mode(f'Score is nan. DNA is invalid') score = 0.0001 # elif jh.is_debugging(): else: logger.log_optimize_mode(f"DNA is usable => {ratio_config}: {round(ratio, 2)}, total: {training_data_metrics["total"]}, PNL%: {round(training_data_metrics["net_profit_percentage"], 2)}%, win-rate: {round(training_data_metrics["win_rate"]*100, 2)}%") # run backtest simulation testing_data_metrics = isolated_backtest( _formatted_inputs_for_isolated_backtest(optimization_config, routes), routes, extra_routes, testing_candles, hyperparameters=hp )['metrics'] # log for debugging/monitoring if testing_data_metrics['total'] > 0: testing_log = { 'win-rate': int(testing_data_metrics['win_rate'] * 100), 'total': testing_data_metrics['total'], 'PNL': round(testing_data_metrics['net_profit_percentage'], 2) } else: logger.log_optimize_mode(f'Less than 5 trades in the training data. DNA is invalid') score = 0.0001 return score, training_log, testing_log def get_and_add_fitness_to_the_bucket( dna_bucket, optimization_config, routes: list, extra_routes: list, strategy_hp, dna, training_candles, testing_candles, optimal_total ) -> None: """ Calculates the fitness and adds the result into the dna_bucket (which is the object passed among workers) """ try: # check if the DNA is already in the list if all(dna_tuple[0] != dna for dna_tuple in dna_bucket): fitness_score, fitness_log_training, fitness_log_testing = get_fitness( optimization_config, routes, extra_routes, strategy_hp, dna, training_candles, testing_candles, optimal_total ) dna_bucket.append((dna, fitness_score, fitness_log_training, fitness_log_testing)) else: raise ValueError(f"Initial Population: Double DNA: {dna}") except Exception as e: pid = os.getpid() logger.log_optimize_mode(f"process failed (ID: {pid}):\n{e}") def make_love( mommy, daddy, solution_len, optimization_config, routes, extra_routes, strategy_hp, training_candles, testing_candles, optimal_total ) -> dict: dna = ''.join( daddy['dna'][i] if i % 2 == 0 else mommy['dna'][i] for i in range(solution_len) ) # not found - so run the backtest fitness_score, fitness_log_training, fitness_log_testing = get_fitness( optimization_config, routes, extra_routes, strategy_hp, dna, training_candles, testing_candles, optimal_total ) return { 'dna': dna, 'fitness': fitness_score, 'training_log': fitness_log_training, 'testing_log': fitness_log_testing } def mutate( baby, solution_len, charset, optimization_config, routes, extra_routes, strategy_hp, training_candles, testing_candles, optimal_total ) -> dict: replace_at = randint(0, solution_len - 1) replace_with = choice(charset) dna = f"{baby["dna"][:replace_at]}{replace_with}{baby["dna"][replace_at + 1:]}" # not found - so run the backtest fitness_score, fitness_log_training, fitness_log_testing = get_fitness( optimization_config, routes, extra_routes, strategy_hp, dna, training_candles, testing_candles, optimal_total ) return { 'dna': dna, 'fitness': fitness_score, 'training_log': fitness_log_training, 'testing_log': fitness_log_testing } def create_baby( people_bucket: list, mommy, daddy, solution_len, charset, optimization_config, routes, extra_routes, strategy_hp, training_candles, testing_candles, optimal_total ) -> None: try: # let's make a baby together 👀 baby = make_love( mommy, daddy, solution_len, optimization_config, routes, extra_routes, strategy_hp, training_candles, testing_candles, optimal_total ) # let's mutate baby's genes, who knows, maybe we create a x-man or something baby = mutate( baby, solution_len, charset, optimization_config, routes, extra_routes, strategy_hp, training_candles, testing_candles, optimal_total ) people_bucket.append(baby) except Exception as e: pid = os.getpid() logger.log_optimize_mode(f"process failed - ID: {pid}\n{e}")
""" For the multiprocessing to work property, it's best to pass around pure functions into workers instead of methods of a class. Below functions have been designed with that in mind. """ from math import log10 import jesse.helpers as jh from jesse.research.backtest import _isolated_backtest as isolated_backtest from jesse.services import logger import traceback import os from random import randint, choice import numpy as np def _formatted_inputs_for_isolated_backtest(user_config, routes): return { 'starting_balance': user_config['exchange']['balance'], 'fee': user_config['exchange']['fee'], 'futures_leverage': user_config['exchange']['futures_leverage'], 'futures_leverage_mode': user_config['exchange']['futures_leverage_mode'], 'exchange': routes[0]['exchange'], 'settlement_currency': jh.quote_asset(routes[0]['symbol']), 'warm_up_candles': user_config['warmup_candles_num'] } def get_fitness( optimization_config: dict, routes: list, extra_routes: list, strategy_hp, dna: str, training_candles, testing_candles, optimal_total ) -> tuple: """ Notice that this function is likely to be executed inside workers, hence its inputs must have everything required for it to run. So it cannot access store, config, etc """ hp = jh.dna_to_hp(strategy_hp, dna) # run backtest simulation try: training_data_metrics = isolated_backtest( _formatted_inputs_for_isolated_backtest(optimization_config, routes), routes, extra_routes, training_candles, hyperparameters=hp )['metrics'] except Exception as e: # get the main title of the exception log_text = e log_text = f"Exception in strategy execution:\n {log_text}" logger.log_optimize_mode(log_text) raise e training_log = {'win-rate': None, 'total': None, 'PNL': None} testing_log = {'win-rate': None, 'total': None, 'PNL': None} # TODO: some of these have to be dynamic based on how many days it's trading for like for example "total" if training_data_metrics['total'] > 5: total_effect_rate = log10(training_data_metrics['total']) / log10(optimal_total) total_effect_rate = min(total_effect_rate, 1) ratio_config = jh.get_config('env.optimization.ratio', 'sharpe') if ratio_config == 'sharpe': ratio = training_data_metrics['sharpe_ratio'] ratio_normalized = jh.normalize(ratio, -.5, 5) elif ratio_config == 'calmar': ratio = training_data_metrics['calmar_ratio'] ratio_normalized = jh.normalize(ratio, -.5, 30) elif ratio_config == 'sortino': ratio = training_data_metrics['sortino_ratio'] ratio_normalized = jh.normalize(ratio, -.5, 15) elif ratio_config == 'omega': ratio = training_data_metrics['omega_ratio'] ratio_normalized = jh.normalize(ratio, -.5, 5) elif ratio_config == 'serenity': ratio = training_data_metrics['serenity_index'] ratio_normalized = jh.normalize(ratio, -.5, 15) elif ratio_config == 'smart sharpe': ratio = training_data_metrics['smart_sharpe'] ratio_normalized = jh.normalize(ratio, -.5, 5) elif ratio_config == 'smart sortino': ratio = training_data_metrics['smart_sortino'] ratio_normalized = jh.normalize(ratio, -.5, 15) else: raise ValueError( f'The entered ratio configuration `{ratio_config}` for the optimization is unknown. Choose between sharpe, calmar, sortino, serenity, smart shapre, smart sortino and omega.') if ratio < 0: score = 0.0001 logger.log_optimize_mode(f"NEGATIVE RATIO: DNA is not usable => {ratio_config}: {ratio}, total: {training_data_metrics['total']}") return score, training_log, testing_log # log for debugging/monitoring training_log = { 'win-rate': int(training_data_metrics['win_rate'] * 100), 'total': training_data_metrics['total'], 'PNL': round(training_data_metrics['net_profit_percentage'], 2) } score = total_effect_rate * ratio_normalized # if score is numpy nan, replace it with 0.0001 if np.isnan(score): logger.log_optimize_mode(f'Score is nan. DNA is invalid') score = 0.0001 # elif jh.is_debugging(): else: logger.log_optimize_mode(f"DNA is usable => {ratio_config}: {round(ratio, 2)}, total: {training_data_metrics['total']}, PNL%: {round(training_data_metrics['net_profit_percentage'], 2)}%, win-rate: {round(training_data_metrics['win_rate']*100, 2)}%") # run backtest simulation testing_data_metrics = isolated_backtest( _formatted_inputs_for_isolated_backtest(optimization_config, routes), routes, extra_routes, testing_candles, hyperparameters=hp )['metrics'] # log for debugging/monitoring if testing_data_metrics['total'] > 0: testing_log = { 'win-rate': int(testing_data_metrics['win_rate'] * 100), 'total': testing_data_metrics['total'], 'PNL': round(testing_data_metrics['net_profit_percentage'], 2) } else: logger.log_optimize_mode(f'Less than 5 trades in the training data. DNA is invalid') score = 0.0001 return score, training_log, testing_log def get_and_add_fitness_to_the_bucket( dna_bucket, optimization_config, routes: list, extra_routes: list, strategy_hp, dna, training_candles, testing_candles, optimal_total ) -> None: """ Calculates the fitness and adds the result into the dna_bucket (which is the object passed among workers) """ try: # check if the DNA is already in the list if all(dna_tuple[0] != dna for dna_tuple in dna_bucket): fitness_score, fitness_log_training, fitness_log_testing = get_fitness( optimization_config, routes, extra_routes, strategy_hp, dna, training_candles, testing_candles, optimal_total ) dna_bucket.append((dna, fitness_score, fitness_log_training, fitness_log_testing)) else: raise ValueError(f"Initial Population: Double DNA: {dna}") except Exception as e: pid = os.getpid() logger.log_optimize_mode(f"process failed (ID: {pid}):\n{e}") def make_love( mommy, daddy, solution_len, optimization_config, routes, extra_routes, strategy_hp, training_candles, testing_candles, optimal_total ) -> dict: dna = ''.join( daddy['dna'][i] if i % 2 == 0 else mommy['dna'][i] for i in range(solution_len) ) # not found - so run the backtest fitness_score, fitness_log_training, fitness_log_testing = get_fitness( optimization_config, routes, extra_routes, strategy_hp, dna, training_candles, testing_candles, optimal_total ) return { 'dna': dna, 'fitness': fitness_score, 'training_log': fitness_log_training, 'testing_log': fitness_log_testing } def mutate( baby, solution_len, charset, optimization_config, routes, extra_routes, strategy_hp, training_candles, testing_candles, optimal_total ) -> dict: replace_at = randint(0, solution_len - 1) replace_with = choice(charset) dna = f"{baby['dna'][:replace_at]}{replace_with}{baby['dna'][replace_at + 1:]}" # not found - so run the backtest fitness_score, fitness_log_training, fitness_log_testing = get_fitness( optimization_config, routes, extra_routes, strategy_hp, dna, training_candles, testing_candles, optimal_total ) return { 'dna': dna, 'fitness': fitness_score, 'training_log': fitness_log_training, 'testing_log': fitness_log_testing } def create_baby( people_bucket: list, mommy, daddy, solution_len, charset, optimization_config, routes, extra_routes, strategy_hp, training_candles, testing_candles, optimal_total ) -> None: try: # let's make a baby together 👀 baby = make_love( mommy, daddy, solution_len, optimization_config, routes, extra_routes, strategy_hp, training_candles, testing_candles, optimal_total ) # let's mutate baby's genes, who knows, maybe we create a x-man or something baby = mutate( baby, solution_len, charset, optimization_config, routes, extra_routes, strategy_hp, training_candles, testing_candles, optimal_total ) people_bucket.append(baby) except Exception as e: pid = os.getpid() logger.log_optimize_mode(f"process failed - ID: {pid}\n{e}")
#!/usr/bin/env python # -*- coding: utf-8 -*- # # complexity documentation build configuration file, created by # sphinx-quickstart on Tue Jul 9 22:26:36 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # Get the project root dir, which is the parent dir of this from pathlib import Path from subprocess import check_call cwd = os.getcwd() project_root = os.path.dirname(cwd) # Insert the project root dir as the first element in the PYTHONPATH. # This lets us ensure that the source package is imported, and that its # version is used. sys.path.insert(0, project_root) os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings' from django import setup setup() check_call(f"python {(Path(__file__).parent.parent / "make_doc_rsts.py").absolute()}", shell=True) check_call(f"cd {(Path(__file__).parent.parent).absolute()}; python -m pytest docs", shell=True) # -- General configuration ----------------------------------------------------- html_css_files = [ 'custom.css', ] html_js_files = [ 'custom.js', ] html_extra_path = [ 'custom', ] # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [ # 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.todo', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'iommi' copyright = u'2022, Anders Hovmöller & Johan Lübcke' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. import iommi version = iommi.__version__ # The full version, including alpha/beta/rc tags. release = iommi.__version__ # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. # This turns `foo` from just italic to the same as :code:`foo` default_role = 'code' #html_extra_path = [] # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'furo' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. # import sphinx_rtd_theme # html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. html_logo = '../logo_with_outline.svg' # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. html_favicon = 'favicon.ico' # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'iommi_tablesdoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'iommi.tex', u'iommi', u'Anders Hovmöller', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'iommi', u'iommi', [u'Anders Hovmöller'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'iommi', u'iommi', u'Anders Hovmöller', 'iommi', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False
#!/usr/bin/env python # -*- coding: utf-8 -*- # # complexity documentation build configuration file, created by # sphinx-quickstart on Tue Jul 9 22:26:36 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # Get the project root dir, which is the parent dir of this from pathlib import Path from subprocess import check_call cwd = os.getcwd() project_root = os.path.dirname(cwd) # Insert the project root dir as the first element in the PYTHONPATH. # This lets us ensure that the source package is imported, and that its # version is used. sys.path.insert(0, project_root) os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings' from django import setup setup() check_call(f"python {(Path(__file__).parent.parent / 'make_doc_rsts.py').absolute()}", shell=True) check_call(f"cd {(Path(__file__).parent.parent).absolute()}; python -m pytest docs", shell=True) # -- General configuration ----------------------------------------------------- html_css_files = [ 'custom.css', ] html_js_files = [ 'custom.js', ] html_extra_path = [ 'custom', ] # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [ # 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.todo', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'iommi' copyright = u'2022, Anders Hovmöller & Johan Lübcke' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. import iommi version = iommi.__version__ # The full version, including alpha/beta/rc tags. release = iommi.__version__ # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. # This turns `foo` from just italic to the same as :code:`foo` default_role = 'code' #html_extra_path = [] # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'furo' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. # import sphinx_rtd_theme # html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. html_logo = '../logo_with_outline.svg' # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. html_favicon = 'favicon.ico' # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'iommi_tablesdoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'iommi.tex', u'iommi', u'Anders Hovmöller', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'iommi', u'iommi', [u'Anders Hovmöller'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'iommi', u'iommi', u'Anders Hovmöller', 'iommi', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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 # # http://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. # import time from typing import TYPE_CHECKING, Any, Dict, Iterable, Iterator, List, Optional, Sequence, Set, Tuple import attr import pendulum from sqlalchemy.exc import OperationalError from sqlalchemy.orm.session import Session, make_transient from tabulate import tabulate from airflow import models from airflow.exceptions import ( AirflowException, BackfillUnfinished, DagConcurrencyLimitReached, NoAvailablePoolSlot, PoolNotFound, TaskConcurrencyLimitReached, ) from airflow.executors import executor_constants from airflow.jobs.base_job import BaseJob from airflow.models import DAG, DagPickle from airflow.models.dagrun import DagRun from airflow.models.taskinstance import TaskInstance, TaskInstanceKey from airflow.ti_deps.dep_context import DepContext from airflow.ti_deps.dependencies_deps import BACKFILL_QUEUED_DEPS from airflow.timetables.base import DagRunInfo from airflow.utils import helpers, timezone from airflow.utils.configuration import conf as airflow_conf, tmp_configuration_copy from airflow.utils.session import provide_session from airflow.utils.state import DagRunState, State, TaskInstanceState from airflow.utils.types import DagRunType if TYPE_CHECKING: from airflow.models.mappedoperator import MappedOperator class BackfillJob(BaseJob): """ A backfill job consists of a dag or subdag for a specific time range. It triggers a set of task instance runs, in the right order and lasts for as long as it takes for the set of task instance to be completed. """ STATES_COUNT_AS_RUNNING = (State.RUNNING, State.QUEUED) __mapper_args__ = {'polymorphic_identity': 'BackfillJob'} @attr.define class _DagRunTaskStatus: """ Internal status of the backfill job. This class is intended to be instantiated only within a BackfillJob instance and will track the execution of tasks, e.g. running, skipped, succeeded, failed, etc. Information about the dag runs related to the backfill job are also being tracked in this structure, .e.g finished runs, etc. Any other status related information related to the execution of dag runs / tasks can be included in this structure since it makes it easier to pass it around. :param to_run: Tasks to run in the backfill :param running: Maps running task instance key to task instance object :param skipped: Tasks that have been skipped :param succeeded: Tasks that have succeeded so far :param failed: Tasks that have failed :param not_ready: Tasks not ready for execution :param deadlocked: Deadlocked tasks :param active_runs: Active dag runs at a certain point in time :param executed_dag_run_dates: Datetime objects for the executed dag runs :param finished_runs: Number of finished runs so far :param total_runs: Number of total dag runs able to run """ to_run: Dict[TaskInstanceKey, TaskInstance] = attr.ib(factory=dict) running: Dict[TaskInstanceKey, TaskInstance] = attr.ib(factory=dict) skipped: Set[TaskInstanceKey] = attr.ib(factory=set) succeeded: Set[TaskInstanceKey] = attr.ib(factory=set) failed: Set[TaskInstanceKey] = attr.ib(factory=set) not_ready: Set[TaskInstanceKey] = attr.ib(factory=set) deadlocked: Set[TaskInstance] = attr.ib(factory=set) active_runs: List[DagRun] = attr.ib(factory=list) executed_dag_run_dates: Set[pendulum.DateTime] = attr.ib(factory=set) finished_runs: int = 0 total_runs: int = 0 def __init__( self, dag, start_date=None, end_date=None, mark_success=False, donot_pickle=False, ignore_first_depends_on_past=False, ignore_task_deps=False, pool=None, delay_on_limit_secs=1.0, verbose=False, conf=None, rerun_failed_tasks=False, run_backwards=False, run_at_least_once=False, continue_on_failures=False, *args, **kwargs, ): """ :param dag: DAG object. :param start_date: start date for the backfill date range. :param end_date: end date for the backfill date range. :param mark_success: flag whether to mark the task auto success. :param donot_pickle: whether pickle :param ignore_first_depends_on_past: whether to ignore depend on past :param ignore_task_deps: whether to ignore the task dependency :param pool: pool to backfill :param delay_on_limit_secs: :param verbose: :param conf: a dictionary which user could pass k-v pairs for backfill :param rerun_failed_tasks: flag to whether to auto rerun the failed task in backfill :param run_backwards: Whether to process the dates from most to least recent :param run_at_least_once: If true, always run the DAG at least once even if no logical run exists within the time range. :param args: :param kwargs: """ self.dag = dag self.dag_id = dag.dag_id self.bf_start_date = start_date self.bf_end_date = end_date self.mark_success = mark_success self.donot_pickle = donot_pickle self.ignore_first_depends_on_past = ignore_first_depends_on_past self.ignore_task_deps = ignore_task_deps self.pool = pool self.delay_on_limit_secs = delay_on_limit_secs self.verbose = verbose self.conf = conf self.rerun_failed_tasks = rerun_failed_tasks self.run_backwards = run_backwards self.run_at_least_once = run_at_least_once self.continue_on_failures = continue_on_failures super().__init__(*args, **kwargs) def _update_counters(self, ti_status, session=None): """ Updates the counters per state of the tasks that were running. Can re-add to tasks to run in case required. :param ti_status: the internal status of the backfill job tasks """ tis_to_be_scheduled = [] refreshed_tis = [] TI = TaskInstance filter_for_tis = TI.filter_for_tis(list(ti_status.running.values())) if filter_for_tis is not None: refreshed_tis = session.query(TI).filter(filter_for_tis).all() for ti in refreshed_tis: # Here we remake the key by subtracting 1 to match in memory information reduced_key = ti.key.reduced if ti.state == TaskInstanceState.SUCCESS: ti_status.succeeded.add(reduced_key) self.log.debug("Task instance %s succeeded. Don't rerun.", ti) ti_status.running.pop(reduced_key) continue if ti.state == TaskInstanceState.SKIPPED: ti_status.skipped.add(reduced_key) self.log.debug("Task instance %s skipped. Don't rerun.", ti) ti_status.running.pop(reduced_key) continue if ti.state == TaskInstanceState.FAILED: self.log.error("Task instance %s failed", ti) ti_status.failed.add(reduced_key) ti_status.running.pop(reduced_key) continue # special case: if the task needs to run again put it back if ti.state == TaskInstanceState.UP_FOR_RETRY: self.log.warning("Task instance %s is up for retry", ti) ti_status.running.pop(reduced_key) ti_status.to_run[ti.key] = ti # special case: if the task needs to be rescheduled put it back elif ti.state == TaskInstanceState.UP_FOR_RESCHEDULE: self.log.warning("Task instance %s is up for reschedule", ti) # During handling of reschedule state in ti._handle_reschedule, try number is reduced # by one, so we should not use reduced_key to avoid key error ti_status.running.pop(ti.key) ti_status.to_run[ti.key] = ti # special case: The state of the task can be set to NONE by the task itself # when it reaches concurrency limits. It could also happen when the state # is changed externally, e.g. by clearing tasks from the ui. We need to cover # for that as otherwise those tasks would fall outside of the scope of # the backfill suddenly. elif ti.state == State.NONE: self.log.warning( "FIXME: task instance %s state was set to none externally or " "reaching concurrency limits. Re-adding task to queue.", ti, ) tis_to_be_scheduled.append(ti) ti_status.running.pop(reduced_key) ti_status.to_run[ti.key] = ti # Batch schedule of task instances if tis_to_be_scheduled: filter_for_tis = TI.filter_for_tis(tis_to_be_scheduled) session.query(TI).filter(filter_for_tis).update( values={TI.state: TaskInstanceState.SCHEDULED}, synchronize_session=False ) session.flush() def _manage_executor_state( self, running, session ) -> Iterator[Tuple["MappedOperator", str, Sequence[TaskInstance]]]: """ Checks if the executor agrees with the state of task instances that are running. Expands downstream mapped tasks when necessary :param running: dict of key, task to verify :return: An iterable of expanded TaskInstance per MappedTask """ from airflow.models.mappedoperator import MappedOperator executor = self.executor # TODO: query all instead of refresh from db for key, value in list(executor.get_event_buffer().items()): state, info = value if key not in running: self.log.warning("%s state %s not in running=%s", key, state, running.values()) continue ti = running[key] ti.refresh_from_db() self.log.debug("Executor state: %s task %s", state, ti) if ( state in (TaskInstanceState.FAILED, TaskInstanceState.SUCCESS) and ti.state in self.STATES_COUNT_AS_RUNNING ): msg = ( f"Executor reports task instance {ti} finished ({state}) although the task says its " f"{ti.state}. Was the task killed externally? Info: {info}" ) self.log.error(msg) ti.handle_failure_with_callback(error=msg) continue if ti.state not in self.STATES_COUNT_AS_RUNNING: for node in ti.task.mapped_dependants(): assert isinstance(node, MappedOperator) yield node, ti.run_id, node.expand_mapped_task(ti.run_id, session=session) @provide_session def _get_dag_run(self, dagrun_info: DagRunInfo, dag: DAG, session: Session = None): """ Returns a dag run for the given run date, which will be matched to an existing dag run if available or create a new dag run otherwise. If the max_active_runs limit is reached, this function will return None. :param dagrun_info: Schedule information for the dag run :param dag: DAG :param session: the database session object :return: a DagRun in state RUNNING or None """ run_date = dagrun_info.logical_date # consider max_active_runs but ignore when running subdags respect_dag_max_active_limit = bool(dag.timetable.can_run and not dag.is_subdag) current_active_dag_count = dag.get_num_active_runs(external_trigger=False) # check if we are scheduling on top of a already existing dag_run # we could find a "scheduled" run instead of a "backfill" runs = DagRun.find(dag_id=dag.dag_id, execution_date=run_date, session=session) run: Optional[DagRun] if runs: run = runs[0] if run.state == DagRunState.RUNNING: respect_dag_max_active_limit = False # Fixes --conf overwrite for backfills with already existing DagRuns run.conf = self.conf or {} else: run = None # enforce max_active_runs limit for dag, special cases already # handled by respect_dag_max_active_limit if respect_dag_max_active_limit and current_active_dag_count >= dag.max_active_runs: return None run = run or dag.create_dagrun( execution_date=run_date, data_interval=dagrun_info.data_interval, start_date=timezone.utcnow(), state=DagRunState.RUNNING, external_trigger=False, session=session, conf=self.conf, run_type=DagRunType.BACKFILL_JOB, creating_job_id=self.id, ) # set required transient field run.dag = dag # explicitly mark as backfill and running run.state = DagRunState.RUNNING run.run_type = DagRunType.BACKFILL_JOB run.verify_integrity(session=session) return run @provide_session def _task_instances_for_dag_run(self, dag_run, session=None): """ Returns a map of task instance key to task instance object for the tasks to run in the given dag run. :param dag_run: the dag run to get the tasks from :param session: the database session object """ tasks_to_run = {} if dag_run is None: return tasks_to_run # check if we have orphaned tasks self.reset_state_for_orphaned_tasks(filter_by_dag_run=dag_run, session=session) # for some reason if we don't refresh the reference to run is lost dag_run.refresh_from_db() make_transient(dag_run) try: for ti in dag_run.get_task_instances(): # all tasks part of the backfill are scheduled to run if ti.state == State.NONE: ti.set_state(TaskInstanceState.SCHEDULED, session=session) if ti.state != TaskInstanceState.REMOVED: tasks_to_run[ti.key] = ti session.commit() except Exception: session.rollback() raise return tasks_to_run def _log_progress(self, ti_status): self.log.info( '[backfill progress] | finished run %s of %s | tasks waiting: %s | succeeded: %s | ' 'running: %s | failed: %s | skipped: %s | deadlocked: %s | not ready: %s', ti_status.finished_runs, ti_status.total_runs, len(ti_status.to_run), len(ti_status.succeeded), len(ti_status.running), len(ti_status.failed), len(ti_status.skipped), len(ti_status.deadlocked), len(ti_status.not_ready), ) self.log.debug("Finished dag run loop iteration. Remaining tasks %s", ti_status.to_run.values()) @provide_session def _process_backfill_task_instances( self, ti_status, executor, pickle_id, start_date=None, session=None, ): """ Process a set of task instances from a set of dag runs. Special handling is done to account for different task instance states that could be present when running them in a backfill process. :param ti_status: the internal status of the job :param executor: the executor to run the task instances :param pickle_id: the pickle_id if dag is pickled, None otherwise :param start_date: the start date of the backfill job :param session: the current session object :return: the list of execution_dates for the finished dag runs :rtype: list """ executed_run_dates = [] is_unit_test = airflow_conf.getboolean('core', 'unit_test_mode') while (len(ti_status.to_run) > 0 or len(ti_status.running) > 0) and len(ti_status.deadlocked) == 0: self.log.debug("*** Clearing out not_ready list ***") ti_status.not_ready.clear() # we need to execute the tasks bottom to top # or leaf to root, as otherwise tasks might be # determined deadlocked while they are actually # waiting for their upstream to finish def _per_task_process(key, ti: TaskInstance, session=None): ti.refresh_from_db(lock_for_update=True, session=session) task = self.dag.get_task(ti.task_id, include_subdags=True) ti.task = task self.log.debug("Task instance to run %s state %s", ti, ti.state) # The task was already marked successful or skipped by a # different Job. Don't rerun it. if ti.state == TaskInstanceState.SUCCESS: ti_status.succeeded.add(key) self.log.debug("Task instance %s succeeded. Don't rerun.", ti) ti_status.to_run.pop(key) if key in ti_status.running: ti_status.running.pop(key) return elif ti.state == TaskInstanceState.SKIPPED: ti_status.skipped.add(key) self.log.debug("Task instance %s skipped. Don't rerun.", ti) ti_status.to_run.pop(key) if key in ti_status.running: ti_status.running.pop(key) return # guard against externally modified tasks instances or # in case max concurrency has been reached at task runtime elif ti.state == State.NONE: self.log.warning( "FIXME: Task instance %s state was set to None externally. This should not happen", ti ) ti.set_state(TaskInstanceState.SCHEDULED, session=session) if self.rerun_failed_tasks: # Rerun failed tasks or upstreamed failed tasks if ti.state in (TaskInstanceState.FAILED, TaskInstanceState.UPSTREAM_FAILED): self.log.error("Task instance %s with state %s", ti, ti.state) if key in ti_status.running: ti_status.running.pop(key) # Reset the failed task in backfill to scheduled state ti.set_state(TaskInstanceState.SCHEDULED, session=session) else: # Default behaviour which works for subdag. if ti.state in (TaskInstanceState.FAILED, TaskInstanceState.UPSTREAM_FAILED): self.log.error("Task instance %s with state %s", ti, ti.state) ti_status.failed.add(key) ti_status.to_run.pop(key) if key in ti_status.running: ti_status.running.pop(key) return if self.ignore_first_depends_on_past: dagrun = ti.get_dagrun(session=session) ignore_depends_on_past = dagrun.execution_date == (start_date or ti.start_date) else: ignore_depends_on_past = False backfill_context = DepContext( deps=BACKFILL_QUEUED_DEPS, ignore_depends_on_past=ignore_depends_on_past, ignore_task_deps=self.ignore_task_deps, flag_upstream_failed=True, ) # Is the task runnable? -- then run it # the dependency checker can change states of tis if ti.are_dependencies_met( dep_context=backfill_context, session=session, verbose=self.verbose ): if executor.has_task(ti): self.log.debug("Task Instance %s already in executor waiting for queue to clear", ti) else: self.log.debug('Sending %s to executor', ti) # Skip scheduled state, we are executing immediately ti.state = TaskInstanceState.QUEUED ti.queued_by_job_id = self.id ti.queued_dttm = timezone.utcnow() session.merge(ti) try: session.commit() except OperationalError: self.log.exception("Failed to commit task state change due to operational error") session.rollback() # early exit so the outer loop can retry return cfg_path = None if self.executor_class in ( executor_constants.LOCAL_EXECUTOR, executor_constants.SEQUENTIAL_EXECUTOR, ): cfg_path = tmp_configuration_copy() executor.queue_task_instance( ti, mark_success=self.mark_success, pickle_id=pickle_id, ignore_task_deps=self.ignore_task_deps, ignore_depends_on_past=ignore_depends_on_past, pool=self.pool, cfg_path=cfg_path, ) ti_status.running[key] = ti ti_status.to_run.pop(key) return if ti.state == TaskInstanceState.UPSTREAM_FAILED: self.log.error("Task instance %s upstream failed", ti) ti_status.failed.add(key) ti_status.to_run.pop(key) if key in ti_status.running: ti_status.running.pop(key) return # special case if ti.state == TaskInstanceState.UP_FOR_RETRY: self.log.debug("Task instance %s retry period not expired yet", ti) if key in ti_status.running: ti_status.running.pop(key) ti_status.to_run[key] = ti return # special case if ti.state == TaskInstanceState.UP_FOR_RESCHEDULE: self.log.debug("Task instance %s reschedule period not expired yet", ti) if key in ti_status.running: ti_status.running.pop(key) ti_status.to_run[key] = ti return # all remaining tasks self.log.debug('Adding %s to not_ready', ti) ti_status.not_ready.add(key) try: for task in self.dag.topological_sort(include_subdag_tasks=True): for key, ti in list(ti_status.to_run.items()): if task.task_id != ti.task_id: continue pool = session.query(models.Pool).filter(models.Pool.pool == task.pool).first() if not pool: raise PoolNotFound(f'Unknown pool: {task.pool}') open_slots = pool.open_slots(session=session) if open_slots <= 0: raise NoAvailablePoolSlot( f"Not scheduling since there are {open_slots} open slots in pool {task.pool}" ) num_running_task_instances_in_dag = DAG.get_num_task_instances( self.dag_id, states=self.STATES_COUNT_AS_RUNNING, session=session, ) if num_running_task_instances_in_dag >= self.dag.max_active_tasks: raise DagConcurrencyLimitReached( "Not scheduling since DAG max_active_tasks limit is reached." ) if task.max_active_tis_per_dag: num_running_task_instances_in_task = DAG.get_num_task_instances( dag_id=self.dag_id, task_ids=[task.task_id], states=self.STATES_COUNT_AS_RUNNING, session=session, ) if num_running_task_instances_in_task >= task.max_active_tis_per_dag: raise TaskConcurrencyLimitReached( "Not scheduling since Task concurrency limit is reached." ) _per_task_process(key, ti, session) session.commit() except (NoAvailablePoolSlot, DagConcurrencyLimitReached, TaskConcurrencyLimitReached) as e: self.log.debug(e) self.heartbeat(only_if_necessary=is_unit_test) # execute the tasks in the queue executor.heartbeat() # If the set of tasks that aren't ready ever equals the set of # tasks to run and there are no running tasks then the backfill # is deadlocked if ( ti_status.not_ready and ti_status.not_ready == set(ti_status.to_run) and len(ti_status.running) == 0 ): self.log.warning("Deadlock discovered for ti_status.to_run=%s", ti_status.to_run.values()) ti_status.deadlocked.update(ti_status.to_run.values()) ti_status.to_run.clear() # check executor state -- and expand any mapped TIs for node, run_id, mapped_tis in self._manage_executor_state(ti_status.running, session): def to_keep(key: TaskInstanceKey) -> bool: if key.dag_id != node.dag_id or key.task_id != node.task_id or key.run_id != run_id: # For another Dag/Task/Run -- don't remove return True return False # remove the old unmapped TIs for node -- they have been replaced with the mapped TIs ti_status.to_run = {key: ti for (key, ti) in ti_status.to_run.items() if to_keep(key)} ti_status.to_run.update({ti.key: ti for ti in mapped_tis}) # update the task counters self._update_counters(ti_status=ti_status, session=session) session.commit() # update dag run state _dag_runs = ti_status.active_runs[:] for run in _dag_runs: run.update_state(session=session) if run.state in State.finished: ti_status.finished_runs += 1 ti_status.active_runs.remove(run) executed_run_dates.append(run.execution_date) self._log_progress(ti_status) session.commit() # return updated status return executed_run_dates @provide_session def _collect_errors(self, ti_status: _DagRunTaskStatus, session=None): def tabulate_ti_keys_set(ti_keys: Iterable[TaskInstanceKey]) -> str: # Sorting by execution date first sorted_ti_keys: Any = sorted( ti_keys, key=lambda ti_key: ( ti_key.run_id, ti_key.dag_id, ti_key.task_id, ti_key.map_index, ti_key.try_number, ), ) if all(key.map_index == -1 for key in ti_keys): headers = ["DAG ID", "Task ID", "Run ID", "Try number"] sorted_ti_keys = map(lambda k: k[0:4], sorted_ti_keys) else: headers = ["DAG ID", "Task ID", "Run ID", "Map Index", "Try number"] return tabulate(sorted_ti_keys, headers=headers) err = '' if ti_status.failed: err += "Some task instances failed:\n" err += tabulate_ti_keys_set(ti_status.failed) if ti_status.deadlocked: err += 'BackfillJob is deadlocked.' deadlocked_depends_on_past = any( t.are_dependencies_met( dep_context=DepContext(ignore_depends_on_past=False), session=session, verbose=self.verbose, ) != t.are_dependencies_met( dep_context=DepContext(ignore_depends_on_past=True), session=session, verbose=self.verbose ) for t in ti_status.deadlocked ) if deadlocked_depends_on_past: err += ( 'Some of the deadlocked tasks were unable to run because ' 'of "depends_on_past" relationships. Try running the ' 'backfill with the option ' '"ignore_first_depends_on_past=True" or passing "-I" at ' 'the command line.' ) err += '\nThese tasks have succeeded:\n' err += tabulate_ti_keys_set(ti_status.succeeded) err += '\n\nThese tasks are running:\n' err += tabulate_ti_keys_set(ti_status.running) err += '\n\nThese tasks have failed:\n' err += tabulate_ti_keys_set(ti_status.failed) err += '\n\nThese tasks are skipped:\n' err += tabulate_ti_keys_set(ti_status.skipped) err += '\n\nThese tasks are deadlocked:\n' err += tabulate_ti_keys_set([ti.key for ti in ti_status.deadlocked]) return err def _get_dag_with_subdags(self): return [self.dag] + self.dag.subdags @provide_session def _execute_dagruns(self, dagrun_infos, ti_status, executor, pickle_id, start_date, session=None): """ Computes the dag runs and their respective task instances for the given run dates and executes the task instances. Returns a list of execution dates of the dag runs that were executed. :param dagrun_infos: Schedule information for dag runs :param ti_status: internal BackfillJob status structure to tis track progress :param executor: the executor to use, it must be previously started :param pickle_id: numeric id of the pickled dag, None if not pickled :param start_date: backfill start date :param session: the current session object """ for dagrun_info in dagrun_infos: for dag in self._get_dag_with_subdags(): dag_run = self._get_dag_run(dagrun_info, dag, session=session) tis_map = self._task_instances_for_dag_run(dag_run, session=session) if dag_run is None: continue ti_status.active_runs.append(dag_run) ti_status.to_run.update(tis_map or {}) processed_dag_run_dates = self._process_backfill_task_instances( ti_status=ti_status, executor=executor, pickle_id=pickle_id, start_date=start_date, session=session, ) ti_status.executed_dag_run_dates.update(processed_dag_run_dates) @provide_session def _set_unfinished_dag_runs_to_failed(self, dag_runs, session=None): """ Go through the dag_runs and update the state based on the task_instance state. Then set DAG runs that are not finished to failed. :param dag_runs: DAG runs :param session: session :return: None """ for dag_run in dag_runs: dag_run.update_state() if dag_run.state not in State.finished: dag_run.set_state(DagRunState.FAILED) session.merge(dag_run) @provide_session def _execute(self, session=None): """ Initializes all components required to run a dag for a specified date range and calls helper method to execute the tasks. """ ti_status = BackfillJob._DagRunTaskStatus() start_date = self.bf_start_date # Get DagRun schedule between the start/end dates, which will turn into dag runs. dagrun_start_date = timezone.coerce_datetime(start_date) if self.bf_end_date is None: dagrun_end_date = pendulum.now(timezone.utc) else: dagrun_end_date = pendulum.instance(self.bf_end_date) dagrun_infos = list(self.dag.iter_dagrun_infos_between(dagrun_start_date, dagrun_end_date)) if self.run_backwards: tasks_that_depend_on_past = [t.task_id for t in self.dag.task_dict.values() if t.depends_on_past] if tasks_that_depend_on_past: raise AirflowException( f'You cannot backfill backwards because one or more ' f'tasks depend_on_past: {','.join(tasks_that_depend_on_past)}' ) dagrun_infos = dagrun_infos[::-1] if not dagrun_infos: if not self.run_at_least_once: self.log.info("No run dates were found for the given dates and dag interval.") return dagrun_infos = [DagRunInfo.interval(dagrun_start_date, dagrun_end_date)] dag_with_subdags_ids = [d.dag_id for d in self._get_dag_with_subdags()] running_dagruns = DagRun.find( dag_id=dag_with_subdags_ids, execution_start_date=self.bf_start_date, execution_end_date=self.bf_end_date, no_backfills=True, state=DagRunState.RUNNING, ) if running_dagruns: for run in running_dagruns: self.log.error( "Backfill cannot be created for DagRun %s in %s, as there's already %s in a RUNNING " "state.", run.run_id, run.execution_date.strftime("%Y-%m-%dT%H:%M:%S"), run.run_type, ) self.log.error( "Changing DagRun into BACKFILL would cause scheduler to lose track of executing " "tasks. Not changing DagRun type into BACKFILL, and trying insert another DagRun into " "database would cause database constraint violation for dag_id + execution_date " "combination. Please adjust backfill dates or wait for this DagRun to finish.", ) return # picklin' pickle_id = None if not self.donot_pickle and self.executor_class not in ( executor_constants.LOCAL_EXECUTOR, executor_constants.SEQUENTIAL_EXECUTOR, executor_constants.DASK_EXECUTOR, ): pickle = DagPickle(self.dag) session.add(pickle) session.commit() pickle_id = pickle.id executor = self.executor executor.job_id = "backfill" executor.start() ti_status.total_runs = len(dagrun_infos) # total dag runs in backfill try: remaining_dates = ti_status.total_runs while remaining_dates > 0: dagrun_infos_to_process = [ dagrun_info for dagrun_info in dagrun_infos if dagrun_info.logical_date not in ti_status.executed_dag_run_dates ] self._execute_dagruns( dagrun_infos=dagrun_infos_to_process, ti_status=ti_status, executor=executor, pickle_id=pickle_id, start_date=start_date, session=session, ) remaining_dates = ti_status.total_runs - len(ti_status.executed_dag_run_dates) err = self._collect_errors(ti_status=ti_status, session=session) if err: if not self.continue_on_failures or ti_status.deadlocked: raise BackfillUnfinished(err, ti_status) if remaining_dates > 0: self.log.info( "max_active_runs limit for dag %s has been reached " " - waiting for other dag runs to finish", self.dag_id, ) time.sleep(self.delay_on_limit_secs) except (KeyboardInterrupt, SystemExit): self.log.warning("Backfill terminated by user.") # TODO: we will need to terminate running task instances and set the # state to failed. self._set_unfinished_dag_runs_to_failed(ti_status.active_runs) finally: session.commit() executor.end() self.log.info("Backfill done. Exiting.") @provide_session def reset_state_for_orphaned_tasks(self, filter_by_dag_run=None, session=None): """ This function checks if there are any tasks in the dagrun (or all) that have a schedule or queued states but are not known by the executor. If it finds those it will reset the state to None so they will get picked up again. The batch option is for performance reasons as the queries are made in sequence. :param filter_by_dag_run: the dag_run we want to process, None if all :return: the number of TIs reset :rtype: int """ queued_tis = self.executor.queued_tasks # also consider running as the state might not have changed in the db yet running_tis = self.executor.running # Can't use an update here since it doesn't support joins. resettable_states = [TaskInstanceState.SCHEDULED, TaskInstanceState.QUEUED] if filter_by_dag_run is None: resettable_tis = ( session.query(TaskInstance) .join(TaskInstance.dag_run) .filter( DagRun.state == DagRunState.RUNNING, DagRun.run_type != DagRunType.BACKFILL_JOB, TaskInstance.state.in_(resettable_states), ) ).all() else: resettable_tis = filter_by_dag_run.get_task_instances(state=resettable_states, session=session) tis_to_reset = [ti for ti in resettable_tis if ti.key not in queued_tis and ti.key not in running_tis] if not tis_to_reset: return 0 def query(result, items): if not items: return result filter_for_tis = TaskInstance.filter_for_tis(items) reset_tis = ( session.query(TaskInstance) .filter(filter_for_tis, TaskInstance.state.in_(resettable_states)) .with_for_update() .all() ) for ti in reset_tis: ti.state = State.NONE session.merge(ti) return result + reset_tis reset_tis = helpers.reduce_in_chunks(query, tis_to_reset, [], self.max_tis_per_query) task_instance_str = '\n\t'.join(repr(x) for x in reset_tis) session.flush() self.log.info("Reset the following %s TaskInstances:\n\t%s", len(reset_tis), task_instance_str) return len(reset_tis)
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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 # # http://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. # import time from typing import TYPE_CHECKING, Any, Dict, Iterable, Iterator, List, Optional, Sequence, Set, Tuple import attr import pendulum from sqlalchemy.exc import OperationalError from sqlalchemy.orm.session import Session, make_transient from tabulate import tabulate from airflow import models from airflow.exceptions import ( AirflowException, BackfillUnfinished, DagConcurrencyLimitReached, NoAvailablePoolSlot, PoolNotFound, TaskConcurrencyLimitReached, ) from airflow.executors import executor_constants from airflow.jobs.base_job import BaseJob from airflow.models import DAG, DagPickle from airflow.models.dagrun import DagRun from airflow.models.taskinstance import TaskInstance, TaskInstanceKey from airflow.ti_deps.dep_context import DepContext from airflow.ti_deps.dependencies_deps import BACKFILL_QUEUED_DEPS from airflow.timetables.base import DagRunInfo from airflow.utils import helpers, timezone from airflow.utils.configuration import conf as airflow_conf, tmp_configuration_copy from airflow.utils.session import provide_session from airflow.utils.state import DagRunState, State, TaskInstanceState from airflow.utils.types import DagRunType if TYPE_CHECKING: from airflow.models.mappedoperator import MappedOperator class BackfillJob(BaseJob): """ A backfill job consists of a dag or subdag for a specific time range. It triggers a set of task instance runs, in the right order and lasts for as long as it takes for the set of task instance to be completed. """ STATES_COUNT_AS_RUNNING = (State.RUNNING, State.QUEUED) __mapper_args__ = {'polymorphic_identity': 'BackfillJob'} @attr.define class _DagRunTaskStatus: """ Internal status of the backfill job. This class is intended to be instantiated only within a BackfillJob instance and will track the execution of tasks, e.g. running, skipped, succeeded, failed, etc. Information about the dag runs related to the backfill job are also being tracked in this structure, .e.g finished runs, etc. Any other status related information related to the execution of dag runs / tasks can be included in this structure since it makes it easier to pass it around. :param to_run: Tasks to run in the backfill :param running: Maps running task instance key to task instance object :param skipped: Tasks that have been skipped :param succeeded: Tasks that have succeeded so far :param failed: Tasks that have failed :param not_ready: Tasks not ready for execution :param deadlocked: Deadlocked tasks :param active_runs: Active dag runs at a certain point in time :param executed_dag_run_dates: Datetime objects for the executed dag runs :param finished_runs: Number of finished runs so far :param total_runs: Number of total dag runs able to run """ to_run: Dict[TaskInstanceKey, TaskInstance] = attr.ib(factory=dict) running: Dict[TaskInstanceKey, TaskInstance] = attr.ib(factory=dict) skipped: Set[TaskInstanceKey] = attr.ib(factory=set) succeeded: Set[TaskInstanceKey] = attr.ib(factory=set) failed: Set[TaskInstanceKey] = attr.ib(factory=set) not_ready: Set[TaskInstanceKey] = attr.ib(factory=set) deadlocked: Set[TaskInstance] = attr.ib(factory=set) active_runs: List[DagRun] = attr.ib(factory=list) executed_dag_run_dates: Set[pendulum.DateTime] = attr.ib(factory=set) finished_runs: int = 0 total_runs: int = 0 def __init__( self, dag, start_date=None, end_date=None, mark_success=False, donot_pickle=False, ignore_first_depends_on_past=False, ignore_task_deps=False, pool=None, delay_on_limit_secs=1.0, verbose=False, conf=None, rerun_failed_tasks=False, run_backwards=False, run_at_least_once=False, continue_on_failures=False, *args, **kwargs, ): """ :param dag: DAG object. :param start_date: start date for the backfill date range. :param end_date: end date for the backfill date range. :param mark_success: flag whether to mark the task auto success. :param donot_pickle: whether pickle :param ignore_first_depends_on_past: whether to ignore depend on past :param ignore_task_deps: whether to ignore the task dependency :param pool: pool to backfill :param delay_on_limit_secs: :param verbose: :param conf: a dictionary which user could pass k-v pairs for backfill :param rerun_failed_tasks: flag to whether to auto rerun the failed task in backfill :param run_backwards: Whether to process the dates from most to least recent :param run_at_least_once: If true, always run the DAG at least once even if no logical run exists within the time range. :param args: :param kwargs: """ self.dag = dag self.dag_id = dag.dag_id self.bf_start_date = start_date self.bf_end_date = end_date self.mark_success = mark_success self.donot_pickle = donot_pickle self.ignore_first_depends_on_past = ignore_first_depends_on_past self.ignore_task_deps = ignore_task_deps self.pool = pool self.delay_on_limit_secs = delay_on_limit_secs self.verbose = verbose self.conf = conf self.rerun_failed_tasks = rerun_failed_tasks self.run_backwards = run_backwards self.run_at_least_once = run_at_least_once self.continue_on_failures = continue_on_failures super().__init__(*args, **kwargs) def _update_counters(self, ti_status, session=None): """ Updates the counters per state of the tasks that were running. Can re-add to tasks to run in case required. :param ti_status: the internal status of the backfill job tasks """ tis_to_be_scheduled = [] refreshed_tis = [] TI = TaskInstance filter_for_tis = TI.filter_for_tis(list(ti_status.running.values())) if filter_for_tis is not None: refreshed_tis = session.query(TI).filter(filter_for_tis).all() for ti in refreshed_tis: # Here we remake the key by subtracting 1 to match in memory information reduced_key = ti.key.reduced if ti.state == TaskInstanceState.SUCCESS: ti_status.succeeded.add(reduced_key) self.log.debug("Task instance %s succeeded. Don't rerun.", ti) ti_status.running.pop(reduced_key) continue if ti.state == TaskInstanceState.SKIPPED: ti_status.skipped.add(reduced_key) self.log.debug("Task instance %s skipped. Don't rerun.", ti) ti_status.running.pop(reduced_key) continue if ti.state == TaskInstanceState.FAILED: self.log.error("Task instance %s failed", ti) ti_status.failed.add(reduced_key) ti_status.running.pop(reduced_key) continue # special case: if the task needs to run again put it back if ti.state == TaskInstanceState.UP_FOR_RETRY: self.log.warning("Task instance %s is up for retry", ti) ti_status.running.pop(reduced_key) ti_status.to_run[ti.key] = ti # special case: if the task needs to be rescheduled put it back elif ti.state == TaskInstanceState.UP_FOR_RESCHEDULE: self.log.warning("Task instance %s is up for reschedule", ti) # During handling of reschedule state in ti._handle_reschedule, try number is reduced # by one, so we should not use reduced_key to avoid key error ti_status.running.pop(ti.key) ti_status.to_run[ti.key] = ti # special case: The state of the task can be set to NONE by the task itself # when it reaches concurrency limits. It could also happen when the state # is changed externally, e.g. by clearing tasks from the ui. We need to cover # for that as otherwise those tasks would fall outside of the scope of # the backfill suddenly. elif ti.state == State.NONE: self.log.warning( "FIXME: task instance %s state was set to none externally or " "reaching concurrency limits. Re-adding task to queue.", ti, ) tis_to_be_scheduled.append(ti) ti_status.running.pop(reduced_key) ti_status.to_run[ti.key] = ti # Batch schedule of task instances if tis_to_be_scheduled: filter_for_tis = TI.filter_for_tis(tis_to_be_scheduled) session.query(TI).filter(filter_for_tis).update( values={TI.state: TaskInstanceState.SCHEDULED}, synchronize_session=False ) session.flush() def _manage_executor_state( self, running, session ) -> Iterator[Tuple["MappedOperator", str, Sequence[TaskInstance]]]: """ Checks if the executor agrees with the state of task instances that are running. Expands downstream mapped tasks when necessary :param running: dict of key, task to verify :return: An iterable of expanded TaskInstance per MappedTask """ from airflow.models.mappedoperator import MappedOperator executor = self.executor # TODO: query all instead of refresh from db for key, value in list(executor.get_event_buffer().items()): state, info = value if key not in running: self.log.warning("%s state %s not in running=%s", key, state, running.values()) continue ti = running[key] ti.refresh_from_db() self.log.debug("Executor state: %s task %s", state, ti) if ( state in (TaskInstanceState.FAILED, TaskInstanceState.SUCCESS) and ti.state in self.STATES_COUNT_AS_RUNNING ): msg = ( f"Executor reports task instance {ti} finished ({state}) although the task says its " f"{ti.state}. Was the task killed externally? Info: {info}" ) self.log.error(msg) ti.handle_failure_with_callback(error=msg) continue if ti.state not in self.STATES_COUNT_AS_RUNNING: for node in ti.task.mapped_dependants(): assert isinstance(node, MappedOperator) yield node, ti.run_id, node.expand_mapped_task(ti.run_id, session=session) @provide_session def _get_dag_run(self, dagrun_info: DagRunInfo, dag: DAG, session: Session = None): """ Returns a dag run for the given run date, which will be matched to an existing dag run if available or create a new dag run otherwise. If the max_active_runs limit is reached, this function will return None. :param dagrun_info: Schedule information for the dag run :param dag: DAG :param session: the database session object :return: a DagRun in state RUNNING or None """ run_date = dagrun_info.logical_date # consider max_active_runs but ignore when running subdags respect_dag_max_active_limit = bool(dag.timetable.can_run and not dag.is_subdag) current_active_dag_count = dag.get_num_active_runs(external_trigger=False) # check if we are scheduling on top of a already existing dag_run # we could find a "scheduled" run instead of a "backfill" runs = DagRun.find(dag_id=dag.dag_id, execution_date=run_date, session=session) run: Optional[DagRun] if runs: run = runs[0] if run.state == DagRunState.RUNNING: respect_dag_max_active_limit = False # Fixes --conf overwrite for backfills with already existing DagRuns run.conf = self.conf or {} else: run = None # enforce max_active_runs limit for dag, special cases already # handled by respect_dag_max_active_limit if respect_dag_max_active_limit and current_active_dag_count >= dag.max_active_runs: return None run = run or dag.create_dagrun( execution_date=run_date, data_interval=dagrun_info.data_interval, start_date=timezone.utcnow(), state=DagRunState.RUNNING, external_trigger=False, session=session, conf=self.conf, run_type=DagRunType.BACKFILL_JOB, creating_job_id=self.id, ) # set required transient field run.dag = dag # explicitly mark as backfill and running run.state = DagRunState.RUNNING run.run_type = DagRunType.BACKFILL_JOB run.verify_integrity(session=session) return run @provide_session def _task_instances_for_dag_run(self, dag_run, session=None): """ Returns a map of task instance key to task instance object for the tasks to run in the given dag run. :param dag_run: the dag run to get the tasks from :param session: the database session object """ tasks_to_run = {} if dag_run is None: return tasks_to_run # check if we have orphaned tasks self.reset_state_for_orphaned_tasks(filter_by_dag_run=dag_run, session=session) # for some reason if we don't refresh the reference to run is lost dag_run.refresh_from_db() make_transient(dag_run) try: for ti in dag_run.get_task_instances(): # all tasks part of the backfill are scheduled to run if ti.state == State.NONE: ti.set_state(TaskInstanceState.SCHEDULED, session=session) if ti.state != TaskInstanceState.REMOVED: tasks_to_run[ti.key] = ti session.commit() except Exception: session.rollback() raise return tasks_to_run def _log_progress(self, ti_status): self.log.info( '[backfill progress] | finished run %s of %s | tasks waiting: %s | succeeded: %s | ' 'running: %s | failed: %s | skipped: %s | deadlocked: %s | not ready: %s', ti_status.finished_runs, ti_status.total_runs, len(ti_status.to_run), len(ti_status.succeeded), len(ti_status.running), len(ti_status.failed), len(ti_status.skipped), len(ti_status.deadlocked), len(ti_status.not_ready), ) self.log.debug("Finished dag run loop iteration. Remaining tasks %s", ti_status.to_run.values()) @provide_session def _process_backfill_task_instances( self, ti_status, executor, pickle_id, start_date=None, session=None, ): """ Process a set of task instances from a set of dag runs. Special handling is done to account for different task instance states that could be present when running them in a backfill process. :param ti_status: the internal status of the job :param executor: the executor to run the task instances :param pickle_id: the pickle_id if dag is pickled, None otherwise :param start_date: the start date of the backfill job :param session: the current session object :return: the list of execution_dates for the finished dag runs :rtype: list """ executed_run_dates = [] is_unit_test = airflow_conf.getboolean('core', 'unit_test_mode') while (len(ti_status.to_run) > 0 or len(ti_status.running) > 0) and len(ti_status.deadlocked) == 0: self.log.debug("*** Clearing out not_ready list ***") ti_status.not_ready.clear() # we need to execute the tasks bottom to top # or leaf to root, as otherwise tasks might be # determined deadlocked while they are actually # waiting for their upstream to finish def _per_task_process(key, ti: TaskInstance, session=None): ti.refresh_from_db(lock_for_update=True, session=session) task = self.dag.get_task(ti.task_id, include_subdags=True) ti.task = task self.log.debug("Task instance to run %s state %s", ti, ti.state) # The task was already marked successful or skipped by a # different Job. Don't rerun it. if ti.state == TaskInstanceState.SUCCESS: ti_status.succeeded.add(key) self.log.debug("Task instance %s succeeded. Don't rerun.", ti) ti_status.to_run.pop(key) if key in ti_status.running: ti_status.running.pop(key) return elif ti.state == TaskInstanceState.SKIPPED: ti_status.skipped.add(key) self.log.debug("Task instance %s skipped. Don't rerun.", ti) ti_status.to_run.pop(key) if key in ti_status.running: ti_status.running.pop(key) return # guard against externally modified tasks instances or # in case max concurrency has been reached at task runtime elif ti.state == State.NONE: self.log.warning( "FIXME: Task instance %s state was set to None externally. This should not happen", ti ) ti.set_state(TaskInstanceState.SCHEDULED, session=session) if self.rerun_failed_tasks: # Rerun failed tasks or upstreamed failed tasks if ti.state in (TaskInstanceState.FAILED, TaskInstanceState.UPSTREAM_FAILED): self.log.error("Task instance %s with state %s", ti, ti.state) if key in ti_status.running: ti_status.running.pop(key) # Reset the failed task in backfill to scheduled state ti.set_state(TaskInstanceState.SCHEDULED, session=session) else: # Default behaviour which works for subdag. if ti.state in (TaskInstanceState.FAILED, TaskInstanceState.UPSTREAM_FAILED): self.log.error("Task instance %s with state %s", ti, ti.state) ti_status.failed.add(key) ti_status.to_run.pop(key) if key in ti_status.running: ti_status.running.pop(key) return if self.ignore_first_depends_on_past: dagrun = ti.get_dagrun(session=session) ignore_depends_on_past = dagrun.execution_date == (start_date or ti.start_date) else: ignore_depends_on_past = False backfill_context = DepContext( deps=BACKFILL_QUEUED_DEPS, ignore_depends_on_past=ignore_depends_on_past, ignore_task_deps=self.ignore_task_deps, flag_upstream_failed=True, ) # Is the task runnable? -- then run it # the dependency checker can change states of tis if ti.are_dependencies_met( dep_context=backfill_context, session=session, verbose=self.verbose ): if executor.has_task(ti): self.log.debug("Task Instance %s already in executor waiting for queue to clear", ti) else: self.log.debug('Sending %s to executor', ti) # Skip scheduled state, we are executing immediately ti.state = TaskInstanceState.QUEUED ti.queued_by_job_id = self.id ti.queued_dttm = timezone.utcnow() session.merge(ti) try: session.commit() except OperationalError: self.log.exception("Failed to commit task state change due to operational error") session.rollback() # early exit so the outer loop can retry return cfg_path = None if self.executor_class in ( executor_constants.LOCAL_EXECUTOR, executor_constants.SEQUENTIAL_EXECUTOR, ): cfg_path = tmp_configuration_copy() executor.queue_task_instance( ti, mark_success=self.mark_success, pickle_id=pickle_id, ignore_task_deps=self.ignore_task_deps, ignore_depends_on_past=ignore_depends_on_past, pool=self.pool, cfg_path=cfg_path, ) ti_status.running[key] = ti ti_status.to_run.pop(key) return if ti.state == TaskInstanceState.UPSTREAM_FAILED: self.log.error("Task instance %s upstream failed", ti) ti_status.failed.add(key) ti_status.to_run.pop(key) if key in ti_status.running: ti_status.running.pop(key) return # special case if ti.state == TaskInstanceState.UP_FOR_RETRY: self.log.debug("Task instance %s retry period not expired yet", ti) if key in ti_status.running: ti_status.running.pop(key) ti_status.to_run[key] = ti return # special case if ti.state == TaskInstanceState.UP_FOR_RESCHEDULE: self.log.debug("Task instance %s reschedule period not expired yet", ti) if key in ti_status.running: ti_status.running.pop(key) ti_status.to_run[key] = ti return # all remaining tasks self.log.debug('Adding %s to not_ready', ti) ti_status.not_ready.add(key) try: for task in self.dag.topological_sort(include_subdag_tasks=True): for key, ti in list(ti_status.to_run.items()): if task.task_id != ti.task_id: continue pool = session.query(models.Pool).filter(models.Pool.pool == task.pool).first() if not pool: raise PoolNotFound(f'Unknown pool: {task.pool}') open_slots = pool.open_slots(session=session) if open_slots <= 0: raise NoAvailablePoolSlot( f"Not scheduling since there are {open_slots} open slots in pool {task.pool}" ) num_running_task_instances_in_dag = DAG.get_num_task_instances( self.dag_id, states=self.STATES_COUNT_AS_RUNNING, session=session, ) if num_running_task_instances_in_dag >= self.dag.max_active_tasks: raise DagConcurrencyLimitReached( "Not scheduling since DAG max_active_tasks limit is reached." ) if task.max_active_tis_per_dag: num_running_task_instances_in_task = DAG.get_num_task_instances( dag_id=self.dag_id, task_ids=[task.task_id], states=self.STATES_COUNT_AS_RUNNING, session=session, ) if num_running_task_instances_in_task >= task.max_active_tis_per_dag: raise TaskConcurrencyLimitReached( "Not scheduling since Task concurrency limit is reached." ) _per_task_process(key, ti, session) session.commit() except (NoAvailablePoolSlot, DagConcurrencyLimitReached, TaskConcurrencyLimitReached) as e: self.log.debug(e) self.heartbeat(only_if_necessary=is_unit_test) # execute the tasks in the queue executor.heartbeat() # If the set of tasks that aren't ready ever equals the set of # tasks to run and there are no running tasks then the backfill # is deadlocked if ( ti_status.not_ready and ti_status.not_ready == set(ti_status.to_run) and len(ti_status.running) == 0 ): self.log.warning("Deadlock discovered for ti_status.to_run=%s", ti_status.to_run.values()) ti_status.deadlocked.update(ti_status.to_run.values()) ti_status.to_run.clear() # check executor state -- and expand any mapped TIs for node, run_id, mapped_tis in self._manage_executor_state(ti_status.running, session): def to_keep(key: TaskInstanceKey) -> bool: if key.dag_id != node.dag_id or key.task_id != node.task_id or key.run_id != run_id: # For another Dag/Task/Run -- don't remove return True return False # remove the old unmapped TIs for node -- they have been replaced with the mapped TIs ti_status.to_run = {key: ti for (key, ti) in ti_status.to_run.items() if to_keep(key)} ti_status.to_run.update({ti.key: ti for ti in mapped_tis}) # update the task counters self._update_counters(ti_status=ti_status, session=session) session.commit() # update dag run state _dag_runs = ti_status.active_runs[:] for run in _dag_runs: run.update_state(session=session) if run.state in State.finished: ti_status.finished_runs += 1 ti_status.active_runs.remove(run) executed_run_dates.append(run.execution_date) self._log_progress(ti_status) session.commit() # return updated status return executed_run_dates @provide_session def _collect_errors(self, ti_status: _DagRunTaskStatus, session=None): def tabulate_ti_keys_set(ti_keys: Iterable[TaskInstanceKey]) -> str: # Sorting by execution date first sorted_ti_keys: Any = sorted( ti_keys, key=lambda ti_key: ( ti_key.run_id, ti_key.dag_id, ti_key.task_id, ti_key.map_index, ti_key.try_number, ), ) if all(key.map_index == -1 for key in ti_keys): headers = ["DAG ID", "Task ID", "Run ID", "Try number"] sorted_ti_keys = map(lambda k: k[0:4], sorted_ti_keys) else: headers = ["DAG ID", "Task ID", "Run ID", "Map Index", "Try number"] return tabulate(sorted_ti_keys, headers=headers) err = '' if ti_status.failed: err += "Some task instances failed:\n" err += tabulate_ti_keys_set(ti_status.failed) if ti_status.deadlocked: err += 'BackfillJob is deadlocked.' deadlocked_depends_on_past = any( t.are_dependencies_met( dep_context=DepContext(ignore_depends_on_past=False), session=session, verbose=self.verbose, ) != t.are_dependencies_met( dep_context=DepContext(ignore_depends_on_past=True), session=session, verbose=self.verbose ) for t in ti_status.deadlocked ) if deadlocked_depends_on_past: err += ( 'Some of the deadlocked tasks were unable to run because ' 'of "depends_on_past" relationships. Try running the ' 'backfill with the option ' '"ignore_first_depends_on_past=True" or passing "-I" at ' 'the command line.' ) err += '\nThese tasks have succeeded:\n' err += tabulate_ti_keys_set(ti_status.succeeded) err += '\n\nThese tasks are running:\n' err += tabulate_ti_keys_set(ti_status.running) err += '\n\nThese tasks have failed:\n' err += tabulate_ti_keys_set(ti_status.failed) err += '\n\nThese tasks are skipped:\n' err += tabulate_ti_keys_set(ti_status.skipped) err += '\n\nThese tasks are deadlocked:\n' err += tabulate_ti_keys_set([ti.key for ti in ti_status.deadlocked]) return err def _get_dag_with_subdags(self): return [self.dag] + self.dag.subdags @provide_session def _execute_dagruns(self, dagrun_infos, ti_status, executor, pickle_id, start_date, session=None): """ Computes the dag runs and their respective task instances for the given run dates and executes the task instances. Returns a list of execution dates of the dag runs that were executed. :param dagrun_infos: Schedule information for dag runs :param ti_status: internal BackfillJob status structure to tis track progress :param executor: the executor to use, it must be previously started :param pickle_id: numeric id of the pickled dag, None if not pickled :param start_date: backfill start date :param session: the current session object """ for dagrun_info in dagrun_infos: for dag in self._get_dag_with_subdags(): dag_run = self._get_dag_run(dagrun_info, dag, session=session) tis_map = self._task_instances_for_dag_run(dag_run, session=session) if dag_run is None: continue ti_status.active_runs.append(dag_run) ti_status.to_run.update(tis_map or {}) processed_dag_run_dates = self._process_backfill_task_instances( ti_status=ti_status, executor=executor, pickle_id=pickle_id, start_date=start_date, session=session, ) ti_status.executed_dag_run_dates.update(processed_dag_run_dates) @provide_session def _set_unfinished_dag_runs_to_failed(self, dag_runs, session=None): """ Go through the dag_runs and update the state based on the task_instance state. Then set DAG runs that are not finished to failed. :param dag_runs: DAG runs :param session: session :return: None """ for dag_run in dag_runs: dag_run.update_state() if dag_run.state not in State.finished: dag_run.set_state(DagRunState.FAILED) session.merge(dag_run) @provide_session def _execute(self, session=None): """ Initializes all components required to run a dag for a specified date range and calls helper method to execute the tasks. """ ti_status = BackfillJob._DagRunTaskStatus() start_date = self.bf_start_date # Get DagRun schedule between the start/end dates, which will turn into dag runs. dagrun_start_date = timezone.coerce_datetime(start_date) if self.bf_end_date is None: dagrun_end_date = pendulum.now(timezone.utc) else: dagrun_end_date = pendulum.instance(self.bf_end_date) dagrun_infos = list(self.dag.iter_dagrun_infos_between(dagrun_start_date, dagrun_end_date)) if self.run_backwards: tasks_that_depend_on_past = [t.task_id for t in self.dag.task_dict.values() if t.depends_on_past] if tasks_that_depend_on_past: raise AirflowException( f'You cannot backfill backwards because one or more ' f'tasks depend_on_past: {",".join(tasks_that_depend_on_past)}' ) dagrun_infos = dagrun_infos[::-1] if not dagrun_infos: if not self.run_at_least_once: self.log.info("No run dates were found for the given dates and dag interval.") return dagrun_infos = [DagRunInfo.interval(dagrun_start_date, dagrun_end_date)] dag_with_subdags_ids = [d.dag_id for d in self._get_dag_with_subdags()] running_dagruns = DagRun.find( dag_id=dag_with_subdags_ids, execution_start_date=self.bf_start_date, execution_end_date=self.bf_end_date, no_backfills=True, state=DagRunState.RUNNING, ) if running_dagruns: for run in running_dagruns: self.log.error( "Backfill cannot be created for DagRun %s in %s, as there's already %s in a RUNNING " "state.", run.run_id, run.execution_date.strftime("%Y-%m-%dT%H:%M:%S"), run.run_type, ) self.log.error( "Changing DagRun into BACKFILL would cause scheduler to lose track of executing " "tasks. Not changing DagRun type into BACKFILL, and trying insert another DagRun into " "database would cause database constraint violation for dag_id + execution_date " "combination. Please adjust backfill dates or wait for this DagRun to finish.", ) return # picklin' pickle_id = None if not self.donot_pickle and self.executor_class not in ( executor_constants.LOCAL_EXECUTOR, executor_constants.SEQUENTIAL_EXECUTOR, executor_constants.DASK_EXECUTOR, ): pickle = DagPickle(self.dag) session.add(pickle) session.commit() pickle_id = pickle.id executor = self.executor executor.job_id = "backfill" executor.start() ti_status.total_runs = len(dagrun_infos) # total dag runs in backfill try: remaining_dates = ti_status.total_runs while remaining_dates > 0: dagrun_infos_to_process = [ dagrun_info for dagrun_info in dagrun_infos if dagrun_info.logical_date not in ti_status.executed_dag_run_dates ] self._execute_dagruns( dagrun_infos=dagrun_infos_to_process, ti_status=ti_status, executor=executor, pickle_id=pickle_id, start_date=start_date, session=session, ) remaining_dates = ti_status.total_runs - len(ti_status.executed_dag_run_dates) err = self._collect_errors(ti_status=ti_status, session=session) if err: if not self.continue_on_failures or ti_status.deadlocked: raise BackfillUnfinished(err, ti_status) if remaining_dates > 0: self.log.info( "max_active_runs limit for dag %s has been reached " " - waiting for other dag runs to finish", self.dag_id, ) time.sleep(self.delay_on_limit_secs) except (KeyboardInterrupt, SystemExit): self.log.warning("Backfill terminated by user.") # TODO: we will need to terminate running task instances and set the # state to failed. self._set_unfinished_dag_runs_to_failed(ti_status.active_runs) finally: session.commit() executor.end() self.log.info("Backfill done. Exiting.") @provide_session def reset_state_for_orphaned_tasks(self, filter_by_dag_run=None, session=None): """ This function checks if there are any tasks in the dagrun (or all) that have a schedule or queued states but are not known by the executor. If it finds those it will reset the state to None so they will get picked up again. The batch option is for performance reasons as the queries are made in sequence. :param filter_by_dag_run: the dag_run we want to process, None if all :return: the number of TIs reset :rtype: int """ queued_tis = self.executor.queued_tasks # also consider running as the state might not have changed in the db yet running_tis = self.executor.running # Can't use an update here since it doesn't support joins. resettable_states = [TaskInstanceState.SCHEDULED, TaskInstanceState.QUEUED] if filter_by_dag_run is None: resettable_tis = ( session.query(TaskInstance) .join(TaskInstance.dag_run) .filter( DagRun.state == DagRunState.RUNNING, DagRun.run_type != DagRunType.BACKFILL_JOB, TaskInstance.state.in_(resettable_states), ) ).all() else: resettable_tis = filter_by_dag_run.get_task_instances(state=resettable_states, session=session) tis_to_reset = [ti for ti in resettable_tis if ti.key not in queued_tis and ti.key not in running_tis] if not tis_to_reset: return 0 def query(result, items): if not items: return result filter_for_tis = TaskInstance.filter_for_tis(items) reset_tis = ( session.query(TaskInstance) .filter(filter_for_tis, TaskInstance.state.in_(resettable_states)) .with_for_update() .all() ) for ti in reset_tis: ti.state = State.NONE session.merge(ti) return result + reset_tis reset_tis = helpers.reduce_in_chunks(query, tis_to_reset, [], self.max_tis_per_query) task_instance_str = '\n\t'.join(repr(x) for x in reset_tis) session.flush() self.log.info("Reset the following %s TaskInstances:\n\t%s", len(reset_tis), task_instance_str) return len(reset_tis)
# Copyright 2020 Pulser Development Team # # 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 # # http://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. from __future__ import annotations from collections.abc import Callable from functools import partialmethod from itertools import chain import inspect import operator import warnings from typing import Any, Union, TYPE_CHECKING from pulser.json.utils import obj_to_dict from pulser.parametrized import Parametrized if TYPE_CHECKING: from pulser.parametrized import Variable # pragma: no cover # Available operations on parametrized objects with OpSupport reversible_ops = [ "__add__", "__sub__", "__mul__", "__truediv__", "__floordiv__", "__pow__", "__mod__" ] class OpSupport: """Methods for supporting operators on parametrized objects.""" def _do_op(self, op_name: str, other: Union[int, float]) -> ParamObj: return ParamObj(getattr(operator, op_name), self, other) def _do_rop(self, op_name: str, other: Union[int, float]) -> ParamObj: return ParamObj(getattr(operator, op_name), other, self) def __neg__(self) -> ParamObj: return ParamObj(operator.neg, self) def __abs__(self) -> ParamObj: return ParamObj(operator.abs, self) # Inject operator magic methods into OpSupport for method in reversible_ops: rmethod = "__r" + method[2:] setattr(OpSupport, method, partialmethod(OpSupport._do_op, method)) setattr(OpSupport, rmethod, partialmethod(OpSupport._do_rop, method)) class ParamObj(Parametrized, OpSupport): def __init__(self, cls: Callable, *args: Any, **kwargs: Any) -> None: """Holds a call to a given class. When called, a ParamObj instance returns `cls(*args, **kwargs)`. Args: cls (callable): The object to call. Usually it's a class that's instantiated when called. args: The args for calling `cls`. kwargs: The kwargs for calling `cls`. """ self.cls = cls self._variables: dict[str, Variable] = {} if isinstance(self.cls, Parametrized): self._variables.update(self.cls.variables) for x in chain(args, kwargs.values()): if isinstance(x, Parametrized): self._variables.update(x.variables) self.args = args self.kwargs = kwargs self._instance = None self._vars_state: dict[str, int] = {} @property def variables(self) -> dict[str, Variable]: return self._variables def build(self): """Builds the object with its variables last assigned values.""" vars_state = {key: var._count for key, var in self._variables.items()} if vars_state != self._vars_state: self._vars_state = vars_state # Builds all Parametrized arguments before feeding them to cls args_ = [arg.build() if isinstance(arg, Parametrized) else arg for arg in self.args] kwargs_ = {key: val.build() if isinstance(val, Parametrized) else val for key, val in self.kwargs.items()} obj = (self.cls.build() if isinstance(self.cls, ParamObj) else self.cls) self._instance = obj(*args_, **kwargs_) return self._instance def _to_dict(self) -> dict[str, Any]: def class_to_dict(cls): return obj_to_dict(self, _build=False, _name=cls.__name__, _module=cls.__module__) args = list(self.args) if isinstance(self.cls, Parametrized): cls_dict = self.cls._to_dict() elif (hasattr(args[0], self.cls.__name__) and inspect.isfunction(self.cls)): # Check for parametrized methods if inspect.isclass(self.args[0]): # classmethod cls_dict = obj_to_dict(self, _build=False, _name=self.cls.__name__, _module=self.args[0].__module__, _submodule=self.args[0].__name__) args[0] = class_to_dict(self.args[0]) else: raise NotImplementedError("Instance or static method " "serialization is not supported.") else: cls_dict = class_to_dict(self.cls) return obj_to_dict(self, cls_dict, *args, **self.kwargs) def __call__(self, *args: Any, **kwargs: Any) -> ParamObj: obj = ParamObj(self, *args, **kwargs) warnings.warn("Calls to methods of parametrized objects are only " "executed if they serve as arguments of other " "parametrized objects that are themselves built. If this" f" is not the case, the call to {obj} will not be " "executed upon sequence building.") return obj def __getattr__(self, name: str) -> ParamObj: if hasattr(self.cls, name): return ParamObj(getattr, self, name) else: raise AttributeError(f"No attribute named '{name}' in {self}.") def __str__(self) -> str: args = [str(a) for a in self.args] kwargs = [f"{key}={str(value)}" for key, value in self.kwargs.items()] if isinstance(self.cls, Parametrized): name = str(self.cls) elif (hasattr(self.args[0], self.cls.__name__) and inspect.isfunction(self.cls) and inspect.isclass(self.args[0])): name = f"{self.args[0].__name__}.{self.cls.__name__}" args = args[1:] else: name = self.cls.__name__ return f"{name}({", ".join(args+kwargs)})"
# Copyright 2020 Pulser Development Team # # 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 # # http://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. from __future__ import annotations from collections.abc import Callable from functools import partialmethod from itertools import chain import inspect import operator import warnings from typing import Any, Union, TYPE_CHECKING from pulser.json.utils import obj_to_dict from pulser.parametrized import Parametrized if TYPE_CHECKING: from pulser.parametrized import Variable # pragma: no cover # Available operations on parametrized objects with OpSupport reversible_ops = [ "__add__", "__sub__", "__mul__", "__truediv__", "__floordiv__", "__pow__", "__mod__" ] class OpSupport: """Methods for supporting operators on parametrized objects.""" def _do_op(self, op_name: str, other: Union[int, float]) -> ParamObj: return ParamObj(getattr(operator, op_name), self, other) def _do_rop(self, op_name: str, other: Union[int, float]) -> ParamObj: return ParamObj(getattr(operator, op_name), other, self) def __neg__(self) -> ParamObj: return ParamObj(operator.neg, self) def __abs__(self) -> ParamObj: return ParamObj(operator.abs, self) # Inject operator magic methods into OpSupport for method in reversible_ops: rmethod = "__r" + method[2:] setattr(OpSupport, method, partialmethod(OpSupport._do_op, method)) setattr(OpSupport, rmethod, partialmethod(OpSupport._do_rop, method)) class ParamObj(Parametrized, OpSupport): def __init__(self, cls: Callable, *args: Any, **kwargs: Any) -> None: """Holds a call to a given class. When called, a ParamObj instance returns `cls(*args, **kwargs)`. Args: cls (callable): The object to call. Usually it's a class that's instantiated when called. args: The args for calling `cls`. kwargs: The kwargs for calling `cls`. """ self.cls = cls self._variables: dict[str, Variable] = {} if isinstance(self.cls, Parametrized): self._variables.update(self.cls.variables) for x in chain(args, kwargs.values()): if isinstance(x, Parametrized): self._variables.update(x.variables) self.args = args self.kwargs = kwargs self._instance = None self._vars_state: dict[str, int] = {} @property def variables(self) -> dict[str, Variable]: return self._variables def build(self): """Builds the object with its variables last assigned values.""" vars_state = {key: var._count for key, var in self._variables.items()} if vars_state != self._vars_state: self._vars_state = vars_state # Builds all Parametrized arguments before feeding them to cls args_ = [arg.build() if isinstance(arg, Parametrized) else arg for arg in self.args] kwargs_ = {key: val.build() if isinstance(val, Parametrized) else val for key, val in self.kwargs.items()} obj = (self.cls.build() if isinstance(self.cls, ParamObj) else self.cls) self._instance = obj(*args_, **kwargs_) return self._instance def _to_dict(self) -> dict[str, Any]: def class_to_dict(cls): return obj_to_dict(self, _build=False, _name=cls.__name__, _module=cls.__module__) args = list(self.args) if isinstance(self.cls, Parametrized): cls_dict = self.cls._to_dict() elif (hasattr(args[0], self.cls.__name__) and inspect.isfunction(self.cls)): # Check for parametrized methods if inspect.isclass(self.args[0]): # classmethod cls_dict = obj_to_dict(self, _build=False, _name=self.cls.__name__, _module=self.args[0].__module__, _submodule=self.args[0].__name__) args[0] = class_to_dict(self.args[0]) else: raise NotImplementedError("Instance or static method " "serialization is not supported.") else: cls_dict = class_to_dict(self.cls) return obj_to_dict(self, cls_dict, *args, **self.kwargs) def __call__(self, *args: Any, **kwargs: Any) -> ParamObj: obj = ParamObj(self, *args, **kwargs) warnings.warn("Calls to methods of parametrized objects are only " "executed if they serve as arguments of other " "parametrized objects that are themselves built. If this" f" is not the case, the call to {obj} will not be " "executed upon sequence building.") return obj def __getattr__(self, name: str) -> ParamObj: if hasattr(self.cls, name): return ParamObj(getattr, self, name) else: raise AttributeError(f"No attribute named '{name}' in {self}.") def __str__(self) -> str: args = [str(a) for a in self.args] kwargs = [f"{key}={str(value)}" for key, value in self.kwargs.items()] if isinstance(self.cls, Parametrized): name = str(self.cls) elif (hasattr(self.args[0], self.cls.__name__) and inspect.isfunction(self.cls) and inspect.isclass(self.args[0])): name = f"{self.args[0].__name__}.{self.cls.__name__}" args = args[1:] else: name = self.cls.__name__ return f"{name}({', '.join(args+kwargs)})"
"""Test asyncpraw.models.subreddit.""" import socket import sys from asyncio import TimeoutError from os.path import abspath, dirname, join import pytest from aiohttp import ClientResponse from aiohttp.http_websocket import WebSocketError from asyncprawcore import BadRequest, Forbidden, NotFound, TooLarge from asynctest import mock from asyncpraw.const import PNG_HEADER from asyncpraw.exceptions import ( ClientException, InvalidFlairTemplateID, RedditAPIException, TooLargeMediaException, WebSocketException, ) from asyncpraw.models import ( Comment, InlineGif, InlineImage, InlineVideo, ListingGenerator, ModAction, ModmailAction, ModmailConversation, ModmailMessage, Redditor, Stylesheet, Submission, Subreddit, SubredditMessage, WikiPage, ) from ... import IntegrationTest def image_path(name): test_dir = abspath(dirname(sys.modules[__name__].__file__)) return abspath(join(test_dir, "..", "..", "files", name)) class WebsocketMock: POST_URL = "https://reddit.com/r/<TEST_SUBREDDIT>/comments/{}/test_title/" @classmethod def make_dict(cls, post_id): return {"payload": {"redirect": cls.POST_URL.format(post_id)}} def __init__(self, *post_ids): self.post_ids = post_ids self.i = -1 async def __aenter__(self): return self async def __aexit__(self, exc_type, exc_val, exc_tb): pass async def receive_json(self): if not self.post_ids: raise WebSocketError(None, None) assert 0 <= self.i + 1 < len(self.post_ids) self.i += 1 return self.make_dict(self.post_ids[self.i]) class TestSubreddit(IntegrationTest): @mock.patch("asyncio.sleep", return_value=None) async def test_create(self, _): self.reddit.read_only = False new_name = pytest.placeholders.test_subreddit with self.use_cassette(): subreddit = await self.reddit.subreddit.create( name=new_name, title="Sub", link_type="any", subreddit_type="public", wikimode="disabled", wiki_edit_age=0, wiki_edit_karma=0, comment_score_hide_mins=0, ) assert subreddit.display_name == new_name assert subreddit.submission_type == "any" async def test_create__exists(self): self.reddit.read_only = False with self.use_cassette(): with pytest.raises(RedditAPIException) as excinfo: await self.reddit.subreddit.create( "redditdev", title="redditdev", link_type="any", subreddit_type="public", wikimode="disabled", ) assert excinfo.value.items[0].error_type == "SUBREDDIT_EXISTS" async def test_create__invalid_parameter(self): self.reddit.read_only = False with self.use_cassette(): with pytest.raises(RedditAPIException) as excinfo: # Supplying invalid setting for link_type await self.reddit.subreddit.create( name="PRAW_iavynavff2", title="sub", link_type="abcd", subreddit_type="public", wikimode="disabled", ) assert excinfo.value.items[0].error_type == "INVALID_OPTION" async def test_create__missing_parameter(self): self.reddit.read_only = False with self.use_cassette(): with pytest.raises(RedditAPIException) as excinfo: # Not supplying required field wiki_edit_age. await self.reddit.subreddit.create( name="PRAW_iavynavff3", title=None, link_type="any", subreddit_type="public", wikimode="disabled", wiki_edit_karma=0, comment_score_hide_mins=0, ) assert excinfo.value.items[0].error_type == "BAD_NUMBER" @mock.patch("asyncio.sleep", return_value=None) async def test_message(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) await subreddit.message("Test from Async PRAW", message="Test content") @mock.patch("asyncio.sleep", return_value=None) async def test_post_requirements(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) data = await subreddit.post_requirements() tags = [ "domain_blacklist", "body_restriction_policy", "domain_whitelist", "title_regexes", "body_blacklisted_strings", "body_required_strings", "title_text_min_length", "is_flair_required", "title_text_max_length", "body_regexes", "link_repost_age", "body_text_min_length", "link_restriction_policy", "body_text_max_length", "title_required_strings", "title_blacklisted_strings", "guidelines_text", "guidelines_display_policy", ] assert list(data) == tags async def test_random(self): with self.use_cassette(): subreddit = await self.reddit.subreddit("pics") submissions = [ await subreddit.random(), await subreddit.random(), await subreddit.random(), await subreddit.random(), ] assert len(submissions) == len(set(submissions)) async def test_random__returns_none(self): with self.use_cassette(): subreddit = await self.reddit.subreddit("wallpapers") assert await subreddit.random() is None async def test_sticky(self): subreddit = await self.reddit.subreddit("pics") with self.use_cassette(): submission = await subreddit.sticky() assert isinstance(submission, Submission) async def test_sticky__not_set(self): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): with pytest.raises(NotFound): await subreddit.sticky(2) async def test_search(self): with self.use_cassette(): subreddit = await self.reddit.subreddit("all") async for item in subreddit.search( "praw oauth search", limit=None, syntax="cloudsearch" ): assert isinstance(item, Submission) @mock.patch("asyncio.sleep", return_value=None) async def test_submit__flair(self, _): flair_id = "94f13282-e2e8-11e8-8291-0eae4e167256" flair_text = "AF" flair_class = "" self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) submission = await subreddit.submit( "Test Title", selftext="Test text.", flair_id=flair_id, flair_text=flair_text, ) await submission.load() assert submission.link_flair_css_class == flair_class assert submission.link_flair_text == flair_text @mock.patch("asyncio.sleep", return_value=None) async def test_submit__selftext(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) submission = await subreddit.submit("Test Title", selftext="Test text.") await submission.load() assert submission.author == pytest.placeholders.username assert submission.selftext == "Test text." assert submission.title == "Test Title" @mock.patch("asyncio.sleep", return_value=None) async def test_submit__selftext_blank(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) submission = await subreddit.submit("Test Title", selftext="") await submission.load() assert submission.author == pytest.placeholders.username assert submission.selftext == "" assert submission.title == "Test Title" @mock.patch("asyncio.sleep", return_value=None) async def test_submit__selftext_inline_media(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) gif = InlineGif(image_path("test.gif"), "optional caption") image = InlineImage(image_path("test.png"), "optional caption") video = InlineVideo(image_path("test.mp4"), "optional caption") selftext = ( "Text with a gif {gif1} an image {image1} and a video {video1} inline" ) media = {"gif1": gif, "image1": image, "video1": video} submission = await subreddit.submit( "title", selftext=selftext, inline_media=media ) await submission.load() assert submission.author == pytest.placeholders.username assert ( submission.selftext == "Text with a gif\n\n[optional caption](https://i.redd.it/s1i7ejqkgdc61.gif)\n\nan image\n\n[optional caption](https://preview.redd.it/95pza2skgdc61.png?width=128&format=png&auto=webp&s=c81d303645d9792afcdb9c47f0a6039708714274)\n\nand a video\n\n[optional caption](https://reddit.com/link/l0vyxc/video/qeg2azskgdc61/player)\n\ninline" ) assert submission.title == "title" @mock.patch("asyncio.sleep", return_value=None) async def test_submit_live_chat(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) submission = await subreddit.submit( "Test Title", selftext="", discussion_type="CHAT" ) await submission.load() assert submission.discussion_type == "CHAT" @mock.patch("asyncio.sleep", return_value=None) async def test_submit__url(self, _): url = "https://asyncpraw.readthedocs.org/en/stable/" self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) submission = await subreddit.submit("Test Title", url=url) await submission.load() assert submission.author == pytest.placeholders.username assert submission.url == url assert submission.title == "Test Title" @mock.patch("asyncio.sleep", return_value=None) async def test_submit__nsfw(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) submission = await subreddit.submit( "Test Title", selftext="Test text.", nsfw=True ) await submission.load() assert submission.over_18 is True @mock.patch("asyncio.sleep", return_value=None) async def test_submit__spoiler(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) submission = await subreddit.submit( "Test Title", selftext="Test text.", spoiler=True ) await submission.load() assert submission.spoiler is True @mock.patch("asyncio.sleep", return_value=None) async def test_submit__verify_invalid(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) self.reddit.validate_on_submit = True with pytest.raises( (RedditAPIException, BadRequest) ): # waiting for prawcore fix await subreddit.submit("dfgfdgfdgdf", url="https://www.google.com") @mock.patch("asyncio.sleep", return_value=None) async def test_submit_poll(self, _): options = ["Yes", "No", "3", "4", "5", "6"] self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) submission = await subreddit.submit_poll( "Test Poll", selftext="Test poll text.", options=options, duration=6, ) await submission.load() assert submission.author == pytest.placeholders.username assert submission.selftext.startswith("Test poll text.") assert submission.title == "Test Poll" assert [str(option) for option in submission.poll_data.options] == options assert submission.poll_data.voting_end_timestamp > submission.created_utc @mock.patch("asyncio.sleep", return_value=None) async def test_submit_poll__flair(self, _): flair_id = "94f13282-e2e8-11e8-8291-0eae4e167256" flair_text = "AF" flair_class = "" options = ["Yes", "No"] self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) submission = await subreddit.submit_poll( "Test Poll", selftext="Test poll text.", flair_id=flair_id, flair_text=flair_text, options=options, duration=6, ) await submission.load() assert submission.link_flair_text == flair_text assert submission.link_flair_css_class == flair_class @mock.patch("asyncio.sleep", return_value=None) async def test_submit_poll__live_chat(self, _): options = ["Yes", "No"] self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) submission = await subreddit.submit_poll( "Test Poll", selftext="", discussion_type="CHAT", options=options, duration=2, ) await submission.load() assert submission.discussion_type == "CHAT" async def test_submit_gallery(self): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) images = [ {"image_path": image_path("test.png")}, {"image_path": image_path("test.jpg"), "caption": "test.jpg"}, { "image_path": image_path("test.gif"), "outbound_url": "https://example.com", }, { "image_path": image_path("test.png"), "caption": "test.png", "outbound_url": "https://example.com", }, ] submission = await subreddit.submit_gallery("Test Title", images) assert submission.author == pytest.placeholders.username assert submission.is_gallery assert submission.title == "Test Title" items = submission.gallery_data["items"] assert isinstance(submission.gallery_data["items"], list) for i, item in enumerate(items): test_data = images[i] test_data.pop("image_path") item.pop("id") item.pop("media_id") assert item == test_data async def test_submit_gallery_disabled(self): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) images = [ {"image_path": image_path("test.png")}, {"image_path": image_path("test.jpg"), "caption": "test.jpg"}, { "image_path": image_path("test.gif"), "outbound_url": "https://example.com", }, { "image_path": image_path("test.png"), "caption": "test.png", "outbound_url": "https://example.com", }, ] with pytest.raises(RedditAPIException): await subreddit.submit_gallery("Test Title", images) @mock.patch("asyncio.sleep", return_value=None) async def test_submit_gallery__flair(self, _): flair_id = "6fc213da-cae7-11ea-9274-0e2407099e45" flair_text = "test" flair_class = "test-flair-class" self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) images = [ {"image_path": image_path("test.png")}, {"image_path": image_path("test.jpg"), "caption": "test.jpg"}, { "image_path": image_path("test.gif"), "outbound_url": "https://example.com", }, { "image_path": image_path("test.png"), "caption": "test.png", "outbound_url": "https://example.com", }, ] submission = await subreddit.submit_gallery( "Test Title", images, flair_id=flair_id, flair_text=flair_text ) assert submission.link_flair_css_class == flair_class assert submission.link_flair_text == flair_text @mock.patch( "aiohttp.client.ClientSession.ws_connect", return_value=WebsocketMock( "l6eqw6", "l6er3r", "l6erfu" # update with cassette ), ) @mock.patch("asyncio.sleep", return_value=None) async def test_submit_image(self, _, __): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) for i, file_name in enumerate(("test.png", "test.jpg", "test.gif")): image = image_path(file_name) submission = await subreddit.submit_image(f"Test Title {i}", image) await submission.load() assert submission.author == pytest.placeholders.username assert submission.is_reddit_media_domain assert submission.title == f"Test Title {i}" @pytest.mark.usefixtures("tmp_path") @mock.patch("asyncio.sleep", return_value=None) async def test_submit_image__large(self, _): reddit = self.reddit reddit.read_only = False mock_data = ( '<?xml version="1.0" encoding="UTF-8"?>' "<Error>" "<Code>EntityTooLarge</Code>" "<Message>Your proposed upload exceeds the maximum allowed size</Message>" "<ProposedSize>20971528</ProposedSize>" "<MaxSizeAllowed>20971520</MaxSizeAllowed>" "<RequestId>23F056D6990D87E0</RequestId>" "<HostId>iYEVOuRfbLiKwMgHt2ewqQRIm0NWL79uiC2rPLj9P0PwW55MhjY2/O8d9JdKTf1iwzLjwWMnGQ=</HostId>" "</Error>" ) _post = reddit._core._requestor._http.post async def patch_request(url, *args, **kwargs): """Patch requests to return mock data on specific url.""" if "https://reddit-uploaded-media.s3-accelerate.amazonaws.com" in url: response = ClientResponse response.text = mock_data response.status = 400 return response return await _post(url, *args, **kwargs) reddit._core._requestor._http.post = patch_request fake_png = PNG_HEADER + b"\x1a" * 10 # Normally 1024 ** 2 * 20 (20 MB) with open(self.tmp_path.joinpath("fake_img.png"), "wb") as tempfile: tempfile.write(fake_png) with self.use_cassette(): with pytest.raises(TooLargeMediaException): subreddit = await reddit.subreddit("test") await subreddit.submit_image("test", tempfile.name) @mock.patch("asyncio.sleep", return_value=None) @mock.patch("aiohttp.client.ClientSession.ws_connect", return_value=WebsocketMock()) async def test_submit_image__bad_websocket(self, _, __): self.reddit.read_only = False with self.use_cassette("TestSubreddit.test_submit_image"): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) for file_name in ("test.png", "test.jpg"): image = image_path(file_name) with pytest.raises(ClientException): await subreddit.submit_image("Test Title", image) @mock.patch("asyncio.sleep", return_value=None) async def test_submit_image__bad_filetype(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) for file_name in ("test.mov", "test.mp4"): image = image_path(file_name) with pytest.raises(ClientException): await subreddit.submit_image("Test Title", image) @mock.patch("asyncio.sleep", return_value=None) @mock.patch( "aiohttp.client.ClientSession.ws_connect", return_value=WebsocketMock("l6evpd") ) # update with cassette async def test_submit_image__flair(self, _, __): flair_id = "6fc213da-cae7-11ea-9274-0e2407099e45" flair_text = "Test flair text" flair_class = "" self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) image = image_path("test.jpg") submission = await subreddit.submit_image( "Test Title", image, flair_id=flair_id, flair_text=flair_text ) await submission.load() assert submission.link_flair_css_class == flair_class assert submission.link_flair_text == flair_text @mock.patch("asyncio.sleep", return_value=None) @mock.patch( "aiohttp.client.ClientSession.ws_connect", return_value=WebsocketMock("l6ey7j") ) # update with cassette async def test_submit_image_chat(self, _, __): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) image = image_path("test.jpg") submission = await subreddit.submit_image( "Test Title", image, discussion_type="CHAT" ) await submission.load() assert submission.discussion_type == "CHAT" @mock.patch("asyncio.sleep", return_value=None) async def test_submit_image_verify_invalid(self, _): self.reddit.read_only = False self.reddit.validate_on_submit = True with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) image = image_path("test.jpg") with pytest.raises( (RedditAPIException, BadRequest) ): # waiting for prawcore fix await subreddit.submit_image( "gdfgfdgdgdgfgfdgdfgfdgfdg", image, without_websockets=True ) @mock.patch("asyncio.sleep", return_value=None) @mock.patch( "aiohttp.client.ClientSession.ws_connect", side_effect=BlockingIOError ) # happens with timeout=0 async def test_submit_image__timeout_1(self, _, __): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) image = image_path("test.jpg") with pytest.raises(WebSocketException): await subreddit.submit_image("Test Title", image) @mock.patch("asyncio.sleep", return_value=None) @mock.patch( "aiohttp.client.ClientSession.ws_connect", side_effect=socket.timeout # happens with timeout=0.00001 ) async def test_submit_image__timeout_2(self, _, __): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) image = image_path("test.jpg") with pytest.raises(WebSocketException): await subreddit.submit_image("Test Title", image) @mock.patch("asyncio.sleep", return_value=None) @mock.patch( "aiohttp.client.ClientSession.ws_connect", side_effect=TimeoutError, # could happen but Async PRAW should handle it ) async def test_submit_image__timeout_3(self, _, __): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) image = image_path("test.jpg") with pytest.raises(WebSocketException): await subreddit.submit_image("Test Title", image) @mock.patch("asyncio.sleep", return_value=None) @mock.patch( "aiohttp.client.ClientSession.ws_connect", side_effect=WebSocketError(None, None), # could happen but Async PRAW should handle it ) async def test_submit_image__timeout_4(self, _, __): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) image = image_path("test.jpg") with pytest.raises(WebSocketException): await subreddit.submit_image("Test Title", image) @mock.patch("asyncio.sleep", return_value=None) async def test_submit_image__without_websockets(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) for file_name in ("test.png", "test.jpg", "test.gif"): image = image_path(file_name) submission = await subreddit.submit_image( "Test Title", image, without_websockets=True ) assert submission is None @mock.patch("asyncio.sleep", return_value=None) @mock.patch( "aiohttp.client.ClientSession.ws_connect", return_value=WebsocketMock("l6g58s", "l6g5al"), # update with cassette ) async def test_submit_video(self, _, __): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) for i, file_name in enumerate(("test.mov", "test.mp4")): video = image_path(file_name) submission = await subreddit.submit_video(f"Test Title {i}", video) await submission.load() assert submission.author == pytest.placeholders.username # assert submission.is_reddit_media_domain # for some reason returns false assert submission.title == f"Test Title {i}" @mock.patch("asyncio.sleep", return_value=None) async def test_submit_video__bad_filetype(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) for file_name in ("test.jpg", "test.png", "test.gif"): video = image_path(file_name) with pytest.raises(ClientException): await subreddit.submit_video("Test Title", video) @mock.patch("asyncio.sleep", return_value=None) @mock.patch("aiohttp.client.ClientSession.ws_connect", return_value=WebsocketMock()) async def test_submit_video__bad_websocket(self, _, __): self.reddit.read_only = False with self.use_cassette("TestSubreddit.test_submit_video"): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) for file_name in ("test.mov", "test.mp4"): video = image_path(file_name) with pytest.raises(ClientException): await subreddit.submit_video("Test Title", video) @mock.patch("asyncio.sleep", return_value=None) @mock.patch( "aiohttp.client.ClientSession.ws_connect", return_value=WebsocketMock("l6g771") ) # update with cassette async def test_submit_video__flair(self, _, __): flair_id = "6fc213da-cae7-11ea-9274-0e2407099e45" flair_text = "Test flair text" flair_class = "" self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) image = image_path("test.mov") submission = await subreddit.submit_video( "Test Title", image, flair_id=flair_id, flair_text=flair_text ) assert submission.link_flair_css_class == flair_class assert submission.link_flair_text == flair_text @mock.patch("asyncio.sleep", return_value=None) @mock.patch( "aiohttp.client.ClientSession.ws_connect", return_value=WebsocketMock("l6gocy") ) # update with cassette async def test_submit_video_chat(self, _, __): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) image = image_path("test.mov") submission = await subreddit.submit_video( "Test Title", image, discussion_type="CHAT" ) await submission.load() assert submission.discussion_type == "CHAT" @mock.patch("asyncio.sleep", return_value=None) async def test_submit_video_verify_invalid(self, _): self.reddit.read_only = False self.reddit.validate_on_submit = True with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) image = image_path("test.mov") with pytest.raises( (RedditAPIException, BadRequest) ): # waiting for prawcore fix await subreddit.submit_video( "gdfgfdgdgdgfgfdgdfgfdgfdg", image, without_websockets=True ) @mock.patch("asyncio.sleep", return_value=None) @mock.patch( "aiohttp.client.ClientSession.ws_connect", return_value=WebsocketMock("l6gvvi", "l6gvx7"), # update with cassette ) async def test_submit_video__thumbnail(self, _, __): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) for video_name, thumb_name in ( ("test.mov", "test.jpg"), ("test.mp4", "test.png"), ): video = image_path(video_name) thumb = image_path(thumb_name) submission = await subreddit.submit_video( "Test Title", video, thumbnail_path=thumb ) await submission.load() assert submission.author == pytest.placeholders.username assert submission.is_video assert submission.title == "Test Title" @mock.patch("asyncio.sleep", return_value=None) @mock.patch( "aiohttp.client.ClientSession.ws_connect", side_effect=BlockingIOError ) # happens with timeout=0 async def test_submit_video__timeout_1(self, _, __): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) video = image_path("test.mov") with pytest.raises(WebSocketException): await subreddit.submit_video("Test Title", video) @mock.patch("asyncio.sleep", return_value=None) @mock.patch( "aiohttp.client.ClientSession.ws_connect", side_effect=socket.timeout # happens with timeout=0.00001 ) async def test_submit_video__timeout_2(self, _, __): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) video = image_path("test.mov") with pytest.raises(WebSocketException): await subreddit.submit_video("Test Title", video) @mock.patch("asyncio.sleep", return_value=None) @mock.patch( "aiohttp.client.ClientSession.ws_connect", side_effect=TimeoutError, # could happen but Async PRAW should handle it ) async def test_submit_video__timeout_3(self, _, __): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) video = image_path("test.mov") with pytest.raises(WebSocketException): await subreddit.submit_video("Test Title", video) @mock.patch("asyncio.sleep", return_value=None) @mock.patch( "aiohttp.client.ClientSession.ws_connect", side_effect=WebSocketError(None, None), # could happen but Async PRAW should handle it ) async def test_submit_video__timeout_4(self, _, __): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) video = image_path("test.mov") with pytest.raises(WebSocketException): await subreddit.submit_video("Test Title", video) @mock.patch("asyncio.sleep", return_value=None) @mock.patch( "aiohttp.client.ClientSession.ws_connect", return_value=WebsocketMock("l6gtwa", "l6gty1"), # update with cassette ) async def test_submit_video__videogif(self, _, __): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) for file_name in ("test.mov", "test.mp4"): video = image_path(file_name) submission = await subreddit.submit_video( "Test Title", video, videogif=True ) assert submission.author == pytest.placeholders.username assert submission.is_video assert submission.title == "Test Title" @mock.patch("asyncio.sleep", return_value=None) async def test_submit_video__without_websockets(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) for file_name in ("test.mov", "test.mp4"): video = image_path(file_name) submission = await subreddit.submit_video( "Test Title", video, without_websockets=True ) assert submission is None async def test_subscribe(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await subreddit.subscribe() async def test_subscribe__multiple(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await subreddit.subscribe( ["redditdev", await self.reddit.subreddit("iama")] ) async def test_traffic(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): traffic = await subreddit.traffic() assert isinstance(traffic, dict) async def test_traffic__not_public(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit("announcements") with self.use_cassette(): with pytest.raises(NotFound): await subreddit.traffic() async def test_unsubscribe(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await subreddit.unsubscribe() async def test_unsubscribe__multiple(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await subreddit.unsubscribe( ["redditdev", await self.reddit.subreddit("iama")] ) class TestSubredditFilters(IntegrationTest): @mock.patch("asyncio.sleep", return_value=None) async def test__aiter__all(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit("all") filters = await self.async_list(subreddit.filters) assert len(filters) > 0 assert all(isinstance(x, Subreddit) for x in filters) @mock.patch("asyncio.sleep", return_value=None) async def test__aiter__mod(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit("mod") with self.use_cassette(): filters = await self.async_list(subreddit.filters) assert len(filters) > 0 assert all(isinstance(x, Subreddit) for x in filters) @mock.patch("asyncio.sleep", return_value=None) async def test_add(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit("all") await subreddit.filters.add("redditdev") @mock.patch("asyncio.sleep", return_value=None) async def test_add__subreddit_model(self, _): self.reddit.read_only = False with self.use_cassette("TestSubredditFilters.test_add"): subreddit = await self.reddit.subreddit("all") await subreddit.filters.add(await self.reddit.subreddit("redditdev")) # @mock.patch("asyncio.sleep", return_value=None) # FIXME: no longer raises not found; same with praw # async def test_add__non_special(self, _): # self.reddit.read_only = False # with self.use_cassette(): # with pytest.raises(NotFound): # subreddit = await self.reddit.subreddit("redditdev") # await subreddit.filters.add("redditdev") @mock.patch("asyncio.sleep", return_value=None) async def test_remove(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit("mod") await subreddit.filters.remove("redditdev") @mock.patch("asyncio.sleep", return_value=None) async def test_remove__subreddit_model(self, _): self.reddit.read_only = False with self.use_cassette("TestSubredditFilters.test_remove"): subreddit = await self.reddit.subreddit("mod") await subreddit.filters.remove(await self.reddit.subreddit("redditdev")) # @mock.patch("asyncio.sleep", return_value=None) # FIXME: no longer rases not found; same with praw # async def test_remove__non_special(self, _): # self.reddit.read_only = False # with self.use_cassette(): # with pytest.raises(NotFound): # subreddit = await self.reddit.subreddit("redditdev") # await subreddit.filters.remove("redditdev") class TestSubredditFlair(IntegrationTest): REDDITOR = pytest.placeholders.username async def test__call(self): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) mapping = subreddit.flair() assert len(await self.async_list(mapping)) > 0 assert all([isinstance(x["user"], Redditor) async for x in mapping]) async def test__call__user_filter(self): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) mapping = subreddit.flair(redditor=self.REDDITOR) assert len(await self.async_list(mapping)) == 1 async def test_configure(self): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) await subreddit.flair.configure( position=None, self_assign=True, link_position=None, link_self_assign=True, ) async def test_configure__defaults(self): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) await subreddit.flair.configure() async def test_delete(self): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) await subreddit.flair.delete(pytest.placeholders.username) @mock.patch("asyncio.sleep", return_value=None) async def test_delete_all(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) response = await subreddit.flair.delete_all() assert len(response) == 1 assert all("removed" in x["status"] for x in response) async def test_set__flair_id(self): self.reddit.read_only = False with self.use_cassette(): redditor = await self.reddit.redditor(pytest.placeholders.username) flair = "c99ff6d0-c559-11ea-b93b-0ef0f80279f1" subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) await subreddit.flair.set( redditor, "redditor flair", flair_template_id=flair ) async def test_set__flair_id_default_text(self): self.reddit.read_only = False with self.use_cassette(): redditor = await self.reddit.redditor(pytest.placeholders.username) flair = "c99ff6d0-c559-11ea-b93b-0ef0f80279f1" subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) await subreddit.flair.set(redditor, flair_template_id=flair) async def test_set__redditor(self): self.reddit.read_only = False with self.use_cassette(): redditor = await self.reddit.redditor(pytest.placeholders.username) subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) await subreddit.flair.set(redditor, "redditor flair") async def test_set__redditor_css_only(self): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) await subreddit.flair.set( pytest.placeholders.username, css_class="some class" ) async def test_set__redditor_string(self): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) await subreddit.flair.set( pytest.placeholders.username, "new flair", "some class" ) async def test_update(self): self.reddit.read_only = False with self.use_cassette(): redditor = await self.reddit.redditor(pytest.placeholders.username) flair_list = [ redditor, "spez", {"user": "bsimpson"}, {"user": "spladug", "flair_text": "", "flair_css_class": ""}, ] subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) response = await subreddit.flair.update( flair_list, css_class="async default" ) assert all(x["ok"] for x in response) assert not any(x["errors"] for x in response) assert not any(x["warnings"] for x in response) assert len([x for x in response if "added" in x["status"]]) == 3 assert len([x for x in response if "removed" in x["status"]]) == 1 for i, name in enumerate([str(redditor), "spez", "bsimpson", "spladug"]): assert name in response[i]["status"] async def test_update__comma_in_text(self): self.reddit.read_only = False flair_list = [ {"user": "bsimpson"}, {"user": "spladug", "flair_text": "a,b"}, ] with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) response = await subreddit.flair.update( flair_list, css_class="async default" ) assert all(x["ok"] for x in response) @mock.patch("asyncio.sleep", return_value=None) async def test_update_quotes(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) redditor = await self.reddit.user.me() response = await subreddit.flair.update( [redditor], text='"testing"', css_class="testing" ) assert all(x["ok"] for x in response) flair = await self.async_next(subreddit.flair(redditor)) assert flair["flair_text"] == '"testing"' assert flair["flair_css_class"] == "testing" class TestSubredditFlairTemplates(IntegrationTest): async def test__aiter(self): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) templates = await self.async_list(subreddit.flair.templates) assert len(templates) == 1 for flair_template in templates: assert flair_template["id"] async def test_add(self): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) await subreddit.flair.templates.add( "PRAW", css_class="myCSS", background_color="#ABCDEF" ) async def test_clear(self): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) await subreddit.flair.templates.clear() @mock.patch("asyncio.sleep", return_value=None) async def test_delete(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) template = await self.async_next(subreddit.flair.templates) await subreddit.flair.templates.delete(template["id"]) @mock.patch("asyncio.sleep", return_value=None) async def test_update(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) template = await self.async_next(subreddit.flair.templates) await subreddit.flair.templates.update( template["id"], "PRAW updated", css_class="myCSS", text_color="dark", background_color="#00FFFF", ) @mock.patch("asyncio.sleep", return_value=None) async def test_update_invalid(self, _): self.reddit.read_only = False with self.use_cassette(): with pytest.raises(InvalidFlairTemplateID): subreddit = await self.reddit.subreddit( pytest.placeholders.test_subreddit ) await subreddit.flair.templates.update( "fake id", "PRAW updated", css_class="myCSS", text_color="dark", background_color="#00FFFF", fetch=True, ) @mock.patch("asyncio.sleep", return_value=None) async def test_update_fetch(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) template = await self.async_next(subreddit.flair.templates) await subreddit.flair.templates.update( template["id"], "PRAW updated", css_class="myCSS", text_color="dark", background_color="#00FFFF", fetch=True, ) @mock.patch("asyncio.sleep", return_value=None) async def test_update_fetch_no_css_class(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) template = await self.async_next(subreddit.flair.templates) await subreddit.flair.templates.update( template["id"], "PRAW updated", text_color="dark", background_color="#00FFFF", fetch=True, ) @mock.patch("asyncio.sleep", return_value=None) async def test_update_fetch_no_text(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) template = await self.async_next(subreddit.flair.templates) await subreddit.flair.templates.update( template["id"], css_class="myCSS", text_color="dark", background_color="#00FFFF", fetch=True, ) @mock.patch("asyncio.sleep", return_value=None) async def test_update_fetch_no_text_or_css_class(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) template = await self.async_next(subreddit.flair.templates) await subreddit.flair.templates.update( template["id"], text_color="dark", background_color="#00FFFF", fetch=True, ) @mock.patch("asyncio.sleep", return_value=None) async def test_update_fetch_only(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) template = await self.async_next(subreddit.flair.templates) await subreddit.flair.templates.update(template["id"], fetch=True) newtemplate = list( filter( lambda _template: _template["id"] == template["id"], [flair async for flair in subreddit.flair.templates], ) )[0] assert newtemplate == template @mock.patch("asyncio.sleep", return_value=None) async def test_update_false(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) template = await self.async_next(subreddit.flair.templates) await subreddit.flair.templates.update( template["id"], text_editable=True, fetch=True ) await subreddit.flair.templates.update( template["id"], text_editable=False, fetch=True ) newtemplate = list( filter( lambda _template: _template["id"] == template["id"], [flair async for flair in subreddit.flair.templates], ) )[0] assert newtemplate["text_editable"] is False class TestSubredditLinkFlairTemplates(IntegrationTest): async def test__aiter(self): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) templates = await self.async_list(subreddit.flair.link_templates) assert len(templates) == 2 for template in templates: assert template["id"] assert isinstance(template["richtext"], list) assert all(isinstance(item, dict) for item in template["richtext"]) async def test_add(self): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) await subreddit.flair.link_templates.add( "PRAW", css_class="myCSS", text_color="light" ) async def test_clear(self): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) await subreddit.flair.link_templates.clear() class TestSubredditListings(IntegrationTest): async def test_comments(self): with self.use_cassette(): subreddit = await self.reddit.subreddit("askreddit") comments = await self.async_list(subreddit.comments()) assert len(comments) == 100 async def test_controversial(self): with self.use_cassette(): subreddit = await self.reddit.subreddit("askreddit") submissions = await self.async_list(subreddit.controversial()) assert len(submissions) == 100 async def test_gilded(self): with self.use_cassette(): subreddit = await self.reddit.subreddit("askreddit") submissions = await self.async_list(subreddit.gilded()) assert len(submissions) >= 50 async def test_hot(self): with self.use_cassette(): subreddit = await self.reddit.subreddit("askreddit") submissions = await self.async_list(subreddit.hot()) assert len(submissions) == 100 async def test_new(self): with self.use_cassette(): subreddit = await self.reddit.subreddit("askreddit") submissions = await self.async_list(subreddit.new()) assert len(submissions) == 100 async def test_random_rising(self): with self.use_cassette(): subreddit = await self.reddit.subreddit("askreddit") submissions = await self.async_list(subreddit.random_rising()) assert len(submissions) == 91 async def test_rising(self): with self.use_cassette(): subreddit = await self.reddit.subreddit("askreddit") submissions = await self.async_list(subreddit.rising()) assert len(submissions) == 100 async def test_top(self): with self.use_cassette(): subreddit = await self.reddit.subreddit("askreddit") submissions = await self.async_list(subreddit.top()) assert len(submissions) == 100 class TestSubredditModeration(IntegrationTest): async def test_accept_invite__no_invite(self): self.reddit.read_only = False with self.use_cassette(): with pytest.raises(RedditAPIException) as excinfo: subreddit = await self.reddit.subreddit( pytest.placeholders.test_subreddit ) await subreddit.mod.accept_invite() assert excinfo.value.items[0].error_type == "NO_INVITE_FOUND" async def test_edited(self): self.reddit.read_only = False with self.use_cassette(): count = 0 subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) async for item in subreddit.mod.edited(): assert isinstance(item, (Comment, Submission)) count += 1 assert count == 100 async def test_edited__only_comments(self): self.reddit.read_only = False with self.use_cassette(): count = 0 subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) async for item in subreddit.mod.edited(only="comments"): assert isinstance(item, Comment) count += 1 assert count == 100 async def test_edited__only_submissions(self): self.reddit.read_only = False with self.use_cassette(): count = 0 subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) async for item in subreddit.mod.edited(only="submissions"): assert isinstance(item, Submission) count += 1 assert count > 0 async def test_inbox(self): self.reddit.read_only = False with self.use_cassette(): count = 0 subreddit = await self.reddit.subreddit("all") async for item in subreddit.mod.inbox(): assert isinstance(item, SubredditMessage) count += 1 assert count == 100 async def test_log(self): self.reddit.read_only = False with self.use_cassette(): count = 0 subreddit = await self.reddit.subreddit("mod") async for item in subreddit.mod.log(): assert isinstance(item, ModAction) count += 1 assert count == 100 async def test_log__filters(self): self.reddit.read_only = False with self.use_cassette(): count = 0 redditor = await self.reddit.user.me() subreddit = await self.reddit.subreddit("mod") async for item in subreddit.mod.log(action="invitemoderator", mod=redditor): assert isinstance(item, ModAction) assert item.action == "invitemoderator" assert isinstance(item.mod, Redditor) assert item.mod == pytest.placeholders.username count += 1 assert count > 0 async def test_modqueue(self): self.reddit.read_only = False with self.use_cassette(): count = 0 subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) async for item in subreddit.mod.modqueue(): assert isinstance(item, (Comment, Submission)) count += 1 assert count > 0 async def test_modqueue__only_comments(self): self.reddit.read_only = False with self.use_cassette(): count = 0 subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) async for item in subreddit.mod.modqueue(only="comments"): assert isinstance(item, Comment) count += 1 assert count > 0 async def test_modqueue__only_submissions(self): self.reddit.read_only = False with self.use_cassette(): count = 0 subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) async for item in subreddit.mod.modqueue(only="submissions"): assert isinstance(item, Submission) count += 1 assert count > 0 async def test_reports(self): self.reddit.read_only = False with self.use_cassette(): count = 0 subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) async for item in subreddit.mod.reports(): assert isinstance(item, (Comment, Submission)) count += 1 assert count == 100 async def test_reports__only_comments(self): self.reddit.read_only = False with self.use_cassette(): count = 0 subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) async for item in subreddit.mod.reports(only="comments"): assert isinstance(item, Comment) count += 1 assert count > 0 async def test_reports__only_submissions(self): self.reddit.read_only = False with self.use_cassette(): count = 0 subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) async for item in subreddit.mod.reports(only="submissions"): assert isinstance(item, Submission) count += 1 assert count == 100 async def test_spam(self): self.reddit.read_only = False with self.use_cassette(): count = 0 subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) async for item in subreddit.mod.spam(): assert isinstance(item, (Comment, Submission)) count += 1 assert count > 0 async def test_spam__only_comments(self): self.reddit.read_only = False with self.use_cassette(): count = 0 subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) async for item in subreddit.mod.spam(only="comments"): assert isinstance(item, Comment) count += 1 assert count > 0 async def test_spam__only_submissions(self): self.reddit.read_only = False with self.use_cassette(): count = 0 subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) async for item in subreddit.mod.spam(only="submissions"): assert isinstance(item, Submission) count += 1 assert count > 0 async def test_unmoderated(self): self.reddit.read_only = False with self.use_cassette(): count = 0 subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) async for item in subreddit.mod.unmoderated(): assert isinstance(item, (Comment, Submission)) count += 1 assert count > 0 async def test_unread(self): self.reddit.read_only = False with self.use_cassette(): count = 0 subreddit = await self.reddit.subreddit("all") async for item in subreddit.mod.unread(): assert isinstance(item, SubredditMessage) count += 1 assert count > 0 @mock.patch("asyncio.sleep", return_value=None) async def test_update(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) before_settings = await subreddit.mod.settings() new_title = f"{before_settings["title"]}x" new_title = ( "x" if (len(new_title) >= 20 and "placeholder" not in new_title) else new_title ) await subreddit.mod.update(title=new_title) await subreddit.load() assert subreddit.title == new_title after_settings = await subreddit.mod.settings() # Ensure that nothing has changed besides what was specified. before_settings["title"] = new_title assert before_settings == after_settings class TestSubredditModmail(IntegrationTest): async def test_bulk_read(self): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) conversations = await subreddit.modmail.bulk_read(state="new") for conversation in conversations: assert isinstance(conversation, ModmailConversation) @mock.patch("asyncio.sleep", return_value=None) async def test_call(self, _): self.reddit.read_only = False conversation_id = "fjhla" subreddit = await self.reddit.subreddit("all") with self.use_cassette(): conversation = await subreddit.modmail(conversation_id) assert isinstance(conversation.user, Redditor) for message in conversation.messages: assert isinstance(message, ModmailMessage) for action in conversation.mod_actions: assert isinstance(action, ModmailAction) @mock.patch("asyncio.sleep", return_value=None) async def test_call__internal(self, _): self.reddit.read_only = False conversation_id = "ff1r8" subreddit = await self.reddit.subreddit("all") with self.use_cassette(): conversation = await subreddit.modmail(conversation_id) for message in conversation.messages: assert isinstance(message, ModmailMessage) for action in conversation.mod_actions: assert isinstance(action, ModmailAction) @mock.patch("asyncio.sleep", return_value=None) async def test_call__mark_read(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit("all") with self.use_cassette(): conversation = await subreddit.modmail("fccdg", mark_read=True) assert conversation.last_unread is None @mock.patch("asyncio.sleep", return_value=None) async def test_conversations(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit("all") with self.use_cassette(): async for conversation in subreddit.modmail.conversations(): assert isinstance(conversation, ModmailConversation) assert isinstance(conversation.authors[0], Redditor) @mock.patch("asyncio.sleep", return_value=None) async def test_conversations__params(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit("all") with self.use_cassette(): async for conversation in subreddit.modmail.conversations(state="mod"): assert conversation.is_internal @mock.patch("asyncio.sleep", return_value=None) async def test_conversations__other_subreddits(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): conversations = await self.async_list( subreddit.modmail.conversations(other_subreddits=["dankmemes"]) ) assert len(set(conversation.owner for conversation in conversations)) > 1 @mock.patch("asyncio.sleep", return_value=None) async def test_create(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): redditor = await self.reddit.redditor(pytest.placeholders.username) conversation = await subreddit.modmail.create("Subject", "Body", redditor) assert isinstance(conversation, ModmailConversation) async def test_subreddits(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): async for subreddit in subreddit.modmail.subreddits(): assert isinstance(subreddit, Subreddit) async def test_unread_count(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): assert isinstance(await subreddit.modmail.unread_count(), dict) class TestSubredditQuarantine(IntegrationTest): @mock.patch("asyncio.sleep", return_value=None) async def test_opt_in(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit("tiananmenaquarefalse") with self.use_cassette(): with pytest.raises(Forbidden): await self.async_next(subreddit.top()) await subreddit.quaran.opt_in() assert isinstance(await self.async_next(subreddit.top()), Submission) @mock.patch("asyncio.sleep", return_value=None) async def test_opt_out(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit("tiananmenaquarefalse") with self.use_cassette(): await subreddit.quaran.opt_out() with pytest.raises(Forbidden): await self.async_next(subreddit.new()) class TestSubredditRelationships(IntegrationTest): REDDITOR = "pyapitestuser3" async def add_remove(self, base, user, relationship): relationship = getattr(base, relationship) await relationship.add(user) relationships = await self.async_list(relationship()) assert user in relationships redditor = relationships[relationships.index(user)] assert isinstance(redditor, Redditor) assert hasattr(redditor, "date") await relationship.remove(user) assert user not in await self.async_list(relationship()) async def test_banned(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await self.add_remove(subreddit, self.REDDITOR, "banned") async def test_banned__user_filter(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) banned = subreddit.banned(redditor="pyapitestuser3") with self.use_cassette(): assert len(await self.async_list(banned)) == 1 async def test_contributor(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await self.add_remove(subreddit, self.REDDITOR, "contributor") @mock.patch("asyncio.sleep", return_value=None) async def test_contributor_leave(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await subreddit.contributor.leave() async def test_contributor__user_filter(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) contributor = subreddit.contributor(redditor="pyapitestuser3") with self.use_cassette(): assert len(await self.async_list(contributor)) == 1 @mock.patch("asyncio.sleep", return_value=None) async def test_moderator(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): # Moderators can only be invited. # As of 2016-03-18 there is no API endpoint to get the moderator # invite list. await subreddit.moderator.add(self.REDDITOR) assert self.REDDITOR not in await subreddit.moderator() @mock.patch("asyncio.sleep", return_value=None) async def test_moderator_aiter(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): async for moderator in subreddit.moderator: assert isinstance(moderator, Redditor) @mock.patch("asyncio.sleep", return_value=None) async def test_moderator__limited_permissions(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): # Moderators can only be invited. # As of 2016-03-18 there is no API endpoint to get the moderator # invite list. await subreddit.moderator.add(self.REDDITOR, permissions=["access", "wiki"]) assert self.REDDITOR not in await subreddit.moderator() async def test_moderator_invite__invalid_perm(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): with pytest.raises(RedditAPIException) as excinfo: await subreddit.moderator.invite(self.REDDITOR, permissions=["a"]) assert excinfo.value.items[0].error_type == "INVALID_PERMISSIONS" @mock.patch("asyncio.sleep", return_value=None) async def test_moderator_invite__no_perms(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): # Moderators can only be invited. # As of 2016-03-18 there is no API endpoint to get the moderator # invite list. await subreddit.moderator.invite(self.REDDITOR, permissions=[]) assert self.REDDITOR not in await subreddit.moderator() @mock.patch("asyncio.sleep", return_value=None) async def test_moderator_invited_moderators(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): invited = subreddit.moderator.invited() assert isinstance(invited, ListingGenerator) async for moderator in invited: assert isinstance(moderator, Redditor) @mock.patch("asyncio.sleep", return_value=None) async def test_moderator_leave(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await subreddit.moderator.leave() async def test_moderator_update(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await subreddit.moderator.update( pytest.placeholders.username, permissions=["config"] ) async def test_moderator_update_invite(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await subreddit.moderator.update_invite(self.REDDITOR, permissions=["mail"]) async def test_moderator__user_filter(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): moderator = await subreddit.moderator(redditor=pytest.placeholders.username) assert len(moderator) == 1 assert "mod_permissions" in moderator[0].__dict__ @mock.patch("asyncio.sleep", return_value=None) async def test_muted(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await self.add_remove(subreddit, self.REDDITOR, "muted") async def test_moderator_remove_invite(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await subreddit.moderator.remove_invite(self.REDDITOR) async def test_wiki_banned(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await self.add_remove(subreddit.wiki, self.REDDITOR, "banned") async def test_wiki_contributor(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await self.add_remove(subreddit.wiki, self.REDDITOR, "contributor") class TestSubredditStreams(IntegrationTest): @mock.patch("asyncio.sleep", return_value=None) async def test_comments(self, _): subreddit = await self.reddit.subreddit("all") with self.use_cassette(): generator = subreddit.stream.comments() for i in range(400): assert isinstance(await self.async_next(generator), Comment) @mock.patch("asyncio.sleep", return_value=None) async def test_comments__with_pause(self, _): subreddit = await self.reddit.subreddit("askreddit") with self.use_cassette(): comment_stream = subreddit.stream.comments(pause_after=0) comment_count = 1 pause_count = 1 comment = await self.async_next(comment_stream) while comment is not None: comment_count += 1 comment = await self.async_next(comment_stream) while comment is None: pause_count += 1 comment = await self.async_next(comment_stream) assert comment_count == 108 assert pause_count == 3 @mock.patch("asyncio.sleep", return_value=None) async def test_comments__with_skip_existing(self, _): with self.use_cassette("TestSubredditStreams.test_comments__with_pause"): subreddit = await self.reddit.subreddit("askreddit") generator = subreddit.stream.comments(skip_existing=True) count = 0 try: async for comment in generator: count += 1 except TypeError: pass # This test uses the same cassette as test_comments which shows # that there are at least 100 comments in the stream. assert count < 102 @mock.patch("asyncio.sleep", return_value=None) async def test_submissions(self, _): with self.use_cassette(): subreddit = await self.reddit.subreddit("all") generator = subreddit.stream.submissions() for i in range(101): assert isinstance(await self.async_next(generator), Submission) @mock.patch("asyncio.sleep", return_value=None) async def test_submissions__with_pause(self, _): with self.use_cassette("TestSubredditStreams.test_submissions"): subreddit = await self.reddit.subreddit("all") generator = subreddit.stream.submissions(pause_after=-1) submission = await self.async_next(generator) submission_count = 0 while submission is not None: submission_count += 1 submission = await self.async_next(generator) assert submission_count == 100 @mock.patch("asyncio.sleep", return_value=None) async def test_submissions__with_pause_and_skip_after(self, _): with self.use_cassette("TestSubredditStreams.test_submissions"): subreddit = await self.reddit.subreddit("all") generator = subreddit.stream.submissions(pause_after=-1, skip_existing=True) submission = await self.async_next(generator) assert submission is None # The first thing yielded should be None submission_count = 0 submission = await self.async_next(generator) while submission is not None: submission_count += 1 submission = await self.async_next(generator) assert submission_count < 100 class TestSubredditModerationStreams(IntegrationTest): @mock.patch("asyncio.sleep", return_value=None) async def test_edited(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit("mod") with self.use_cassette(): generator = subreddit.mod.stream.edited() for i in range(101): assert isinstance( await self.async_next(generator), (Comment, Submission) ) @mock.patch("asyncio.sleep", return_value=None) async def test_log(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit("mod") with self.use_cassette(): generator = subreddit.mod.stream.log() for i in range(101): assert isinstance(await self.async_next(generator), ModAction) @mock.patch("asyncio.sleep", return_value=None) async def test_modmail_conversations(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit("mod") with self.use_cassette(): generator = subreddit.mod.stream.modmail_conversations() for i in range(10): assert isinstance(await self.async_next(generator), ModmailConversation) @mock.patch("asyncio.sleep", return_value=None) async def test_modqueue(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit("mod") with self.use_cassette(): generator = subreddit.mod.stream.modqueue() for i in range(10): assert isinstance( await self.async_next(generator), (Comment, Submission) ) @mock.patch("asyncio.sleep", return_value=None) async def test_spam(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit("mod") with self.use_cassette(): generator = subreddit.mod.stream.spam() for i in range(101): assert isinstance( await self.async_next(generator), (Comment, Submission) ) @mock.patch("asyncio.sleep", return_value=None) async def test_reports(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit("mod") with self.use_cassette(): generator = subreddit.mod.stream.reports() for i in range(10): assert isinstance( await self.async_next(generator), (Comment, Submission) ) @mock.patch("asyncio.sleep", return_value=None) async def test_unmoderated(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit("mod") with self.use_cassette(): generator = subreddit.mod.stream.unmoderated() for i in range(101): assert isinstance( await self.async_next(generator), (Comment, Submission) ) @mock.patch("asyncio.sleep", return_value=None) async def test_unread(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit("mod") with self.use_cassette(): generator = subreddit.mod.stream.unread() for i in range(2): assert isinstance(await self.async_next(generator), SubredditMessage) class TestSubredditStylesheet(IntegrationTest): async def test_call(self): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): stylesheet = await subreddit.stylesheet() assert isinstance(stylesheet, Stylesheet) assert len(stylesheet.images) > 0 assert stylesheet.stylesheet != "" async def test_delete_banner(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await subreddit.stylesheet.delete_banner() async def test_delete_banner_additional_image(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await subreddit.stylesheet.delete_banner_additional_image() async def test_delete_banner_hover_image(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await subreddit.stylesheet.delete_banner_hover_image() async def test_delete_header(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await subreddit.stylesheet.delete_header() async def test_delete_image(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await subreddit.stylesheet.delete_image("praw") async def test_delete_mobile_header(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await subreddit.stylesheet.delete_mobile_header() async def test_delete_mobile_icon(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await subreddit.stylesheet.delete_mobile_icon() async def test_update(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await subreddit.stylesheet.update("p { color: red; }") async def test_update__with_reason(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await subreddit.stylesheet.update("div { color: red; }", reason="use div") async def test_upload(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): response = await subreddit.stylesheet.upload( "asyncpraw", image_path("white-square.png") ) assert response["img_src"].endswith(".png") async def test_upload__invalid(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): with pytest.raises(RedditAPIException) as excinfo: await subreddit.stylesheet.upload( "asyncpraw", image_path("invalid.jpg") ) assert excinfo.value.items[0].error_type == "IMAGE_ERROR" async def test_upload__invalid_ext(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): with pytest.raises(RedditAPIException) as excinfo: await subreddit.stylesheet.upload( "asyncpraw", image_path("white-square.png") ) assert excinfo.value.items[0].error_type == "BAD_CSS_NAME" async def test_upload__too_large(self): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with pytest.raises(TooLarge): await subreddit.stylesheet.upload( "asyncpraw", image_path("too_large.jpg") ) @mock.patch("asyncio.sleep", return_value=None) async def test_upload_banner__jpg(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await subreddit.stylesheet.upload_banner(image_path("white-square.jpg")) @mock.patch("asyncio.sleep", return_value=None) async def test_upload_banner__png(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await subreddit.stylesheet.upload_banner(image_path("white-square.png")) @mock.patch("asyncio.sleep", return_value=None) async def test_upload_banner_additional_image__jpg(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await subreddit.stylesheet.upload_banner_additional_image( image_path("white-square.jpg") ) @mock.patch("asyncio.sleep", return_value=None) async def test_upload_banner_additional_image__png(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await subreddit.stylesheet.upload_banner_additional_image( image_path("white-square.png") ) @mock.patch("asyncio.sleep", return_value=None) async def test_upload_banner_additional_image__align(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): for alignment in ("left", "centered", "right"): await subreddit.stylesheet.upload_banner_additional_image( image_path("white-square.png"), align=alignment ) @mock.patch("asyncio.sleep", return_value=None) async def test_upload_banner_hover_image__jpg(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await subreddit.stylesheet.upload_banner_additional_image( image_path("white-square.png") ) await subreddit.stylesheet.upload_banner_hover_image( image_path("white-square.jpg") ) @mock.patch("asyncio.sleep", return_value=None) async def test_upload_banner_hover_image__png(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await subreddit.stylesheet.upload_banner_additional_image( image_path("white-square.jpg") ) await subreddit.stylesheet.upload_banner_hover_image( image_path("white-square.png") ) async def test_upload_header__jpg(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): response = await subreddit.stylesheet.upload_header( image_path("white-square.jpg") ) assert response["img_src"].endswith(".jpg") async def test_upload_header__png(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): response = await subreddit.stylesheet.upload_header( image_path("white-square.png") ) assert response["img_src"].endswith(".png") async def test_upload_mobile_header(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): response = await subreddit.stylesheet.upload_mobile_header( image_path("header.jpg") ) assert response["img_src"].endswith(".jpg") async def test_upload_mobile_icon(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): response = await subreddit.stylesheet.upload_mobile_icon( image_path("icon.jpg") ) assert response["img_src"].endswith(".jpg") @mock.patch("asyncio.sleep", return_value=None) async def test_upload__others_invalid(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): for method in [ "upload_header", "upload_mobile_header", "upload_mobile_icon", ]: with pytest.raises(RedditAPIException) as excinfo: await getattr(subreddit.stylesheet, method)( image_path("invalid.jpg") ) assert excinfo.value.items[0].error_type == "IMAGE_ERROR" async def test_upload__others_too_large(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): for method in [ "upload_header", "upload_mobile_header", "upload_mobile_icon", ]: with pytest.raises(TooLarge): await getattr( subreddit.stylesheet, method, )(image_path("too_large.jpg")) class TestSubredditWiki(IntegrationTest): @mock.patch("asyncio.sleep", return_value=None) async def test__aiter(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): count = 0 async for wikipage in subreddit.wiki: assert isinstance(wikipage, WikiPage) count += 1 assert count > 0 @mock.patch("asyncio.sleep", return_value=None) async def test_create(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): wikipage = await subreddit.wiki.create( "Async PRAW New Page", "This is the new wiki page" ) await wikipage.load() assert wikipage.name == "async_praw_new_page" assert wikipage.content_md == "This is the new wiki page" @mock.patch("asyncio.sleep", return_value=None) async def test_revisions(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): count = 0 async for revision in subreddit.wiki.revisions(limit=2): count += 1 assert isinstance(revision["author"], Redditor) assert isinstance(revision["page"], WikiPage) assert count == 2
"""Test asyncpraw.models.subreddit.""" import socket import sys from asyncio import TimeoutError from os.path import abspath, dirname, join import pytest from aiohttp import ClientResponse from aiohttp.http_websocket import WebSocketError from asyncprawcore import BadRequest, Forbidden, NotFound, TooLarge from asynctest import mock from asyncpraw.const import PNG_HEADER from asyncpraw.exceptions import ( ClientException, InvalidFlairTemplateID, RedditAPIException, TooLargeMediaException, WebSocketException, ) from asyncpraw.models import ( Comment, InlineGif, InlineImage, InlineVideo, ListingGenerator, ModAction, ModmailAction, ModmailConversation, ModmailMessage, Redditor, Stylesheet, Submission, Subreddit, SubredditMessage, WikiPage, ) from ... import IntegrationTest def image_path(name): test_dir = abspath(dirname(sys.modules[__name__].__file__)) return abspath(join(test_dir, "..", "..", "files", name)) class WebsocketMock: POST_URL = "https://reddit.com/r/<TEST_SUBREDDIT>/comments/{}/test_title/" @classmethod def make_dict(cls, post_id): return {"payload": {"redirect": cls.POST_URL.format(post_id)}} def __init__(self, *post_ids): self.post_ids = post_ids self.i = -1 async def __aenter__(self): return self async def __aexit__(self, exc_type, exc_val, exc_tb): pass async def receive_json(self): if not self.post_ids: raise WebSocketError(None, None) assert 0 <= self.i + 1 < len(self.post_ids) self.i += 1 return self.make_dict(self.post_ids[self.i]) class TestSubreddit(IntegrationTest): @mock.patch("asyncio.sleep", return_value=None) async def test_create(self, _): self.reddit.read_only = False new_name = pytest.placeholders.test_subreddit with self.use_cassette(): subreddit = await self.reddit.subreddit.create( name=new_name, title="Sub", link_type="any", subreddit_type="public", wikimode="disabled", wiki_edit_age=0, wiki_edit_karma=0, comment_score_hide_mins=0, ) assert subreddit.display_name == new_name assert subreddit.submission_type == "any" async def test_create__exists(self): self.reddit.read_only = False with self.use_cassette(): with pytest.raises(RedditAPIException) as excinfo: await self.reddit.subreddit.create( "redditdev", title="redditdev", link_type="any", subreddit_type="public", wikimode="disabled", ) assert excinfo.value.items[0].error_type == "SUBREDDIT_EXISTS" async def test_create__invalid_parameter(self): self.reddit.read_only = False with self.use_cassette(): with pytest.raises(RedditAPIException) as excinfo: # Supplying invalid setting for link_type await self.reddit.subreddit.create( name="PRAW_iavynavff2", title="sub", link_type="abcd", subreddit_type="public", wikimode="disabled", ) assert excinfo.value.items[0].error_type == "INVALID_OPTION" async def test_create__missing_parameter(self): self.reddit.read_only = False with self.use_cassette(): with pytest.raises(RedditAPIException) as excinfo: # Not supplying required field wiki_edit_age. await self.reddit.subreddit.create( name="PRAW_iavynavff3", title=None, link_type="any", subreddit_type="public", wikimode="disabled", wiki_edit_karma=0, comment_score_hide_mins=0, ) assert excinfo.value.items[0].error_type == "BAD_NUMBER" @mock.patch("asyncio.sleep", return_value=None) async def test_message(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) await subreddit.message("Test from Async PRAW", message="Test content") @mock.patch("asyncio.sleep", return_value=None) async def test_post_requirements(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) data = await subreddit.post_requirements() tags = [ "domain_blacklist", "body_restriction_policy", "domain_whitelist", "title_regexes", "body_blacklisted_strings", "body_required_strings", "title_text_min_length", "is_flair_required", "title_text_max_length", "body_regexes", "link_repost_age", "body_text_min_length", "link_restriction_policy", "body_text_max_length", "title_required_strings", "title_blacklisted_strings", "guidelines_text", "guidelines_display_policy", ] assert list(data) == tags async def test_random(self): with self.use_cassette(): subreddit = await self.reddit.subreddit("pics") submissions = [ await subreddit.random(), await subreddit.random(), await subreddit.random(), await subreddit.random(), ] assert len(submissions) == len(set(submissions)) async def test_random__returns_none(self): with self.use_cassette(): subreddit = await self.reddit.subreddit("wallpapers") assert await subreddit.random() is None async def test_sticky(self): subreddit = await self.reddit.subreddit("pics") with self.use_cassette(): submission = await subreddit.sticky() assert isinstance(submission, Submission) async def test_sticky__not_set(self): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): with pytest.raises(NotFound): await subreddit.sticky(2) async def test_search(self): with self.use_cassette(): subreddit = await self.reddit.subreddit("all") async for item in subreddit.search( "praw oauth search", limit=None, syntax="cloudsearch" ): assert isinstance(item, Submission) @mock.patch("asyncio.sleep", return_value=None) async def test_submit__flair(self, _): flair_id = "94f13282-e2e8-11e8-8291-0eae4e167256" flair_text = "AF" flair_class = "" self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) submission = await subreddit.submit( "Test Title", selftext="Test text.", flair_id=flair_id, flair_text=flair_text, ) await submission.load() assert submission.link_flair_css_class == flair_class assert submission.link_flair_text == flair_text @mock.patch("asyncio.sleep", return_value=None) async def test_submit__selftext(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) submission = await subreddit.submit("Test Title", selftext="Test text.") await submission.load() assert submission.author == pytest.placeholders.username assert submission.selftext == "Test text." assert submission.title == "Test Title" @mock.patch("asyncio.sleep", return_value=None) async def test_submit__selftext_blank(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) submission = await subreddit.submit("Test Title", selftext="") await submission.load() assert submission.author == pytest.placeholders.username assert submission.selftext == "" assert submission.title == "Test Title" @mock.patch("asyncio.sleep", return_value=None) async def test_submit__selftext_inline_media(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) gif = InlineGif(image_path("test.gif"), "optional caption") image = InlineImage(image_path("test.png"), "optional caption") video = InlineVideo(image_path("test.mp4"), "optional caption") selftext = ( "Text with a gif {gif1} an image {image1} and a video {video1} inline" ) media = {"gif1": gif, "image1": image, "video1": video} submission = await subreddit.submit( "title", selftext=selftext, inline_media=media ) await submission.load() assert submission.author == pytest.placeholders.username assert ( submission.selftext == "Text with a gif\n\n[optional caption](https://i.redd.it/s1i7ejqkgdc61.gif)\n\nan image\n\n[optional caption](https://preview.redd.it/95pza2skgdc61.png?width=128&format=png&auto=webp&s=c81d303645d9792afcdb9c47f0a6039708714274)\n\nand a video\n\n[optional caption](https://reddit.com/link/l0vyxc/video/qeg2azskgdc61/player)\n\ninline" ) assert submission.title == "title" @mock.patch("asyncio.sleep", return_value=None) async def test_submit_live_chat(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) submission = await subreddit.submit( "Test Title", selftext="", discussion_type="CHAT" ) await submission.load() assert submission.discussion_type == "CHAT" @mock.patch("asyncio.sleep", return_value=None) async def test_submit__url(self, _): url = "https://asyncpraw.readthedocs.org/en/stable/" self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) submission = await subreddit.submit("Test Title", url=url) await submission.load() assert submission.author == pytest.placeholders.username assert submission.url == url assert submission.title == "Test Title" @mock.patch("asyncio.sleep", return_value=None) async def test_submit__nsfw(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) submission = await subreddit.submit( "Test Title", selftext="Test text.", nsfw=True ) await submission.load() assert submission.over_18 is True @mock.patch("asyncio.sleep", return_value=None) async def test_submit__spoiler(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) submission = await subreddit.submit( "Test Title", selftext="Test text.", spoiler=True ) await submission.load() assert submission.spoiler is True @mock.patch("asyncio.sleep", return_value=None) async def test_submit__verify_invalid(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) self.reddit.validate_on_submit = True with pytest.raises( (RedditAPIException, BadRequest) ): # waiting for prawcore fix await subreddit.submit("dfgfdgfdgdf", url="https://www.google.com") @mock.patch("asyncio.sleep", return_value=None) async def test_submit_poll(self, _): options = ["Yes", "No", "3", "4", "5", "6"] self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) submission = await subreddit.submit_poll( "Test Poll", selftext="Test poll text.", options=options, duration=6, ) await submission.load() assert submission.author == pytest.placeholders.username assert submission.selftext.startswith("Test poll text.") assert submission.title == "Test Poll" assert [str(option) for option in submission.poll_data.options] == options assert submission.poll_data.voting_end_timestamp > submission.created_utc @mock.patch("asyncio.sleep", return_value=None) async def test_submit_poll__flair(self, _): flair_id = "94f13282-e2e8-11e8-8291-0eae4e167256" flair_text = "AF" flair_class = "" options = ["Yes", "No"] self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) submission = await subreddit.submit_poll( "Test Poll", selftext="Test poll text.", flair_id=flair_id, flair_text=flair_text, options=options, duration=6, ) await submission.load() assert submission.link_flair_text == flair_text assert submission.link_flair_css_class == flair_class @mock.patch("asyncio.sleep", return_value=None) async def test_submit_poll__live_chat(self, _): options = ["Yes", "No"] self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) submission = await subreddit.submit_poll( "Test Poll", selftext="", discussion_type="CHAT", options=options, duration=2, ) await submission.load() assert submission.discussion_type == "CHAT" async def test_submit_gallery(self): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) images = [ {"image_path": image_path("test.png")}, {"image_path": image_path("test.jpg"), "caption": "test.jpg"}, { "image_path": image_path("test.gif"), "outbound_url": "https://example.com", }, { "image_path": image_path("test.png"), "caption": "test.png", "outbound_url": "https://example.com", }, ] submission = await subreddit.submit_gallery("Test Title", images) assert submission.author == pytest.placeholders.username assert submission.is_gallery assert submission.title == "Test Title" items = submission.gallery_data["items"] assert isinstance(submission.gallery_data["items"], list) for i, item in enumerate(items): test_data = images[i] test_data.pop("image_path") item.pop("id") item.pop("media_id") assert item == test_data async def test_submit_gallery_disabled(self): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) images = [ {"image_path": image_path("test.png")}, {"image_path": image_path("test.jpg"), "caption": "test.jpg"}, { "image_path": image_path("test.gif"), "outbound_url": "https://example.com", }, { "image_path": image_path("test.png"), "caption": "test.png", "outbound_url": "https://example.com", }, ] with pytest.raises(RedditAPIException): await subreddit.submit_gallery("Test Title", images) @mock.patch("asyncio.sleep", return_value=None) async def test_submit_gallery__flair(self, _): flair_id = "6fc213da-cae7-11ea-9274-0e2407099e45" flair_text = "test" flair_class = "test-flair-class" self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) images = [ {"image_path": image_path("test.png")}, {"image_path": image_path("test.jpg"), "caption": "test.jpg"}, { "image_path": image_path("test.gif"), "outbound_url": "https://example.com", }, { "image_path": image_path("test.png"), "caption": "test.png", "outbound_url": "https://example.com", }, ] submission = await subreddit.submit_gallery( "Test Title", images, flair_id=flair_id, flair_text=flair_text ) assert submission.link_flair_css_class == flair_class assert submission.link_flair_text == flair_text @mock.patch( "aiohttp.client.ClientSession.ws_connect", return_value=WebsocketMock( "l6eqw6", "l6er3r", "l6erfu" # update with cassette ), ) @mock.patch("asyncio.sleep", return_value=None) async def test_submit_image(self, _, __): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) for i, file_name in enumerate(("test.png", "test.jpg", "test.gif")): image = image_path(file_name) submission = await subreddit.submit_image(f"Test Title {i}", image) await submission.load() assert submission.author == pytest.placeholders.username assert submission.is_reddit_media_domain assert submission.title == f"Test Title {i}" @pytest.mark.usefixtures("tmp_path") @mock.patch("asyncio.sleep", return_value=None) async def test_submit_image__large(self, _): reddit = self.reddit reddit.read_only = False mock_data = ( '<?xml version="1.0" encoding="UTF-8"?>' "<Error>" "<Code>EntityTooLarge</Code>" "<Message>Your proposed upload exceeds the maximum allowed size</Message>" "<ProposedSize>20971528</ProposedSize>" "<MaxSizeAllowed>20971520</MaxSizeAllowed>" "<RequestId>23F056D6990D87E0</RequestId>" "<HostId>iYEVOuRfbLiKwMgHt2ewqQRIm0NWL79uiC2rPLj9P0PwW55MhjY2/O8d9JdKTf1iwzLjwWMnGQ=</HostId>" "</Error>" ) _post = reddit._core._requestor._http.post async def patch_request(url, *args, **kwargs): """Patch requests to return mock data on specific url.""" if "https://reddit-uploaded-media.s3-accelerate.amazonaws.com" in url: response = ClientResponse response.text = mock_data response.status = 400 return response return await _post(url, *args, **kwargs) reddit._core._requestor._http.post = patch_request fake_png = PNG_HEADER + b"\x1a" * 10 # Normally 1024 ** 2 * 20 (20 MB) with open(self.tmp_path.joinpath("fake_img.png"), "wb") as tempfile: tempfile.write(fake_png) with self.use_cassette(): with pytest.raises(TooLargeMediaException): subreddit = await reddit.subreddit("test") await subreddit.submit_image("test", tempfile.name) @mock.patch("asyncio.sleep", return_value=None) @mock.patch("aiohttp.client.ClientSession.ws_connect", return_value=WebsocketMock()) async def test_submit_image__bad_websocket(self, _, __): self.reddit.read_only = False with self.use_cassette("TestSubreddit.test_submit_image"): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) for file_name in ("test.png", "test.jpg"): image = image_path(file_name) with pytest.raises(ClientException): await subreddit.submit_image("Test Title", image) @mock.patch("asyncio.sleep", return_value=None) async def test_submit_image__bad_filetype(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) for file_name in ("test.mov", "test.mp4"): image = image_path(file_name) with pytest.raises(ClientException): await subreddit.submit_image("Test Title", image) @mock.patch("asyncio.sleep", return_value=None) @mock.patch( "aiohttp.client.ClientSession.ws_connect", return_value=WebsocketMock("l6evpd") ) # update with cassette async def test_submit_image__flair(self, _, __): flair_id = "6fc213da-cae7-11ea-9274-0e2407099e45" flair_text = "Test flair text" flair_class = "" self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) image = image_path("test.jpg") submission = await subreddit.submit_image( "Test Title", image, flair_id=flair_id, flair_text=flair_text ) await submission.load() assert submission.link_flair_css_class == flair_class assert submission.link_flair_text == flair_text @mock.patch("asyncio.sleep", return_value=None) @mock.patch( "aiohttp.client.ClientSession.ws_connect", return_value=WebsocketMock("l6ey7j") ) # update with cassette async def test_submit_image_chat(self, _, __): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) image = image_path("test.jpg") submission = await subreddit.submit_image( "Test Title", image, discussion_type="CHAT" ) await submission.load() assert submission.discussion_type == "CHAT" @mock.patch("asyncio.sleep", return_value=None) async def test_submit_image_verify_invalid(self, _): self.reddit.read_only = False self.reddit.validate_on_submit = True with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) image = image_path("test.jpg") with pytest.raises( (RedditAPIException, BadRequest) ): # waiting for prawcore fix await subreddit.submit_image( "gdfgfdgdgdgfgfdgdfgfdgfdg", image, without_websockets=True ) @mock.patch("asyncio.sleep", return_value=None) @mock.patch( "aiohttp.client.ClientSession.ws_connect", side_effect=BlockingIOError ) # happens with timeout=0 async def test_submit_image__timeout_1(self, _, __): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) image = image_path("test.jpg") with pytest.raises(WebSocketException): await subreddit.submit_image("Test Title", image) @mock.patch("asyncio.sleep", return_value=None) @mock.patch( "aiohttp.client.ClientSession.ws_connect", side_effect=socket.timeout # happens with timeout=0.00001 ) async def test_submit_image__timeout_2(self, _, __): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) image = image_path("test.jpg") with pytest.raises(WebSocketException): await subreddit.submit_image("Test Title", image) @mock.patch("asyncio.sleep", return_value=None) @mock.patch( "aiohttp.client.ClientSession.ws_connect", side_effect=TimeoutError, # could happen but Async PRAW should handle it ) async def test_submit_image__timeout_3(self, _, __): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) image = image_path("test.jpg") with pytest.raises(WebSocketException): await subreddit.submit_image("Test Title", image) @mock.patch("asyncio.sleep", return_value=None) @mock.patch( "aiohttp.client.ClientSession.ws_connect", side_effect=WebSocketError(None, None), # could happen but Async PRAW should handle it ) async def test_submit_image__timeout_4(self, _, __): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) image = image_path("test.jpg") with pytest.raises(WebSocketException): await subreddit.submit_image("Test Title", image) @mock.patch("asyncio.sleep", return_value=None) async def test_submit_image__without_websockets(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) for file_name in ("test.png", "test.jpg", "test.gif"): image = image_path(file_name) submission = await subreddit.submit_image( "Test Title", image, without_websockets=True ) assert submission is None @mock.patch("asyncio.sleep", return_value=None) @mock.patch( "aiohttp.client.ClientSession.ws_connect", return_value=WebsocketMock("l6g58s", "l6g5al"), # update with cassette ) async def test_submit_video(self, _, __): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) for i, file_name in enumerate(("test.mov", "test.mp4")): video = image_path(file_name) submission = await subreddit.submit_video(f"Test Title {i}", video) await submission.load() assert submission.author == pytest.placeholders.username # assert submission.is_reddit_media_domain # for some reason returns false assert submission.title == f"Test Title {i}" @mock.patch("asyncio.sleep", return_value=None) async def test_submit_video__bad_filetype(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) for file_name in ("test.jpg", "test.png", "test.gif"): video = image_path(file_name) with pytest.raises(ClientException): await subreddit.submit_video("Test Title", video) @mock.patch("asyncio.sleep", return_value=None) @mock.patch("aiohttp.client.ClientSession.ws_connect", return_value=WebsocketMock()) async def test_submit_video__bad_websocket(self, _, __): self.reddit.read_only = False with self.use_cassette("TestSubreddit.test_submit_video"): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) for file_name in ("test.mov", "test.mp4"): video = image_path(file_name) with pytest.raises(ClientException): await subreddit.submit_video("Test Title", video) @mock.patch("asyncio.sleep", return_value=None) @mock.patch( "aiohttp.client.ClientSession.ws_connect", return_value=WebsocketMock("l6g771") ) # update with cassette async def test_submit_video__flair(self, _, __): flair_id = "6fc213da-cae7-11ea-9274-0e2407099e45" flair_text = "Test flair text" flair_class = "" self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) image = image_path("test.mov") submission = await subreddit.submit_video( "Test Title", image, flair_id=flair_id, flair_text=flair_text ) assert submission.link_flair_css_class == flair_class assert submission.link_flair_text == flair_text @mock.patch("asyncio.sleep", return_value=None) @mock.patch( "aiohttp.client.ClientSession.ws_connect", return_value=WebsocketMock("l6gocy") ) # update with cassette async def test_submit_video_chat(self, _, __): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) image = image_path("test.mov") submission = await subreddit.submit_video( "Test Title", image, discussion_type="CHAT" ) await submission.load() assert submission.discussion_type == "CHAT" @mock.patch("asyncio.sleep", return_value=None) async def test_submit_video_verify_invalid(self, _): self.reddit.read_only = False self.reddit.validate_on_submit = True with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) image = image_path("test.mov") with pytest.raises( (RedditAPIException, BadRequest) ): # waiting for prawcore fix await subreddit.submit_video( "gdfgfdgdgdgfgfdgdfgfdgfdg", image, without_websockets=True ) @mock.patch("asyncio.sleep", return_value=None) @mock.patch( "aiohttp.client.ClientSession.ws_connect", return_value=WebsocketMock("l6gvvi", "l6gvx7"), # update with cassette ) async def test_submit_video__thumbnail(self, _, __): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) for video_name, thumb_name in ( ("test.mov", "test.jpg"), ("test.mp4", "test.png"), ): video = image_path(video_name) thumb = image_path(thumb_name) submission = await subreddit.submit_video( "Test Title", video, thumbnail_path=thumb ) await submission.load() assert submission.author == pytest.placeholders.username assert submission.is_video assert submission.title == "Test Title" @mock.patch("asyncio.sleep", return_value=None) @mock.patch( "aiohttp.client.ClientSession.ws_connect", side_effect=BlockingIOError ) # happens with timeout=0 async def test_submit_video__timeout_1(self, _, __): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) video = image_path("test.mov") with pytest.raises(WebSocketException): await subreddit.submit_video("Test Title", video) @mock.patch("asyncio.sleep", return_value=None) @mock.patch( "aiohttp.client.ClientSession.ws_connect", side_effect=socket.timeout # happens with timeout=0.00001 ) async def test_submit_video__timeout_2(self, _, __): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) video = image_path("test.mov") with pytest.raises(WebSocketException): await subreddit.submit_video("Test Title", video) @mock.patch("asyncio.sleep", return_value=None) @mock.patch( "aiohttp.client.ClientSession.ws_connect", side_effect=TimeoutError, # could happen but Async PRAW should handle it ) async def test_submit_video__timeout_3(self, _, __): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) video = image_path("test.mov") with pytest.raises(WebSocketException): await subreddit.submit_video("Test Title", video) @mock.patch("asyncio.sleep", return_value=None) @mock.patch( "aiohttp.client.ClientSession.ws_connect", side_effect=WebSocketError(None, None), # could happen but Async PRAW should handle it ) async def test_submit_video__timeout_4(self, _, __): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) video = image_path("test.mov") with pytest.raises(WebSocketException): await subreddit.submit_video("Test Title", video) @mock.patch("asyncio.sleep", return_value=None) @mock.patch( "aiohttp.client.ClientSession.ws_connect", return_value=WebsocketMock("l6gtwa", "l6gty1"), # update with cassette ) async def test_submit_video__videogif(self, _, __): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) for file_name in ("test.mov", "test.mp4"): video = image_path(file_name) submission = await subreddit.submit_video( "Test Title", video, videogif=True ) assert submission.author == pytest.placeholders.username assert submission.is_video assert submission.title == "Test Title" @mock.patch("asyncio.sleep", return_value=None) async def test_submit_video__without_websockets(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) for file_name in ("test.mov", "test.mp4"): video = image_path(file_name) submission = await subreddit.submit_video( "Test Title", video, without_websockets=True ) assert submission is None async def test_subscribe(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await subreddit.subscribe() async def test_subscribe__multiple(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await subreddit.subscribe( ["redditdev", await self.reddit.subreddit("iama")] ) async def test_traffic(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): traffic = await subreddit.traffic() assert isinstance(traffic, dict) async def test_traffic__not_public(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit("announcements") with self.use_cassette(): with pytest.raises(NotFound): await subreddit.traffic() async def test_unsubscribe(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await subreddit.unsubscribe() async def test_unsubscribe__multiple(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await subreddit.unsubscribe( ["redditdev", await self.reddit.subreddit("iama")] ) class TestSubredditFilters(IntegrationTest): @mock.patch("asyncio.sleep", return_value=None) async def test__aiter__all(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit("all") filters = await self.async_list(subreddit.filters) assert len(filters) > 0 assert all(isinstance(x, Subreddit) for x in filters) @mock.patch("asyncio.sleep", return_value=None) async def test__aiter__mod(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit("mod") with self.use_cassette(): filters = await self.async_list(subreddit.filters) assert len(filters) > 0 assert all(isinstance(x, Subreddit) for x in filters) @mock.patch("asyncio.sleep", return_value=None) async def test_add(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit("all") await subreddit.filters.add("redditdev") @mock.patch("asyncio.sleep", return_value=None) async def test_add__subreddit_model(self, _): self.reddit.read_only = False with self.use_cassette("TestSubredditFilters.test_add"): subreddit = await self.reddit.subreddit("all") await subreddit.filters.add(await self.reddit.subreddit("redditdev")) # @mock.patch("asyncio.sleep", return_value=None) # FIXME: no longer raises not found; same with praw # async def test_add__non_special(self, _): # self.reddit.read_only = False # with self.use_cassette(): # with pytest.raises(NotFound): # subreddit = await self.reddit.subreddit("redditdev") # await subreddit.filters.add("redditdev") @mock.patch("asyncio.sleep", return_value=None) async def test_remove(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit("mod") await subreddit.filters.remove("redditdev") @mock.patch("asyncio.sleep", return_value=None) async def test_remove__subreddit_model(self, _): self.reddit.read_only = False with self.use_cassette("TestSubredditFilters.test_remove"): subreddit = await self.reddit.subreddit("mod") await subreddit.filters.remove(await self.reddit.subreddit("redditdev")) # @mock.patch("asyncio.sleep", return_value=None) # FIXME: no longer rases not found; same with praw # async def test_remove__non_special(self, _): # self.reddit.read_only = False # with self.use_cassette(): # with pytest.raises(NotFound): # subreddit = await self.reddit.subreddit("redditdev") # await subreddit.filters.remove("redditdev") class TestSubredditFlair(IntegrationTest): REDDITOR = pytest.placeholders.username async def test__call(self): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) mapping = subreddit.flair() assert len(await self.async_list(mapping)) > 0 assert all([isinstance(x["user"], Redditor) async for x in mapping]) async def test__call__user_filter(self): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) mapping = subreddit.flair(redditor=self.REDDITOR) assert len(await self.async_list(mapping)) == 1 async def test_configure(self): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) await subreddit.flair.configure( position=None, self_assign=True, link_position=None, link_self_assign=True, ) async def test_configure__defaults(self): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) await subreddit.flair.configure() async def test_delete(self): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) await subreddit.flair.delete(pytest.placeholders.username) @mock.patch("asyncio.sleep", return_value=None) async def test_delete_all(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) response = await subreddit.flair.delete_all() assert len(response) == 1 assert all("removed" in x["status"] for x in response) async def test_set__flair_id(self): self.reddit.read_only = False with self.use_cassette(): redditor = await self.reddit.redditor(pytest.placeholders.username) flair = "c99ff6d0-c559-11ea-b93b-0ef0f80279f1" subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) await subreddit.flair.set( redditor, "redditor flair", flair_template_id=flair ) async def test_set__flair_id_default_text(self): self.reddit.read_only = False with self.use_cassette(): redditor = await self.reddit.redditor(pytest.placeholders.username) flair = "c99ff6d0-c559-11ea-b93b-0ef0f80279f1" subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) await subreddit.flair.set(redditor, flair_template_id=flair) async def test_set__redditor(self): self.reddit.read_only = False with self.use_cassette(): redditor = await self.reddit.redditor(pytest.placeholders.username) subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) await subreddit.flair.set(redditor, "redditor flair") async def test_set__redditor_css_only(self): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) await subreddit.flair.set( pytest.placeholders.username, css_class="some class" ) async def test_set__redditor_string(self): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) await subreddit.flair.set( pytest.placeholders.username, "new flair", "some class" ) async def test_update(self): self.reddit.read_only = False with self.use_cassette(): redditor = await self.reddit.redditor(pytest.placeholders.username) flair_list = [ redditor, "spez", {"user": "bsimpson"}, {"user": "spladug", "flair_text": "", "flair_css_class": ""}, ] subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) response = await subreddit.flair.update( flair_list, css_class="async default" ) assert all(x["ok"] for x in response) assert not any(x["errors"] for x in response) assert not any(x["warnings"] for x in response) assert len([x for x in response if "added" in x["status"]]) == 3 assert len([x for x in response if "removed" in x["status"]]) == 1 for i, name in enumerate([str(redditor), "spez", "bsimpson", "spladug"]): assert name in response[i]["status"] async def test_update__comma_in_text(self): self.reddit.read_only = False flair_list = [ {"user": "bsimpson"}, {"user": "spladug", "flair_text": "a,b"}, ] with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) response = await subreddit.flair.update( flair_list, css_class="async default" ) assert all(x["ok"] for x in response) @mock.patch("asyncio.sleep", return_value=None) async def test_update_quotes(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) redditor = await self.reddit.user.me() response = await subreddit.flair.update( [redditor], text='"testing"', css_class="testing" ) assert all(x["ok"] for x in response) flair = await self.async_next(subreddit.flair(redditor)) assert flair["flair_text"] == '"testing"' assert flair["flair_css_class"] == "testing" class TestSubredditFlairTemplates(IntegrationTest): async def test__aiter(self): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) templates = await self.async_list(subreddit.flair.templates) assert len(templates) == 1 for flair_template in templates: assert flair_template["id"] async def test_add(self): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) await subreddit.flair.templates.add( "PRAW", css_class="myCSS", background_color="#ABCDEF" ) async def test_clear(self): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) await subreddit.flair.templates.clear() @mock.patch("asyncio.sleep", return_value=None) async def test_delete(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) template = await self.async_next(subreddit.flair.templates) await subreddit.flair.templates.delete(template["id"]) @mock.patch("asyncio.sleep", return_value=None) async def test_update(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) template = await self.async_next(subreddit.flair.templates) await subreddit.flair.templates.update( template["id"], "PRAW updated", css_class="myCSS", text_color="dark", background_color="#00FFFF", ) @mock.patch("asyncio.sleep", return_value=None) async def test_update_invalid(self, _): self.reddit.read_only = False with self.use_cassette(): with pytest.raises(InvalidFlairTemplateID): subreddit = await self.reddit.subreddit( pytest.placeholders.test_subreddit ) await subreddit.flair.templates.update( "fake id", "PRAW updated", css_class="myCSS", text_color="dark", background_color="#00FFFF", fetch=True, ) @mock.patch("asyncio.sleep", return_value=None) async def test_update_fetch(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) template = await self.async_next(subreddit.flair.templates) await subreddit.flair.templates.update( template["id"], "PRAW updated", css_class="myCSS", text_color="dark", background_color="#00FFFF", fetch=True, ) @mock.patch("asyncio.sleep", return_value=None) async def test_update_fetch_no_css_class(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) template = await self.async_next(subreddit.flair.templates) await subreddit.flair.templates.update( template["id"], "PRAW updated", text_color="dark", background_color="#00FFFF", fetch=True, ) @mock.patch("asyncio.sleep", return_value=None) async def test_update_fetch_no_text(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) template = await self.async_next(subreddit.flair.templates) await subreddit.flair.templates.update( template["id"], css_class="myCSS", text_color="dark", background_color="#00FFFF", fetch=True, ) @mock.patch("asyncio.sleep", return_value=None) async def test_update_fetch_no_text_or_css_class(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) template = await self.async_next(subreddit.flair.templates) await subreddit.flair.templates.update( template["id"], text_color="dark", background_color="#00FFFF", fetch=True, ) @mock.patch("asyncio.sleep", return_value=None) async def test_update_fetch_only(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) template = await self.async_next(subreddit.flair.templates) await subreddit.flair.templates.update(template["id"], fetch=True) newtemplate = list( filter( lambda _template: _template["id"] == template["id"], [flair async for flair in subreddit.flair.templates], ) )[0] assert newtemplate == template @mock.patch("asyncio.sleep", return_value=None) async def test_update_false(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) template = await self.async_next(subreddit.flair.templates) await subreddit.flair.templates.update( template["id"], text_editable=True, fetch=True ) await subreddit.flair.templates.update( template["id"], text_editable=False, fetch=True ) newtemplate = list( filter( lambda _template: _template["id"] == template["id"], [flair async for flair in subreddit.flair.templates], ) )[0] assert newtemplate["text_editable"] is False class TestSubredditLinkFlairTemplates(IntegrationTest): async def test__aiter(self): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) templates = await self.async_list(subreddit.flair.link_templates) assert len(templates) == 2 for template in templates: assert template["id"] assert isinstance(template["richtext"], list) assert all(isinstance(item, dict) for item in template["richtext"]) async def test_add(self): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) await subreddit.flair.link_templates.add( "PRAW", css_class="myCSS", text_color="light" ) async def test_clear(self): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) await subreddit.flair.link_templates.clear() class TestSubredditListings(IntegrationTest): async def test_comments(self): with self.use_cassette(): subreddit = await self.reddit.subreddit("askreddit") comments = await self.async_list(subreddit.comments()) assert len(comments) == 100 async def test_controversial(self): with self.use_cassette(): subreddit = await self.reddit.subreddit("askreddit") submissions = await self.async_list(subreddit.controversial()) assert len(submissions) == 100 async def test_gilded(self): with self.use_cassette(): subreddit = await self.reddit.subreddit("askreddit") submissions = await self.async_list(subreddit.gilded()) assert len(submissions) >= 50 async def test_hot(self): with self.use_cassette(): subreddit = await self.reddit.subreddit("askreddit") submissions = await self.async_list(subreddit.hot()) assert len(submissions) == 100 async def test_new(self): with self.use_cassette(): subreddit = await self.reddit.subreddit("askreddit") submissions = await self.async_list(subreddit.new()) assert len(submissions) == 100 async def test_random_rising(self): with self.use_cassette(): subreddit = await self.reddit.subreddit("askreddit") submissions = await self.async_list(subreddit.random_rising()) assert len(submissions) == 91 async def test_rising(self): with self.use_cassette(): subreddit = await self.reddit.subreddit("askreddit") submissions = await self.async_list(subreddit.rising()) assert len(submissions) == 100 async def test_top(self): with self.use_cassette(): subreddit = await self.reddit.subreddit("askreddit") submissions = await self.async_list(subreddit.top()) assert len(submissions) == 100 class TestSubredditModeration(IntegrationTest): async def test_accept_invite__no_invite(self): self.reddit.read_only = False with self.use_cassette(): with pytest.raises(RedditAPIException) as excinfo: subreddit = await self.reddit.subreddit( pytest.placeholders.test_subreddit ) await subreddit.mod.accept_invite() assert excinfo.value.items[0].error_type == "NO_INVITE_FOUND" async def test_edited(self): self.reddit.read_only = False with self.use_cassette(): count = 0 subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) async for item in subreddit.mod.edited(): assert isinstance(item, (Comment, Submission)) count += 1 assert count == 100 async def test_edited__only_comments(self): self.reddit.read_only = False with self.use_cassette(): count = 0 subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) async for item in subreddit.mod.edited(only="comments"): assert isinstance(item, Comment) count += 1 assert count == 100 async def test_edited__only_submissions(self): self.reddit.read_only = False with self.use_cassette(): count = 0 subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) async for item in subreddit.mod.edited(only="submissions"): assert isinstance(item, Submission) count += 1 assert count > 0 async def test_inbox(self): self.reddit.read_only = False with self.use_cassette(): count = 0 subreddit = await self.reddit.subreddit("all") async for item in subreddit.mod.inbox(): assert isinstance(item, SubredditMessage) count += 1 assert count == 100 async def test_log(self): self.reddit.read_only = False with self.use_cassette(): count = 0 subreddit = await self.reddit.subreddit("mod") async for item in subreddit.mod.log(): assert isinstance(item, ModAction) count += 1 assert count == 100 async def test_log__filters(self): self.reddit.read_only = False with self.use_cassette(): count = 0 redditor = await self.reddit.user.me() subreddit = await self.reddit.subreddit("mod") async for item in subreddit.mod.log(action="invitemoderator", mod=redditor): assert isinstance(item, ModAction) assert item.action == "invitemoderator" assert isinstance(item.mod, Redditor) assert item.mod == pytest.placeholders.username count += 1 assert count > 0 async def test_modqueue(self): self.reddit.read_only = False with self.use_cassette(): count = 0 subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) async for item in subreddit.mod.modqueue(): assert isinstance(item, (Comment, Submission)) count += 1 assert count > 0 async def test_modqueue__only_comments(self): self.reddit.read_only = False with self.use_cassette(): count = 0 subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) async for item in subreddit.mod.modqueue(only="comments"): assert isinstance(item, Comment) count += 1 assert count > 0 async def test_modqueue__only_submissions(self): self.reddit.read_only = False with self.use_cassette(): count = 0 subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) async for item in subreddit.mod.modqueue(only="submissions"): assert isinstance(item, Submission) count += 1 assert count > 0 async def test_reports(self): self.reddit.read_only = False with self.use_cassette(): count = 0 subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) async for item in subreddit.mod.reports(): assert isinstance(item, (Comment, Submission)) count += 1 assert count == 100 async def test_reports__only_comments(self): self.reddit.read_only = False with self.use_cassette(): count = 0 subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) async for item in subreddit.mod.reports(only="comments"): assert isinstance(item, Comment) count += 1 assert count > 0 async def test_reports__only_submissions(self): self.reddit.read_only = False with self.use_cassette(): count = 0 subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) async for item in subreddit.mod.reports(only="submissions"): assert isinstance(item, Submission) count += 1 assert count == 100 async def test_spam(self): self.reddit.read_only = False with self.use_cassette(): count = 0 subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) async for item in subreddit.mod.spam(): assert isinstance(item, (Comment, Submission)) count += 1 assert count > 0 async def test_spam__only_comments(self): self.reddit.read_only = False with self.use_cassette(): count = 0 subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) async for item in subreddit.mod.spam(only="comments"): assert isinstance(item, Comment) count += 1 assert count > 0 async def test_spam__only_submissions(self): self.reddit.read_only = False with self.use_cassette(): count = 0 subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) async for item in subreddit.mod.spam(only="submissions"): assert isinstance(item, Submission) count += 1 assert count > 0 async def test_unmoderated(self): self.reddit.read_only = False with self.use_cassette(): count = 0 subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) async for item in subreddit.mod.unmoderated(): assert isinstance(item, (Comment, Submission)) count += 1 assert count > 0 async def test_unread(self): self.reddit.read_only = False with self.use_cassette(): count = 0 subreddit = await self.reddit.subreddit("all") async for item in subreddit.mod.unread(): assert isinstance(item, SubredditMessage) count += 1 assert count > 0 @mock.patch("asyncio.sleep", return_value=None) async def test_update(self, _): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) before_settings = await subreddit.mod.settings() new_title = f"{before_settings['title']}x" new_title = ( "x" if (len(new_title) >= 20 and "placeholder" not in new_title) else new_title ) await subreddit.mod.update(title=new_title) await subreddit.load() assert subreddit.title == new_title after_settings = await subreddit.mod.settings() # Ensure that nothing has changed besides what was specified. before_settings["title"] = new_title assert before_settings == after_settings class TestSubredditModmail(IntegrationTest): async def test_bulk_read(self): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) conversations = await subreddit.modmail.bulk_read(state="new") for conversation in conversations: assert isinstance(conversation, ModmailConversation) @mock.patch("asyncio.sleep", return_value=None) async def test_call(self, _): self.reddit.read_only = False conversation_id = "fjhla" subreddit = await self.reddit.subreddit("all") with self.use_cassette(): conversation = await subreddit.modmail(conversation_id) assert isinstance(conversation.user, Redditor) for message in conversation.messages: assert isinstance(message, ModmailMessage) for action in conversation.mod_actions: assert isinstance(action, ModmailAction) @mock.patch("asyncio.sleep", return_value=None) async def test_call__internal(self, _): self.reddit.read_only = False conversation_id = "ff1r8" subreddit = await self.reddit.subreddit("all") with self.use_cassette(): conversation = await subreddit.modmail(conversation_id) for message in conversation.messages: assert isinstance(message, ModmailMessage) for action in conversation.mod_actions: assert isinstance(action, ModmailAction) @mock.patch("asyncio.sleep", return_value=None) async def test_call__mark_read(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit("all") with self.use_cassette(): conversation = await subreddit.modmail("fccdg", mark_read=True) assert conversation.last_unread is None @mock.patch("asyncio.sleep", return_value=None) async def test_conversations(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit("all") with self.use_cassette(): async for conversation in subreddit.modmail.conversations(): assert isinstance(conversation, ModmailConversation) assert isinstance(conversation.authors[0], Redditor) @mock.patch("asyncio.sleep", return_value=None) async def test_conversations__params(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit("all") with self.use_cassette(): async for conversation in subreddit.modmail.conversations(state="mod"): assert conversation.is_internal @mock.patch("asyncio.sleep", return_value=None) async def test_conversations__other_subreddits(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): conversations = await self.async_list( subreddit.modmail.conversations(other_subreddits=["dankmemes"]) ) assert len(set(conversation.owner for conversation in conversations)) > 1 @mock.patch("asyncio.sleep", return_value=None) async def test_create(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): redditor = await self.reddit.redditor(pytest.placeholders.username) conversation = await subreddit.modmail.create("Subject", "Body", redditor) assert isinstance(conversation, ModmailConversation) async def test_subreddits(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): async for subreddit in subreddit.modmail.subreddits(): assert isinstance(subreddit, Subreddit) async def test_unread_count(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): assert isinstance(await subreddit.modmail.unread_count(), dict) class TestSubredditQuarantine(IntegrationTest): @mock.patch("asyncio.sleep", return_value=None) async def test_opt_in(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit("tiananmenaquarefalse") with self.use_cassette(): with pytest.raises(Forbidden): await self.async_next(subreddit.top()) await subreddit.quaran.opt_in() assert isinstance(await self.async_next(subreddit.top()), Submission) @mock.patch("asyncio.sleep", return_value=None) async def test_opt_out(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit("tiananmenaquarefalse") with self.use_cassette(): await subreddit.quaran.opt_out() with pytest.raises(Forbidden): await self.async_next(subreddit.new()) class TestSubredditRelationships(IntegrationTest): REDDITOR = "pyapitestuser3" async def add_remove(self, base, user, relationship): relationship = getattr(base, relationship) await relationship.add(user) relationships = await self.async_list(relationship()) assert user in relationships redditor = relationships[relationships.index(user)] assert isinstance(redditor, Redditor) assert hasattr(redditor, "date") await relationship.remove(user) assert user not in await self.async_list(relationship()) async def test_banned(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await self.add_remove(subreddit, self.REDDITOR, "banned") async def test_banned__user_filter(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) banned = subreddit.banned(redditor="pyapitestuser3") with self.use_cassette(): assert len(await self.async_list(banned)) == 1 async def test_contributor(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await self.add_remove(subreddit, self.REDDITOR, "contributor") @mock.patch("asyncio.sleep", return_value=None) async def test_contributor_leave(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await subreddit.contributor.leave() async def test_contributor__user_filter(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) contributor = subreddit.contributor(redditor="pyapitestuser3") with self.use_cassette(): assert len(await self.async_list(contributor)) == 1 @mock.patch("asyncio.sleep", return_value=None) async def test_moderator(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): # Moderators can only be invited. # As of 2016-03-18 there is no API endpoint to get the moderator # invite list. await subreddit.moderator.add(self.REDDITOR) assert self.REDDITOR not in await subreddit.moderator() @mock.patch("asyncio.sleep", return_value=None) async def test_moderator_aiter(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): async for moderator in subreddit.moderator: assert isinstance(moderator, Redditor) @mock.patch("asyncio.sleep", return_value=None) async def test_moderator__limited_permissions(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): # Moderators can only be invited. # As of 2016-03-18 there is no API endpoint to get the moderator # invite list. await subreddit.moderator.add(self.REDDITOR, permissions=["access", "wiki"]) assert self.REDDITOR not in await subreddit.moderator() async def test_moderator_invite__invalid_perm(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): with pytest.raises(RedditAPIException) as excinfo: await subreddit.moderator.invite(self.REDDITOR, permissions=["a"]) assert excinfo.value.items[0].error_type == "INVALID_PERMISSIONS" @mock.patch("asyncio.sleep", return_value=None) async def test_moderator_invite__no_perms(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): # Moderators can only be invited. # As of 2016-03-18 there is no API endpoint to get the moderator # invite list. await subreddit.moderator.invite(self.REDDITOR, permissions=[]) assert self.REDDITOR not in await subreddit.moderator() @mock.patch("asyncio.sleep", return_value=None) async def test_moderator_invited_moderators(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): invited = subreddit.moderator.invited() assert isinstance(invited, ListingGenerator) async for moderator in invited: assert isinstance(moderator, Redditor) @mock.patch("asyncio.sleep", return_value=None) async def test_moderator_leave(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await subreddit.moderator.leave() async def test_moderator_update(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await subreddit.moderator.update( pytest.placeholders.username, permissions=["config"] ) async def test_moderator_update_invite(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await subreddit.moderator.update_invite(self.REDDITOR, permissions=["mail"]) async def test_moderator__user_filter(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): moderator = await subreddit.moderator(redditor=pytest.placeholders.username) assert len(moderator) == 1 assert "mod_permissions" in moderator[0].__dict__ @mock.patch("asyncio.sleep", return_value=None) async def test_muted(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await self.add_remove(subreddit, self.REDDITOR, "muted") async def test_moderator_remove_invite(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await subreddit.moderator.remove_invite(self.REDDITOR) async def test_wiki_banned(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await self.add_remove(subreddit.wiki, self.REDDITOR, "banned") async def test_wiki_contributor(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await self.add_remove(subreddit.wiki, self.REDDITOR, "contributor") class TestSubredditStreams(IntegrationTest): @mock.patch("asyncio.sleep", return_value=None) async def test_comments(self, _): subreddit = await self.reddit.subreddit("all") with self.use_cassette(): generator = subreddit.stream.comments() for i in range(400): assert isinstance(await self.async_next(generator), Comment) @mock.patch("asyncio.sleep", return_value=None) async def test_comments__with_pause(self, _): subreddit = await self.reddit.subreddit("askreddit") with self.use_cassette(): comment_stream = subreddit.stream.comments(pause_after=0) comment_count = 1 pause_count = 1 comment = await self.async_next(comment_stream) while comment is not None: comment_count += 1 comment = await self.async_next(comment_stream) while comment is None: pause_count += 1 comment = await self.async_next(comment_stream) assert comment_count == 108 assert pause_count == 3 @mock.patch("asyncio.sleep", return_value=None) async def test_comments__with_skip_existing(self, _): with self.use_cassette("TestSubredditStreams.test_comments__with_pause"): subreddit = await self.reddit.subreddit("askreddit") generator = subreddit.stream.comments(skip_existing=True) count = 0 try: async for comment in generator: count += 1 except TypeError: pass # This test uses the same cassette as test_comments which shows # that there are at least 100 comments in the stream. assert count < 102 @mock.patch("asyncio.sleep", return_value=None) async def test_submissions(self, _): with self.use_cassette(): subreddit = await self.reddit.subreddit("all") generator = subreddit.stream.submissions() for i in range(101): assert isinstance(await self.async_next(generator), Submission) @mock.patch("asyncio.sleep", return_value=None) async def test_submissions__with_pause(self, _): with self.use_cassette("TestSubredditStreams.test_submissions"): subreddit = await self.reddit.subreddit("all") generator = subreddit.stream.submissions(pause_after=-1) submission = await self.async_next(generator) submission_count = 0 while submission is not None: submission_count += 1 submission = await self.async_next(generator) assert submission_count == 100 @mock.patch("asyncio.sleep", return_value=None) async def test_submissions__with_pause_and_skip_after(self, _): with self.use_cassette("TestSubredditStreams.test_submissions"): subreddit = await self.reddit.subreddit("all") generator = subreddit.stream.submissions(pause_after=-1, skip_existing=True) submission = await self.async_next(generator) assert submission is None # The first thing yielded should be None submission_count = 0 submission = await self.async_next(generator) while submission is not None: submission_count += 1 submission = await self.async_next(generator) assert submission_count < 100 class TestSubredditModerationStreams(IntegrationTest): @mock.patch("asyncio.sleep", return_value=None) async def test_edited(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit("mod") with self.use_cassette(): generator = subreddit.mod.stream.edited() for i in range(101): assert isinstance( await self.async_next(generator), (Comment, Submission) ) @mock.patch("asyncio.sleep", return_value=None) async def test_log(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit("mod") with self.use_cassette(): generator = subreddit.mod.stream.log() for i in range(101): assert isinstance(await self.async_next(generator), ModAction) @mock.patch("asyncio.sleep", return_value=None) async def test_modmail_conversations(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit("mod") with self.use_cassette(): generator = subreddit.mod.stream.modmail_conversations() for i in range(10): assert isinstance(await self.async_next(generator), ModmailConversation) @mock.patch("asyncio.sleep", return_value=None) async def test_modqueue(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit("mod") with self.use_cassette(): generator = subreddit.mod.stream.modqueue() for i in range(10): assert isinstance( await self.async_next(generator), (Comment, Submission) ) @mock.patch("asyncio.sleep", return_value=None) async def test_spam(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit("mod") with self.use_cassette(): generator = subreddit.mod.stream.spam() for i in range(101): assert isinstance( await self.async_next(generator), (Comment, Submission) ) @mock.patch("asyncio.sleep", return_value=None) async def test_reports(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit("mod") with self.use_cassette(): generator = subreddit.mod.stream.reports() for i in range(10): assert isinstance( await self.async_next(generator), (Comment, Submission) ) @mock.patch("asyncio.sleep", return_value=None) async def test_unmoderated(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit("mod") with self.use_cassette(): generator = subreddit.mod.stream.unmoderated() for i in range(101): assert isinstance( await self.async_next(generator), (Comment, Submission) ) @mock.patch("asyncio.sleep", return_value=None) async def test_unread(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit("mod") with self.use_cassette(): generator = subreddit.mod.stream.unread() for i in range(2): assert isinstance(await self.async_next(generator), SubredditMessage) class TestSubredditStylesheet(IntegrationTest): async def test_call(self): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): stylesheet = await subreddit.stylesheet() assert isinstance(stylesheet, Stylesheet) assert len(stylesheet.images) > 0 assert stylesheet.stylesheet != "" async def test_delete_banner(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await subreddit.stylesheet.delete_banner() async def test_delete_banner_additional_image(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await subreddit.stylesheet.delete_banner_additional_image() async def test_delete_banner_hover_image(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await subreddit.stylesheet.delete_banner_hover_image() async def test_delete_header(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await subreddit.stylesheet.delete_header() async def test_delete_image(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await subreddit.stylesheet.delete_image("praw") async def test_delete_mobile_header(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await subreddit.stylesheet.delete_mobile_header() async def test_delete_mobile_icon(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await subreddit.stylesheet.delete_mobile_icon() async def test_update(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await subreddit.stylesheet.update("p { color: red; }") async def test_update__with_reason(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await subreddit.stylesheet.update("div { color: red; }", reason="use div") async def test_upload(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): response = await subreddit.stylesheet.upload( "asyncpraw", image_path("white-square.png") ) assert response["img_src"].endswith(".png") async def test_upload__invalid(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): with pytest.raises(RedditAPIException) as excinfo: await subreddit.stylesheet.upload( "asyncpraw", image_path("invalid.jpg") ) assert excinfo.value.items[0].error_type == "IMAGE_ERROR" async def test_upload__invalid_ext(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): with pytest.raises(RedditAPIException) as excinfo: await subreddit.stylesheet.upload( "asyncpraw", image_path("white-square.png") ) assert excinfo.value.items[0].error_type == "BAD_CSS_NAME" async def test_upload__too_large(self): self.reddit.read_only = False with self.use_cassette(): subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with pytest.raises(TooLarge): await subreddit.stylesheet.upload( "asyncpraw", image_path("too_large.jpg") ) @mock.patch("asyncio.sleep", return_value=None) async def test_upload_banner__jpg(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await subreddit.stylesheet.upload_banner(image_path("white-square.jpg")) @mock.patch("asyncio.sleep", return_value=None) async def test_upload_banner__png(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await subreddit.stylesheet.upload_banner(image_path("white-square.png")) @mock.patch("asyncio.sleep", return_value=None) async def test_upload_banner_additional_image__jpg(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await subreddit.stylesheet.upload_banner_additional_image( image_path("white-square.jpg") ) @mock.patch("asyncio.sleep", return_value=None) async def test_upload_banner_additional_image__png(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await subreddit.stylesheet.upload_banner_additional_image( image_path("white-square.png") ) @mock.patch("asyncio.sleep", return_value=None) async def test_upload_banner_additional_image__align(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): for alignment in ("left", "centered", "right"): await subreddit.stylesheet.upload_banner_additional_image( image_path("white-square.png"), align=alignment ) @mock.patch("asyncio.sleep", return_value=None) async def test_upload_banner_hover_image__jpg(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await subreddit.stylesheet.upload_banner_additional_image( image_path("white-square.png") ) await subreddit.stylesheet.upload_banner_hover_image( image_path("white-square.jpg") ) @mock.patch("asyncio.sleep", return_value=None) async def test_upload_banner_hover_image__png(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): await subreddit.stylesheet.upload_banner_additional_image( image_path("white-square.jpg") ) await subreddit.stylesheet.upload_banner_hover_image( image_path("white-square.png") ) async def test_upload_header__jpg(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): response = await subreddit.stylesheet.upload_header( image_path("white-square.jpg") ) assert response["img_src"].endswith(".jpg") async def test_upload_header__png(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): response = await subreddit.stylesheet.upload_header( image_path("white-square.png") ) assert response["img_src"].endswith(".png") async def test_upload_mobile_header(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): response = await subreddit.stylesheet.upload_mobile_header( image_path("header.jpg") ) assert response["img_src"].endswith(".jpg") async def test_upload_mobile_icon(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): response = await subreddit.stylesheet.upload_mobile_icon( image_path("icon.jpg") ) assert response["img_src"].endswith(".jpg") @mock.patch("asyncio.sleep", return_value=None) async def test_upload__others_invalid(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): for method in [ "upload_header", "upload_mobile_header", "upload_mobile_icon", ]: with pytest.raises(RedditAPIException) as excinfo: await getattr(subreddit.stylesheet, method)( image_path("invalid.jpg") ) assert excinfo.value.items[0].error_type == "IMAGE_ERROR" async def test_upload__others_too_large(self): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): for method in [ "upload_header", "upload_mobile_header", "upload_mobile_icon", ]: with pytest.raises(TooLarge): await getattr( subreddit.stylesheet, method, )(image_path("too_large.jpg")) class TestSubredditWiki(IntegrationTest): @mock.patch("asyncio.sleep", return_value=None) async def test__aiter(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): count = 0 async for wikipage in subreddit.wiki: assert isinstance(wikipage, WikiPage) count += 1 assert count > 0 @mock.patch("asyncio.sleep", return_value=None) async def test_create(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): wikipage = await subreddit.wiki.create( "Async PRAW New Page", "This is the new wiki page" ) await wikipage.load() assert wikipage.name == "async_praw_new_page" assert wikipage.content_md == "This is the new wiki page" @mock.patch("asyncio.sleep", return_value=None) async def test_revisions(self, _): self.reddit.read_only = False subreddit = await self.reddit.subreddit(pytest.placeholders.test_subreddit) with self.use_cassette(): count = 0 async for revision in subreddit.wiki.revisions(limit=2): count += 1 assert isinstance(revision["author"], Redditor) assert isinstance(revision["page"], WikiPage) assert count == 2
from discord import Role, TextChannel, VoiceChannel, Embed, Color, utils, Emoji, Member, User, File from discord.ext.commands import command, group from cassandra.bot import Union from random import choice, randint, sample from os import environ from bs4 import BeautifulSoup from enum import Enum import asyncio import datetime from github import Github import sys import json FULLWIDTH_OFFSET = 65248 class RPS(Enum): rock = "\N{MOYAI}" paper = "\N{PAGE FACING UP}" scissors = "\N{BLACK SCISSORS}" class RPSParser: def __init__(self, argument): argument = argument.lower() if argument == "rock": self.choice = RPS.rock elif argument == "paper": self.choice = RPS.paper elif argument == "scissors": self.choice = RPS.scissors else: return class Server: def __init__(self, bot): self.bot = bot self.self_assignable_roles = [] self.configurable_roles = [] try: self._weather_key = environ["API_WEATHER"] self._nasa_key = environ['API_NASA'] except KeyError: self._weather_key = bot.api_keys["WEATHER"] self._nasa_key = bot.api_keys["NASA"] def populateRoleLists(self, ctx): self.self_assignable_roles = { "ping": utils.get(ctx.guild.roles, name="ping"), "battlenet": utils.get(ctx.guild.roles, name="battlenet"), "gamenight": utils.get(ctx.guild.roles, name="gamenight"), "helpliner": utils.get(ctx.guild.roles, name="helpliner"), "politics": utils.get(ctx.guild.roles, name="Politics Opt-In"), "support": utils.get(ctx.guild.roles, name="Support Opt-In") , "archives": utils.get(ctx.guild.roles, name="Archivist") } self.configurable_roles = [ utils.get(ctx.guild.roles, name="ping"), utils.get(ctx.guild.roles, name="gamenight"), utils.get(ctx.guild.roles, name="helpliner") ] @group() async def role(self, ctx): """Add or remove an available role.""" if ctx.invoked_subcommand is None: await ctx.send(f"Invalid Action! Do `{ctx.prefix}help role` for more information. {ctx.author.mention}") @role.command( name="add", aliases=["+"] ) async def add_(self, ctx, role): """ Adds a role. If the argument given is not a valid role in the guild, it will safely ignore it. If the argument is a valid role in the guild and is not in the available roles list, it will flag it as invalid. """ if(len(self.self_assignable_roles) == 0): self.populateRoleLists(ctx) if role in self.self_assignable_roles: roleobj = self.self_assignable_roles[role] await ctx.author.add_roles(roleobj, reason="Used role command") await ctx.send(f"Added role `{roleobj}` to {ctx.author.mention}") else: await ctx.send( f""" `{role}` is not a valid role! Do `{ctx.prefix}help role add` for more information. {ctx.author.mention} """ ) @role.command( name="remove", aliases=["-"] ) async def remove_(self, ctx, role): """ Removes a role. If the argument given is not a valid role in the guild, it will safely ignore it. If the argument is a valid role in the guild and is not in the available roles list, it will flag it as invalid. """ if(len(self.self_assignable_roles) == 0): self.populateRoleLists(ctx) if role in self.self_assignable_roles: roleobj = self.self_assignable_roles[role] await ctx.author.remove_roles(roleobj, reason="Used role command") await ctx.send(f"Removed `{roleobj}` role from {ctx.author.mention}.") else: await ctx.send( f""" `{role}` is not a valid role! Do `{ctx.prefix}help role remove` for more information. {ctx.author.mention} """ ) @role.command( name="enable", aliases=["e"] ) async def enable_(self, ctx, role: Role): """ Enables mention feature of role """ if(len(self.configurable_roles) == 0): self.populateRoleLists(ctx) if utils.get(ctx.guild.roles, name="Mods") in ctx.message.author.roles: if role in self.configurable_roles: await role.edit(mentionable=True, reason="Enabled mentioning of role") await ctx.send(f"Role mentioning for `{role}` has been enabled!") @role.command( name="disable", aliases=["d"] ) async def disable_(self, ctx, role: Role): """ Disables mention feature of role """ if(len(self.configurable_roles) == 0): self.populateRoleLists(ctx) if utils.get(ctx.guild.roles, name="Mods") in ctx.message.author.roles: if role in self.configurable_roles: await role.edit(mentionable=False, reason="Disabled mentioning of role") await ctx.send(f"Role mentioning for `{role}` has been disabled!") @role.command( name="list", aliases=["l"] ) async def list_(self, ctx): message = "All self-assignable roles:" if(len(self.self_assignable_roles) == 0): self.populateRoleLists(ctx) for role in self.self_assignable_roles: message += f"\n\t- `{role}`" message += "\n\nYou can add/remove these roles by typing `-role [add/remove] [role name]`" await ctx.send(message) @role.command( name="ping", aliases=["p"] ) async def ping_(self, ctx, action): if utils.get(ctx.guild.roles, name="Mods") in ctx.message.author.roles: await ctx.send("Deprecated command! Please use `-role [enable/disable] ping` instead") @command() async def trello(self, ctx): """Cassandra's Trello Link!""" message = "**Cassandra Trello board for bot progress:**\nhttps://trello.com/b/RPRZyqWx/cassandra-discord-bot" await ctx.send(message) @command() async def suggest(self, ctx, *, request: str=None): author = f"{ctx.author.name}#{ctx.author.discriminator}" if(len(sys.argv)>=2 and sys.argv[1] == "-test"): testinglogin = json.load(open('testingdata.json')) gh_client = Github(testinglogin["gh_username"], testinglogin["gh_pass"]) cass_repo = gh_client.get_repo("CassandraBot/CassGHIssueTest") else: gh_client = Github("CassandraBot", environ["CASS_GH_PASS"]) cass_repo = gh_client.get_repo("Avinch/Cassandra") label = [cass_repo.get_label("request")] issue_body = f"Requested by {author}" issue = cass_repo.create_issue(title=request, body=issue_body, labels=label) embed = Embed(title="Thank you for your suggestion!", colour=0x33cc82, type="rich") embed.add_field(name='Suggestion', value=request) embed.add_field(name='Link', value=issue.html_url) await ctx.send(embed=embed) @group(name='id') async def id_(self, ctx, *, argument: Union(Emoji, Role, TextChannel, VoiceChannel, Member, User)): await ctx.send(f"{argument.name}'s ID is {argument.id}") @command(aliases=['fw', 'fullwidth', 'aesthetic'], usage='<msg>') async def aesthetic(self, ctx, *, msg="aesthetic"): """aesthetic.""" await ctx.send("".join(map( lambda c: chr(ord(c) + FULLWIDTH_OFFSET) if (ord(c) >= 0x21 and ord(c) <= 0x7E) else c, msg)).replace(" ", chr(0x3000))) @command() async def clap(self, ctx, *, msg): msg = msg.replace(" ", "\U0001f44f") await ctx.send(msg) @command(aliases=["choose"]) async def decide(self, ctx, *choices: str): """Decides between things for you.""" await ctx.send(f"Obviously, the answer is {choice(choices)}.") @command(aliases=["element"]) async def atom(self, ctx, element): """Displays information for a given atom""" if not element.isalpha() or len(element) > 2: await ctx.send("Element symbols only have alphabetical letters and must be between 1-2 characters!") return try: html = await ctx.bot.fetch(ctx.session, f"http://www.chemicalelements.com/elements/{element.lower()}.html", timeout=15, return_type='text') except: await ctx.send(f"Could not find an element with the symbol \"{element.upper()}\"") return soup = BeautifulSoup(html, "html.parser") text = soup.get_text() element_name = text.split('Name: ')[1].split('\n')[0] element_symbol = text.split('Symbol: ')[1].split('\n')[0] atomic_number = text.split('Atomic Number: ')[1].split('\n')[0] atomic_mass = text.split('Atomic Mass: ')[1].split('\n')[0] neutrons = text.split('Number of Neutrons: ')[1].split('\n')[0] shells = text.split('Number of Energy Levels: ')[1].split('\n')[0] family = text.split('Classification: ')[1].split('\n')[0] color = text.split('Color: ')[1].split('\n')[0] uses = text.split('Uses: ')[1].split('\n')[0] discovery_year = text.split('Date of Discovery: ')[1].split('\n')[0] discoverer = text.split('Discoverer: ')[1].split('\n')[0] embed = Embed(title=element_name, colour=0x33cc82, type="rich") embed.add_field(name='Name', value=element_name) embed.add_field(name='Symbol', value=element_symbol) embed.add_field(name='Atomic Number', value=atomic_number) embed.add_field(name='Atomic Mass', value=atomic_mass) embed.add_field(name='Neutrons', value=neutrons) embed.add_field(name='Shells', value=shells) embed.add_field(name='Family', value=family) embed.add_field(name='Color', value=color) embed.add_field(name='Uses', value=uses) embed.add_field(name='Year of Discovery', value=discovery_year) embed.add_field(name='Discoverer', value=discoverer) await ctx.send(embed=embed) @command() async def roll(self, ctx, number: int=100): """Rolls random number (between 1 and user choice) Defaults to 100.""" if number > 1: await ctx.send(f"{ctx.author.mention} | :game_die: {randint(1, number)}") else: await ctx.send(f"{ctx.author.mention} Maybe higher than 1? :wink:") @command() async def flip(self, ctx, user: Member=None): """Flips a coin... or a user. Defaults to coin. """ if user is not None: msg = "" if user == ctx.bot.user: user = ctx.message.author msg = "Nice try. You think this is funny? How about *this* instead:\n\n" char = "abcdefghijklmnopqrstuvwxyz" tran = "ɐqɔpǝɟƃɥᴉɾʞlɯuodbɹsʇnʌʍxʎz" table = str.maketrans(char, tran) name = user.display_name.translate(table) char = char.upper() tran = "∀qƆpƎℲפHIſʞ˥WNOԀQᴚS┴∩ΛMX⅄Z" table = str.maketrans(char, tran) name = name.translate(table) await ctx.send(msg + "(╯°□°)╯︵ " + name[::-1]) else: await ctx.send("*flips a coin and... " + choice(["HEADS!*", "TAILS!*"])) @command(pass_context=True) async def rps(self, ctx, your_choice: RPSParser): """Play rock paper scissors""" player_choice = your_choice.choice tb_choice = choice((RPS.rock, RPS.paper, RPS.scissors)) cond = { (RPS.rock, RPS.paper): False, (RPS.rock, RPS.scissors): True, (RPS.paper, RPS.rock): True, (RPS.paper, RPS.scissors): False, (RPS.scissors, RPS.rock): False, (RPS.scissors, RPS.paper): True } if tb_choice == player_choice: outcome = None # Tie else: outcome = cond[(player_choice, tb_choice)] if outcome is True: await ctx.send(f"{tb_choice.value} You win {ctx.author.mention}!") elif outcome is False: await ctx.send(f"{tb_choice.value} You lose {ctx.author.mention}!") else: await ctx.send("{tb_choice.value} We're square {ctx.author.mention}!") @command(aliases=["8ball"]) async def ask(self, ctx, *, question=None): """Ask a question""" question = question.lower() if question.startswith("should"): responses = ("Yes", "No", "Definitely", "Sure", "Of course", "Maybe", "Probably" "Definitely not", "No way", "Please don't", "Go ahead!", "I mean, if you want to, sure", "Sure, but be careful", "That's probably not a good idea") elif question.startswith("where"): fast_food_chains = ("McDonald's", "Wendy's", "Burger King", "A&W", "KFC", "Taco Bell") responses = ("Just over there", "In your closet", "Probably hiding from you", f"At the nearest {choice(fast_food_chains)}", "Right behind you", "At the store", "Just a few blocks away", "Nowhere near here") elif question.startswith("when"): time_units = ("years", "months", "days", "hours", "minutes", "seconds") responses = ("In a few hours", "Sometime this month", "When pigs fly", "Not anythime soon, that's for sure", "By the end of the week", "Let's hope that never happens", "I am genuinely unsure", "Soon", "No idea, but be sure to tell me when it does", "In a dog's age", "I don't know, but hopefully it's in my lifetime", f"In {randint(1, 101)} {choice(time_units)}") elif question.startswith("who"): html = await ctx.bot.fetch(ctx.session, "https://www.randomlists.com/random-celebrities?a", timeout=15, return_type='text') soup = BeautifulSoup(html, "html.parser") tags = soup.find_all(class_="crux") celebrities = [] for tag in tags: celebrities.append(tag.text) responses = celebrities elif question.startswith(("what movie should", "what film should")): html = await ctx.bot.fetch(ctx.session, "https://www.randomlists.com/random-movies?a", timeout=15, return_type='text') soup = BeautifulSoup(html, "html.parser") tags = soup.find_all(class_="support") movies = [] for tag in tags: movies.append(tag.text) responses = movies elif question.startswith(("what game should", "what video game should", "what videogame should")): html = await ctx.bot.fetch(ctx.session, "https://www.randomlists.com/random-video-games?a", timeout=15, return_type='text') soup = BeautifulSoup(html, "html.parser") tags = soup.find_all(class_="support") games = [] for tag in tags: games.append(tag.text) responses = games else: responses = ("Yes", "No", "Definitely", "Sure", "Of course", "Maybe", "Probably", "Most likely", "Definitely not", "No way", "I hope not", "Better be", "I don't think so") if question is None: await ctx.send("You forgot to ask a question") else: await ctx.send(choice(responses)) @command() async def lmgtfy(self, ctx, *, search_terms: str): """Creates a lmgtfy link""" await ctx.send(f"https://lmgtfy.com/?q={search_terms}") @command(hidden=True) async def hug(self, ctx, user: Member=None, intensity: int=1): """Because everyone likes hugs Up to 10 intensity levels.""" name = user.display_name or ctx.author.display_name msg = None if intensity <= 0: msg = "(っ˘̩╭╮˘̩)っ" + name elif intensity <= 3: msg = "(っ´▽`)っ" + name elif intensity <= 6: msg = "╰(*´︶`*)╯" + name elif intensity <= 9: msg = "(つ≧▽≦)つ" + name elif intensity >= 10: msg = "(づ ̄ ³ ̄)づ*{}* ⊂(´・ω・`⊂)".format(name) await ctx.send(msg) @command(name='weather', aliases=['w', 'conditions']) async def get_weather(self, ctx, *, location: str = None): """Check the weather in a location""" if location is None: return await ctx.send('Please provide a location to get Weather Information for.') base = f'http://api.apixu.com/v1/current.json?key={self._weather_key}&q={location}' try: resp, data = await self.bot.fetch(base, return_type='json') except asyncio.TimeoutError: return await ctx.send('Our Weather API seems to be experiencing difficulties. Please try again later.') location = data['location'] locmsg = f'{location['name']}, {location['region']} {location['country'].upper()}' current = data['current'] colour = 0xFFA71A if current['is_day'] != 0 else 0x483078 embed = Embed(title=f'Weather for {locmsg}', description=f'*{current['condition']['text']}*', colour=colour) embed.set_thumbnail(url=f'http:{current['condition']['icon']}') embed.add_field(name='Temperature', value=f'{current['temp_c']}°C | {current['temp_f']}°F') embed.add_field(name='Feels Like', value=f'{current['feelslike_c']}°C | {current['feelslike_f']}°F') embed.add_field(name='Precipitation', value=f'{current['precip_mm']} mm') embed.add_field(name='Humidity', value=f'{current['humidity']}%') embed.add_field(name='Windspeed', value=f'{current['wind_kph']} kph | {current['wind_mph']} mph') embed.add_field(name='Wind Direction', value=current['wind_dir']) embed.timestamp = datetime.datetime.utcnow() await ctx.send(content=None, embed=embed) @command(name='colour', aliases=['color', 'col']) async def show_colour(self, ctx, colour: str): """Display a colour and popular scheme, from a HEX or RGB.""" if ctx.message.mentions: colour = ctx.message.mentions[0].colour else: colour = colour.strip('#').strip('0x').replace(' ', ',') base = 'http://www.thecolorapi.com/id?format=json&hex={}' basep = 'http://www.colourlovers.com/api/palettes?hex={}&format=json' if ',' in colour: rgb = tuple(map(int, colour.split(','))) for x in rgb: if x < 0 or x > 255: return await ctx.send('You have entered an invalid colour. Try entering a Hex-Code or R,G,B') colour = '%02x%02x%02x' % rgb url = base.format(colour) urlp = basep.format(colour) try: resp, data = await self.bot.fetch(url, return_type='json') except: return await ctx.send('There was a problem with the request. Please try again.') else: if resp.status > 300: return await ctx.send('There was a problem with the request. Please try again.') try: data['code'] except KeyError: pass else: return await ctx.send('You have entered an invalid colour. Try entering a Hex-Code or R,G,B') try: resp, datap = await self.bot.fetch(urlp, return_type='json') except: pass try: image = datap[0]['imageUrl'] colours = datap[0]['colors'] except: image = f'https://dummyimage.com/300/{data['hex']['clean']}.png' colours = None emcol = f"0x{data["hex"]["clean"]}" embed = Embed(title=f'Colour - {data['name']['value']}', colour=int(emcol, 0)) embed.set_thumbnail(url=f'https://dummyimage.com/150/{data['hex']['clean']}.png') embed.set_image(url=image) embed.add_field(name='HEX', value=f'{data['hex']['value']}') embed.add_field(name='RGB', value=f'{data['rgb']['value']}') embed.add_field(name='HSL', value=f'{data['hsl']['value']}') embed.add_field(name='HSV', value=f'{data['hsv']['value']}') embed.add_field(name='CMYK', value=f'{data['cmyk']['value']}') embed.add_field(name='XYZ', value=f'{data['XYZ']['value']}') if colours: embed.add_field(name='Scheme:', value=' | '.join(colours), inline=False) await ctx.send(content=None, embed=embed) @group(invoke_without_command=True) async def nasa(self, ctx): """Various Commands to access Photos and Information from NASA.""" pass @nasa.command(name='curiosity') async def curiosity_photos(self, ctx, camerainp: str = None, date: str = None): """Retrieve photos from Mars Rover: Curiosity. If date is None, the latest photos will be returned. A date is not guaranteed to have photos. If camera is None, a random camera will be chosen. A camera is not guaranteed to have photos. Cameras: [FHAZ : Front Hazard Avoidance Camera] [RHAZ : Rear Hazard Avoidance Camera] [MAST : Mast Camera] [CHEMCAM : Chemistry and Camera Complex] [MAHLI : Mars Hand Lens Imager] [MARDI : Mars Descent Imager] [NAVCAM : Navigation Camera] """ base = 'https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?sol={}&camera={}&api_key={}' basenc = 'https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?sol={}&api_key={}' cameras = ['fhaz', 'rhaz', 'mast', 'chemcam', 'mahli', 'mardt', 'mardi', 'navcam'] if camerainp is None: camera = 'none' else: camera = camerainp.lower() if camerainp and camerainp.lower() != 'none': if camera not in cameras: return await ctx.send('You have entered an invalid camera. Valid Cameras:\n' '```ini\n' '[FHAZ : Front Hazard Avoidance Camera]\n' '[RHAZ : Rear Hazard Avoidance Camera]\n' '[MAST : Mast Camera]\n' '[CHEMCAM : Chemistry and Camera Complex]\n' '[MAHLI : Mars Hand Lens Imager]\n' '[MARDI : Mars Descent Imager]\n' '[NAVCAM : Navigation Camera]\n' '```') if date is None or date == 'random': url = f'https://api.nasa.gov/mars-photos/api/v1/manifests/Curiosity/?max_sol&api_key={self._nasa_key}' try: res, sol = await self.bot.fetch(url=url, timeout=15, return_type='json') except: return await ctx.send('There was an error with your request. Please try again later.') if date == 'random': if camera and camera != 'none': base = base.format(randint(0, sol["photo_manifest"]["max_sol"]), camera, self._nasa_key) else: base = basenc.format(randint(0, sol["photo_manifest"]["max_sol"]), self._nasa_key) else: if camera and camera != 'none': base = base.format(sol["photo_manifest"]["max_sol"], camera, self._nasa_key) else: base = basenc.format(sol["photo_manifest"]["max_sol"], self._nasa_key) date = sol["photo_manifest"]["max_sol"] else: if camera and camera != 'none': base = f'https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?' \ f'earth_date={date}' \ f'&camera={camera}' \ f'&api_key={self._nasa_key}' else: base = f'https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?' \ f'earth_date={date}' \ f'&api_key={self._nasa_key}' try: res, data = await self.bot.fetch(base, timeout=15, return_type='json') except: return await ctx.send('There was an error with your request. Please try again later.') if len(data['photos']) <= 0: return await ctx.send(f'There was no photos available on date/sol' f' `{date}` with camera `{camera.upper() if camera else 'NONE'}`.') photos = data['photos'] main_img = choice(photos) if len(photos) > 4: photos = sample(photos, 4) embed = Embed(title='NASA Rover: Curiosity', description=f'Date/SOL: {date}', colour=0xB22E20) embed.set_image(url=main_img['img_src']) embed.add_field(name='Camera', value=camera.upper()) embed.add_field(name='See Also:', value='\n'.join(x['img_src'] for x in photos[:3]) if len(photos) > 3 else 'None', inline=False) embed.timestamp = datetime.datetime.utcnow() embed.set_footer(text='Generated on ') await ctx.send(content=None, embed=embed) @nasa.command(name='apod', aliases=['iotd']) async def nasa_apod(self, ctx): """Returns NASA's Astronomy Picture of the day.""" # todo Add the ability to select a date. url = f'https://api.nasa.gov/planetary/apod?api_key={self._nasa_key}' try: res, data = await self.bot.fetch(url=url, timeout=15, return_type='json') except: return await ctx.send('There was an error processing your request') embed = Embed(title='Astronomy Picture of the Day', description=f'**{data['title']}** | {data['date']}', colour=0x1d2951) embed.add_field(name='Explanation', value=data['explanation'] if len(data['explanation']) < 1024 else f"{data["explanation"][:1020]}...", inline=False) embed.add_field(name='HD Download', value=f'[Click here!]({data['hdurl']})') embed.set_image(url=data['url']) embed.timestamp = datetime.datetime.utcnow() embed.set_footer(text='Generated on ') await ctx.send(content=None, embed=embed) @nasa.command(name='epic', aliases=['EPIC']) async def nasa_epic(self, ctx): """Returns NASA's most recent EPIC image.""" base = f'https://api.nasa.gov/EPIC/api/natural?api_key={self._nasa_key}' img_base = 'https://epic.gsfc.nasa.gov/archive/natural/{}/png/{}.png' try: res, data = await self.bot.fetch(base, timeout=15, return_type='json') except: return await ctx.send('There was an error processing your request. Please try again.') img = choice(data) coords = img['centroid_coordinates'] embed = Embed(title='NASA EPIC', description=f'*{img['caption']}*', colour=0x1d2951) embed.set_image(url=img_base.format(img['date'].split(' ')[0].replace('-', '/'), img['image'])) embed.add_field(name='Centroid Coordinates', value=f'Lat: {coords['lat']} | Lon: {coords['lon']}') embed.add_field(name='Download', value=img_base.format(img['date'].split(' ')[0].replace('-', '/'), img['image'])) embed.timestamp = datetime.datetime.utcnow() embed.set_footer(text='Generated on ') await ctx.send(content=None, embed=embed) def setup(bot): bot.add_cog(Server(bot))
from discord import Role, TextChannel, VoiceChannel, Embed, Color, utils, Emoji, Member, User, File from discord.ext.commands import command, group from cassandra.bot import Union from random import choice, randint, sample from os import environ from bs4 import BeautifulSoup from enum import Enum import asyncio import datetime from github import Github import sys import json FULLWIDTH_OFFSET = 65248 class RPS(Enum): rock = "\N{MOYAI}" paper = "\N{PAGE FACING UP}" scissors = "\N{BLACK SCISSORS}" class RPSParser: def __init__(self, argument): argument = argument.lower() if argument == "rock": self.choice = RPS.rock elif argument == "paper": self.choice = RPS.paper elif argument == "scissors": self.choice = RPS.scissors else: return class Server: def __init__(self, bot): self.bot = bot self.self_assignable_roles = [] self.configurable_roles = [] try: self._weather_key = environ["API_WEATHER"] self._nasa_key = environ['API_NASA'] except KeyError: self._weather_key = bot.api_keys["WEATHER"] self._nasa_key = bot.api_keys["NASA"] def populateRoleLists(self, ctx): self.self_assignable_roles = { "ping": utils.get(ctx.guild.roles, name="ping"), "battlenet": utils.get(ctx.guild.roles, name="battlenet"), "gamenight": utils.get(ctx.guild.roles, name="gamenight"), "helpliner": utils.get(ctx.guild.roles, name="helpliner"), "politics": utils.get(ctx.guild.roles, name="Politics Opt-In"), "support": utils.get(ctx.guild.roles, name="Support Opt-In") , "archives": utils.get(ctx.guild.roles, name="Archivist") } self.configurable_roles = [ utils.get(ctx.guild.roles, name="ping"), utils.get(ctx.guild.roles, name="gamenight"), utils.get(ctx.guild.roles, name="helpliner") ] @group() async def role(self, ctx): """Add or remove an available role.""" if ctx.invoked_subcommand is None: await ctx.send(f"Invalid Action! Do `{ctx.prefix}help role` for more information. {ctx.author.mention}") @role.command( name="add", aliases=["+"] ) async def add_(self, ctx, role): """ Adds a role. If the argument given is not a valid role in the guild, it will safely ignore it. If the argument is a valid role in the guild and is not in the available roles list, it will flag it as invalid. """ if(len(self.self_assignable_roles) == 0): self.populateRoleLists(ctx) if role in self.self_assignable_roles: roleobj = self.self_assignable_roles[role] await ctx.author.add_roles(roleobj, reason="Used role command") await ctx.send(f"Added role `{roleobj}` to {ctx.author.mention}") else: await ctx.send( f""" `{role}` is not a valid role! Do `{ctx.prefix}help role add` for more information. {ctx.author.mention} """ ) @role.command( name="remove", aliases=["-"] ) async def remove_(self, ctx, role): """ Removes a role. If the argument given is not a valid role in the guild, it will safely ignore it. If the argument is a valid role in the guild and is not in the available roles list, it will flag it as invalid. """ if(len(self.self_assignable_roles) == 0): self.populateRoleLists(ctx) if role in self.self_assignable_roles: roleobj = self.self_assignable_roles[role] await ctx.author.remove_roles(roleobj, reason="Used role command") await ctx.send(f"Removed `{roleobj}` role from {ctx.author.mention}.") else: await ctx.send( f""" `{role}` is not a valid role! Do `{ctx.prefix}help role remove` for more information. {ctx.author.mention} """ ) @role.command( name="enable", aliases=["e"] ) async def enable_(self, ctx, role: Role): """ Enables mention feature of role """ if(len(self.configurable_roles) == 0): self.populateRoleLists(ctx) if utils.get(ctx.guild.roles, name="Mods") in ctx.message.author.roles: if role in self.configurable_roles: await role.edit(mentionable=True, reason="Enabled mentioning of role") await ctx.send(f"Role mentioning for `{role}` has been enabled!") @role.command( name="disable", aliases=["d"] ) async def disable_(self, ctx, role: Role): """ Disables mention feature of role """ if(len(self.configurable_roles) == 0): self.populateRoleLists(ctx) if utils.get(ctx.guild.roles, name="Mods") in ctx.message.author.roles: if role in self.configurable_roles: await role.edit(mentionable=False, reason="Disabled mentioning of role") await ctx.send(f"Role mentioning for `{role}` has been disabled!") @role.command( name="list", aliases=["l"] ) async def list_(self, ctx): message = "All self-assignable roles:" if(len(self.self_assignable_roles) == 0): self.populateRoleLists(ctx) for role in self.self_assignable_roles: message += f"\n\t- `{role}`" message += "\n\nYou can add/remove these roles by typing `-role [add/remove] [role name]`" await ctx.send(message) @role.command( name="ping", aliases=["p"] ) async def ping_(self, ctx, action): if utils.get(ctx.guild.roles, name="Mods") in ctx.message.author.roles: await ctx.send("Deprecated command! Please use `-role [enable/disable] ping` instead") @command() async def trello(self, ctx): """Cassandra's Trello Link!""" message = "**Cassandra Trello board for bot progress:**\nhttps://trello.com/b/RPRZyqWx/cassandra-discord-bot" await ctx.send(message) @command() async def suggest(self, ctx, *, request: str=None): author = f"{ctx.author.name}#{ctx.author.discriminator}" if(len(sys.argv)>=2 and sys.argv[1] == "-test"): testinglogin = json.load(open('testingdata.json')) gh_client = Github(testinglogin["gh_username"], testinglogin["gh_pass"]) cass_repo = gh_client.get_repo("CassandraBot/CassGHIssueTest") else: gh_client = Github("CassandraBot", environ["CASS_GH_PASS"]) cass_repo = gh_client.get_repo("Avinch/Cassandra") label = [cass_repo.get_label("request")] issue_body = f"Requested by {author}" issue = cass_repo.create_issue(title=request, body=issue_body, labels=label) embed = Embed(title="Thank you for your suggestion!", colour=0x33cc82, type="rich") embed.add_field(name='Suggestion', value=request) embed.add_field(name='Link', value=issue.html_url) await ctx.send(embed=embed) @group(name='id') async def id_(self, ctx, *, argument: Union(Emoji, Role, TextChannel, VoiceChannel, Member, User)): await ctx.send(f"{argument.name}'s ID is {argument.id}") @command(aliases=['fw', 'fullwidth', 'aesthetic'], usage='<msg>') async def aesthetic(self, ctx, *, msg="aesthetic"): """aesthetic.""" await ctx.send("".join(map( lambda c: chr(ord(c) + FULLWIDTH_OFFSET) if (ord(c) >= 0x21 and ord(c) <= 0x7E) else c, msg)).replace(" ", chr(0x3000))) @command() async def clap(self, ctx, *, msg): msg = msg.replace(" ", "\U0001f44f") await ctx.send(msg) @command(aliases=["choose"]) async def decide(self, ctx, *choices: str): """Decides between things for you.""" await ctx.send(f"Obviously, the answer is {choice(choices)}.") @command(aliases=["element"]) async def atom(self, ctx, element): """Displays information for a given atom""" if not element.isalpha() or len(element) > 2: await ctx.send("Element symbols only have alphabetical letters and must be between 1-2 characters!") return try: html = await ctx.bot.fetch(ctx.session, f"http://www.chemicalelements.com/elements/{element.lower()}.html", timeout=15, return_type='text') except: await ctx.send(f"Could not find an element with the symbol \"{element.upper()}\"") return soup = BeautifulSoup(html, "html.parser") text = soup.get_text() element_name = text.split('Name: ')[1].split('\n')[0] element_symbol = text.split('Symbol: ')[1].split('\n')[0] atomic_number = text.split('Atomic Number: ')[1].split('\n')[0] atomic_mass = text.split('Atomic Mass: ')[1].split('\n')[0] neutrons = text.split('Number of Neutrons: ')[1].split('\n')[0] shells = text.split('Number of Energy Levels: ')[1].split('\n')[0] family = text.split('Classification: ')[1].split('\n')[0] color = text.split('Color: ')[1].split('\n')[0] uses = text.split('Uses: ')[1].split('\n')[0] discovery_year = text.split('Date of Discovery: ')[1].split('\n')[0] discoverer = text.split('Discoverer: ')[1].split('\n')[0] embed = Embed(title=element_name, colour=0x33cc82, type="rich") embed.add_field(name='Name', value=element_name) embed.add_field(name='Symbol', value=element_symbol) embed.add_field(name='Atomic Number', value=atomic_number) embed.add_field(name='Atomic Mass', value=atomic_mass) embed.add_field(name='Neutrons', value=neutrons) embed.add_field(name='Shells', value=shells) embed.add_field(name='Family', value=family) embed.add_field(name='Color', value=color) embed.add_field(name='Uses', value=uses) embed.add_field(name='Year of Discovery', value=discovery_year) embed.add_field(name='Discoverer', value=discoverer) await ctx.send(embed=embed) @command() async def roll(self, ctx, number: int=100): """Rolls random number (between 1 and user choice) Defaults to 100.""" if number > 1: await ctx.send(f"{ctx.author.mention} | :game_die: {randint(1, number)}") else: await ctx.send(f"{ctx.author.mention} Maybe higher than 1? :wink:") @command() async def flip(self, ctx, user: Member=None): """Flips a coin... or a user. Defaults to coin. """ if user is not None: msg = "" if user == ctx.bot.user: user = ctx.message.author msg = "Nice try. You think this is funny? How about *this* instead:\n\n" char = "abcdefghijklmnopqrstuvwxyz" tran = "ɐqɔpǝɟƃɥᴉɾʞlɯuodbɹsʇnʌʍxʎz" table = str.maketrans(char, tran) name = user.display_name.translate(table) char = char.upper() tran = "∀qƆpƎℲפHIſʞ˥WNOԀQᴚS┴∩ΛMX⅄Z" table = str.maketrans(char, tran) name = name.translate(table) await ctx.send(msg + "(╯°□°)╯︵ " + name[::-1]) else: await ctx.send("*flips a coin and... " + choice(["HEADS!*", "TAILS!*"])) @command(pass_context=True) async def rps(self, ctx, your_choice: RPSParser): """Play rock paper scissors""" player_choice = your_choice.choice tb_choice = choice((RPS.rock, RPS.paper, RPS.scissors)) cond = { (RPS.rock, RPS.paper): False, (RPS.rock, RPS.scissors): True, (RPS.paper, RPS.rock): True, (RPS.paper, RPS.scissors): False, (RPS.scissors, RPS.rock): False, (RPS.scissors, RPS.paper): True } if tb_choice == player_choice: outcome = None # Tie else: outcome = cond[(player_choice, tb_choice)] if outcome is True: await ctx.send(f"{tb_choice.value} You win {ctx.author.mention}!") elif outcome is False: await ctx.send(f"{tb_choice.value} You lose {ctx.author.mention}!") else: await ctx.send("{tb_choice.value} We're square {ctx.author.mention}!") @command(aliases=["8ball"]) async def ask(self, ctx, *, question=None): """Ask a question""" question = question.lower() if question.startswith("should"): responses = ("Yes", "No", "Definitely", "Sure", "Of course", "Maybe", "Probably" "Definitely not", "No way", "Please don't", "Go ahead!", "I mean, if you want to, sure", "Sure, but be careful", "That's probably not a good idea") elif question.startswith("where"): fast_food_chains = ("McDonald's", "Wendy's", "Burger King", "A&W", "KFC", "Taco Bell") responses = ("Just over there", "In your closet", "Probably hiding from you", f"At the nearest {choice(fast_food_chains)}", "Right behind you", "At the store", "Just a few blocks away", "Nowhere near here") elif question.startswith("when"): time_units = ("years", "months", "days", "hours", "minutes", "seconds") responses = ("In a few hours", "Sometime this month", "When pigs fly", "Not anythime soon, that's for sure", "By the end of the week", "Let's hope that never happens", "I am genuinely unsure", "Soon", "No idea, but be sure to tell me when it does", "In a dog's age", "I don't know, but hopefully it's in my lifetime", f"In {randint(1, 101)} {choice(time_units)}") elif question.startswith("who"): html = await ctx.bot.fetch(ctx.session, "https://www.randomlists.com/random-celebrities?a", timeout=15, return_type='text') soup = BeautifulSoup(html, "html.parser") tags = soup.find_all(class_="crux") celebrities = [] for tag in tags: celebrities.append(tag.text) responses = celebrities elif question.startswith(("what movie should", "what film should")): html = await ctx.bot.fetch(ctx.session, "https://www.randomlists.com/random-movies?a", timeout=15, return_type='text') soup = BeautifulSoup(html, "html.parser") tags = soup.find_all(class_="support") movies = [] for tag in tags: movies.append(tag.text) responses = movies elif question.startswith(("what game should", "what video game should", "what videogame should")): html = await ctx.bot.fetch(ctx.session, "https://www.randomlists.com/random-video-games?a", timeout=15, return_type='text') soup = BeautifulSoup(html, "html.parser") tags = soup.find_all(class_="support") games = [] for tag in tags: games.append(tag.text) responses = games else: responses = ("Yes", "No", "Definitely", "Sure", "Of course", "Maybe", "Probably", "Most likely", "Definitely not", "No way", "I hope not", "Better be", "I don't think so") if question is None: await ctx.send("You forgot to ask a question") else: await ctx.send(choice(responses)) @command() async def lmgtfy(self, ctx, *, search_terms: str): """Creates a lmgtfy link""" await ctx.send(f"https://lmgtfy.com/?q={search_terms}") @command(hidden=True) async def hug(self, ctx, user: Member=None, intensity: int=1): """Because everyone likes hugs Up to 10 intensity levels.""" name = user.display_name or ctx.author.display_name msg = None if intensity <= 0: msg = "(っ˘̩╭╮˘̩)っ" + name elif intensity <= 3: msg = "(っ´▽`)っ" + name elif intensity <= 6: msg = "╰(*´︶`*)╯" + name elif intensity <= 9: msg = "(つ≧▽≦)つ" + name elif intensity >= 10: msg = "(づ ̄ ³ ̄)づ*{}* ⊂(´・ω・`⊂)".format(name) await ctx.send(msg) @command(name='weather', aliases=['w', 'conditions']) async def get_weather(self, ctx, *, location: str = None): """Check the weather in a location""" if location is None: return await ctx.send('Please provide a location to get Weather Information for.') base = f'http://api.apixu.com/v1/current.json?key={self._weather_key}&q={location}' try: resp, data = await self.bot.fetch(base, return_type='json') except asyncio.TimeoutError: return await ctx.send('Our Weather API seems to be experiencing difficulties. Please try again later.') location = data['location'] locmsg = f'{location["name"]}, {location["region"]} {location["country"].upper()}' current = data['current'] colour = 0xFFA71A if current['is_day'] != 0 else 0x483078 embed = Embed(title=f'Weather for {locmsg}', description=f'*{current["condition"]["text"]}*', colour=colour) embed.set_thumbnail(url=f'http:{current["condition"]["icon"]}') embed.add_field(name='Temperature', value=f'{current["temp_c"]}°C | {current["temp_f"]}°F') embed.add_field(name='Feels Like', value=f'{current["feelslike_c"]}°C | {current["feelslike_f"]}°F') embed.add_field(name='Precipitation', value=f'{current["precip_mm"]} mm') embed.add_field(name='Humidity', value=f'{current["humidity"]}%') embed.add_field(name='Windspeed', value=f'{current["wind_kph"]} kph | {current["wind_mph"]} mph') embed.add_field(name='Wind Direction', value=current['wind_dir']) embed.timestamp = datetime.datetime.utcnow() await ctx.send(content=None, embed=embed) @command(name='colour', aliases=['color', 'col']) async def show_colour(self, ctx, colour: str): """Display a colour and popular scheme, from a HEX or RGB.""" if ctx.message.mentions: colour = ctx.message.mentions[0].colour else: colour = colour.strip('#').strip('0x').replace(' ', ',') base = 'http://www.thecolorapi.com/id?format=json&hex={}' basep = 'http://www.colourlovers.com/api/palettes?hex={}&format=json' if ',' in colour: rgb = tuple(map(int, colour.split(','))) for x in rgb: if x < 0 or x > 255: return await ctx.send('You have entered an invalid colour. Try entering a Hex-Code or R,G,B') colour = '%02x%02x%02x' % rgb url = base.format(colour) urlp = basep.format(colour) try: resp, data = await self.bot.fetch(url, return_type='json') except: return await ctx.send('There was a problem with the request. Please try again.') else: if resp.status > 300: return await ctx.send('There was a problem with the request. Please try again.') try: data['code'] except KeyError: pass else: return await ctx.send('You have entered an invalid colour. Try entering a Hex-Code or R,G,B') try: resp, datap = await self.bot.fetch(urlp, return_type='json') except: pass try: image = datap[0]['imageUrl'] colours = datap[0]['colors'] except: image = f'https://dummyimage.com/300/{data["hex"]["clean"]}.png' colours = None emcol = f"0x{data['hex']['clean']}" embed = Embed(title=f'Colour - {data["name"]["value"]}', colour=int(emcol, 0)) embed.set_thumbnail(url=f'https://dummyimage.com/150/{data["hex"]["clean"]}.png') embed.set_image(url=image) embed.add_field(name='HEX', value=f'{data["hex"]["value"]}') embed.add_field(name='RGB', value=f'{data["rgb"]["value"]}') embed.add_field(name='HSL', value=f'{data["hsl"]["value"]}') embed.add_field(name='HSV', value=f'{data["hsv"]["value"]}') embed.add_field(name='CMYK', value=f'{data["cmyk"]["value"]}') embed.add_field(name='XYZ', value=f'{data["XYZ"]["value"]}') if colours: embed.add_field(name='Scheme:', value=' | '.join(colours), inline=False) await ctx.send(content=None, embed=embed) @group(invoke_without_command=True) async def nasa(self, ctx): """Various Commands to access Photos and Information from NASA.""" pass @nasa.command(name='curiosity') async def curiosity_photos(self, ctx, camerainp: str = None, date: str = None): """Retrieve photos from Mars Rover: Curiosity. If date is None, the latest photos will be returned. A date is not guaranteed to have photos. If camera is None, a random camera will be chosen. A camera is not guaranteed to have photos. Cameras: [FHAZ : Front Hazard Avoidance Camera] [RHAZ : Rear Hazard Avoidance Camera] [MAST : Mast Camera] [CHEMCAM : Chemistry and Camera Complex] [MAHLI : Mars Hand Lens Imager] [MARDI : Mars Descent Imager] [NAVCAM : Navigation Camera] """ base = 'https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?sol={}&camera={}&api_key={}' basenc = 'https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?sol={}&api_key={}' cameras = ['fhaz', 'rhaz', 'mast', 'chemcam', 'mahli', 'mardt', 'mardi', 'navcam'] if camerainp is None: camera = 'none' else: camera = camerainp.lower() if camerainp and camerainp.lower() != 'none': if camera not in cameras: return await ctx.send('You have entered an invalid camera. Valid Cameras:\n' '```ini\n' '[FHAZ : Front Hazard Avoidance Camera]\n' '[RHAZ : Rear Hazard Avoidance Camera]\n' '[MAST : Mast Camera]\n' '[CHEMCAM : Chemistry and Camera Complex]\n' '[MAHLI : Mars Hand Lens Imager]\n' '[MARDI : Mars Descent Imager]\n' '[NAVCAM : Navigation Camera]\n' '```') if date is None or date == 'random': url = f'https://api.nasa.gov/mars-photos/api/v1/manifests/Curiosity/?max_sol&api_key={self._nasa_key}' try: res, sol = await self.bot.fetch(url=url, timeout=15, return_type='json') except: return await ctx.send('There was an error with your request. Please try again later.') if date == 'random': if camera and camera != 'none': base = base.format(randint(0, sol["photo_manifest"]["max_sol"]), camera, self._nasa_key) else: base = basenc.format(randint(0, sol["photo_manifest"]["max_sol"]), self._nasa_key) else: if camera and camera != 'none': base = base.format(sol["photo_manifest"]["max_sol"], camera, self._nasa_key) else: base = basenc.format(sol["photo_manifest"]["max_sol"], self._nasa_key) date = sol["photo_manifest"]["max_sol"] else: if camera and camera != 'none': base = f'https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?' \ f'earth_date={date}' \ f'&camera={camera}' \ f'&api_key={self._nasa_key}' else: base = f'https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?' \ f'earth_date={date}' \ f'&api_key={self._nasa_key}' try: res, data = await self.bot.fetch(base, timeout=15, return_type='json') except: return await ctx.send('There was an error with your request. Please try again later.') if len(data['photos']) <= 0: return await ctx.send(f'There was no photos available on date/sol' f' `{date}` with camera `{camera.upper() if camera else "NONE"}`.') photos = data['photos'] main_img = choice(photos) if len(photos) > 4: photos = sample(photos, 4) embed = Embed(title='NASA Rover: Curiosity', description=f'Date/SOL: {date}', colour=0xB22E20) embed.set_image(url=main_img['img_src']) embed.add_field(name='Camera', value=camera.upper()) embed.add_field(name='See Also:', value='\n'.join(x['img_src'] for x in photos[:3]) if len(photos) > 3 else 'None', inline=False) embed.timestamp = datetime.datetime.utcnow() embed.set_footer(text='Generated on ') await ctx.send(content=None, embed=embed) @nasa.command(name='apod', aliases=['iotd']) async def nasa_apod(self, ctx): """Returns NASA's Astronomy Picture of the day.""" # todo Add the ability to select a date. url = f'https://api.nasa.gov/planetary/apod?api_key={self._nasa_key}' try: res, data = await self.bot.fetch(url=url, timeout=15, return_type='json') except: return await ctx.send('There was an error processing your request') embed = Embed(title='Astronomy Picture of the Day', description=f'**{data["title"]}** | {data["date"]}', colour=0x1d2951) embed.add_field(name='Explanation', value=data['explanation'] if len(data['explanation']) < 1024 else f"{data['explanation'][:1020]}...", inline=False) embed.add_field(name='HD Download', value=f'[Click here!]({data["hdurl"]})') embed.set_image(url=data['url']) embed.timestamp = datetime.datetime.utcnow() embed.set_footer(text='Generated on ') await ctx.send(content=None, embed=embed) @nasa.command(name='epic', aliases=['EPIC']) async def nasa_epic(self, ctx): """Returns NASA's most recent EPIC image.""" base = f'https://api.nasa.gov/EPIC/api/natural?api_key={self._nasa_key}' img_base = 'https://epic.gsfc.nasa.gov/archive/natural/{}/png/{}.png' try: res, data = await self.bot.fetch(base, timeout=15, return_type='json') except: return await ctx.send('There was an error processing your request. Please try again.') img = choice(data) coords = img['centroid_coordinates'] embed = Embed(title='NASA EPIC', description=f'*{img["caption"]}*', colour=0x1d2951) embed.set_image(url=img_base.format(img['date'].split(' ')[0].replace('-', '/'), img['image'])) embed.add_field(name='Centroid Coordinates', value=f'Lat: {coords["lat"]} | Lon: {coords["lon"]}') embed.add_field(name='Download', value=img_base.format(img['date'].split(' ')[0].replace('-', '/'), img['image'])) embed.timestamp = datetime.datetime.utcnow() embed.set_footer(text='Generated on ') await ctx.send(content=None, embed=embed) def setup(bot): bot.add_cog(Server(bot))
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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 # # http://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. """ Common utility functions shared by TVMC modules. """ import re import json import logging import os.path import argparse from urllib.parse import urlparse import tvm from tvm import relay from tvm import transform from tvm._ffi import registry # pylint: disable=invalid-name logger = logging.getLogger("TVMC") class TVMCException(Exception): """TVMC Exception""" def convert_graph_layout(mod, desired_layout): """Alter the layout of the input graph. Parameters ---------- mod : tvm.relay.Module The relay module to convert. desired_layout : str The layout to convert to. Returns ------- mod : tvm.relay.Module The converted module. """ # Assume for the time being that graphs only have # conv2d as heavily-sensitive operators. desired_layouts = { "nn.conv2d": [desired_layout, "default"], "nn.conv2d_transpose": [desired_layout, "default"], "qnn.conv2d": [desired_layout, "default"], } # Convert the layout of the graph where possible. seq = transform.Sequential( [ relay.transform.RemoveUnusedFunctions(), relay.transform.ConvertLayout(desired_layouts), ] ) with transform.PassContext(opt_level=3): try: return seq(mod) except Exception as err: raise TVMCException( "Error converting layout to {0}: {1}".format(desired_layout, str(err)) ) def validate_targets(parse_targets): """ Apply a series of validations in the targets provided via CLI. """ tvm_target_kinds = tvm.target.Target.list_kinds() targets = [t["name"] for t in parse_targets] if len(targets) > len(set(targets)): raise TVMCException("Duplicate target definitions are not allowed") if targets[-1] not in tvm_target_kinds: tvm_target_names = ", ".join(tvm_target_kinds) raise TVMCException( f"The last target needs to be a TVM target. Choices: {tvm_target_names}" ) tvm_targets = [t for t in targets if t in tvm_target_kinds] if len(tvm_targets) > 2: verbose_tvm_targets = ", ".join(tvm_targets) raise TVMCException( "Only two of the following targets can be used at a time. " f"Found: {verbose_tvm_targets}." ) def tokenize_target(target): """ Extract a list of tokens from a target specification text. It covers some corner-cases that are not covered by the built-in module 'shlex', such as the use of "+" as a punctuation character. Example ------- For the input `foo -op1=v1 -op2="v ,2", bar -op3=v-4` we should obtain: ["foo", "-op1=v1", "-op2="v ,2"", ",", "bar", "-op3=v-4"] Parameters ---------- target : str Target options sent via CLI arguments Returns ------- list of str a list of parsed tokens extracted from the target string """ # Regex to tokenize the "--target" value. It is split into five parts # to match with: # 1. target and option names e.g. llvm, -mattr=, -mcpu= # 2. option values, all together, without quotes e.g. -mattr=+foo,+opt # 3. option values, when single quotes are used e.g. -mattr='+foo, +opt' # 4. option values, when double quotes are used e.g. -mattr="+foo ,+opt" # 5. commas that separate different targets e.g. "my-target, llvm" target_pattern = ( r"(\-{0,2}[\w\-]+\=?" r"(?:[\w\+\-\.]+(?:,[\w\+\-\.])*" r"|[\'][\w\+\-,\s\.]+[\']" r"|[\"][\w\+\-,\s\.]+[\"])*" r"|,)" ) return re.findall(target_pattern, target) def parse_target(target): """ Parse a plain string of targets provided via a command-line argument. To send more than one codegen, a comma-separated list is expected. Options start with -<option_name>=<value>. We use python standard library 'shlex' to parse the argument in a POSIX compatible way, so that if options are defined as strings with spaces or commas, for example, this is considered and parsed accordingly. Example ------- For the input `--target="foo -op1=v1 -op2="v ,2", bar -op3=v-4"` we should obtain: [ { name: "foo", opts: {"op1":"v1", "op2":"v ,2"}, raw: 'foo -op1=v1 -op2="v ,2"' }, { name: "bar", opts: {"op3":"v-4"}, raw: 'bar -op3=v-4' } ] Parameters ---------- target : str Target options sent via CLI arguments Returns ------- codegens : list of dict This list preserves the order in which codegens were provided via command line. Each Dict contains three keys: 'name', containing the name of the codegen; 'opts' containing a key-value for all options passed via CLI; 'raw', containing the plain string for this codegen """ codegens = [] tvm_target_kinds = tvm.target.Target.list_kinds() parsed_tokens = tokenize_target(target) split_codegens = [] current_codegen = [] split_codegens.append(current_codegen) for token in parsed_tokens: # every time there is a comma separating # two codegen definitions, prepare for # a new codegen if token == ",": current_codegen = [] split_codegens.append(current_codegen) else: # collect a new token for the current # codegen being parsed current_codegen.append(token) # at this point we have a list of lists, # each item on the first list is a codegen definition # in the comma-separated values for codegen_def in split_codegens: # the first is expected to be the name name = codegen_def[0] is_tvm_target = name in tvm_target_kinds raw_target = " ".join(codegen_def) all_opts = codegen_def[1:] if len(codegen_def) > 1 else [] opts = {} for opt in all_opts: try: # deal with -- prefixed flags if opt.startswith("--"): opt_name = opt[2:] opt_value = True else: opt = opt[1:] if opt.startswith("-") else opt opt_name, opt_value = opt.split("=", maxsplit=1) # remove quotes from the value: quotes are only parsed if they match, # so it is safe to assume that if the string starts with quote, it ends # with quote. opt_value = opt_value[1:-1] if opt_value[0] in ('"', "'") else opt_value except ValueError: raise ValueError(f"Error when parsing '{opt}'") opts[opt_name] = opt_value codegens.append( {"name": name, "opts": opts, "raw": raw_target, "is_tvm_target": is_tvm_target} ) return codegens def is_inline_json(target): try: json.loads(target) return True except json.decoder.JSONDecodeError: return False def target_from_cli(target): """ Create a tvm.target.Target instance from a command line interface (CLI) string. Parameters ---------- target : str compilation target as plain string, inline JSON or path to a JSON file Returns ------- tvm.target.Target an instance of target device information extra_targets : list of dict This list preserves the order in which extra targets were provided via command line. Each Dict contains three keys: 'name', containing the name of the codegen; 'opts' containing a key-value for all options passed via CLI; 'raw', containing the plain string for this codegen """ extra_targets = [] if os.path.isfile(target): with open(target) as target_file: logger.debug("target input is a path: %s", target) target = "".join(target_file.readlines()) elif is_inline_json(target): logger.debug("target input is inline JSON: %s", target) else: logger.debug("target input is plain text: %s", target) try: parsed_targets = parse_target(target) except ValueError as ex: raise TVMCException(f"Error parsing target string '{target}'.\nThe error was: {ex}") validate_targets(parsed_targets) tvm_targets = [t for t in parsed_targets if t["is_tvm_target"]] # Validated target strings have 1 or 2 tvm targets, otherwise # `validate_targets` above will fail. if len(tvm_targets) == 1: target = tvm_targets[0]["raw"] target_host = None else: assert len(tvm_targets) == 2 target = tvm_targets[0]["raw"] target_host = tvm_targets[1]["raw"] extra_targets = [t for t in parsed_targets if not t["is_tvm_target"]] return tvm.target.Target(target, host=target_host), extra_targets def tracker_host_port_from_cli(rpc_tracker_str): """Extract hostname and (optional) port from strings like "1.2.3.4:9090" or "4.3.2.1". Used as a helper function to cover --rpc-tracker command line argument, in different subcommands. Parameters ---------- rpc_tracker_str : str hostname (or IP address) and port of the RPC tracker, in the format 'hostname[:port]'. Returns ------- rpc_hostname : str or None hostname or IP address, extracted from input. rpc_port : int or None port number extracted from input (9090 default). """ rpc_hostname = rpc_port = None if rpc_tracker_str: parsed_url = urlparse("//%s" % rpc_tracker_str) rpc_hostname = parsed_url.hostname rpc_port = parsed_url.port or 9090 logger.info("RPC tracker hostname: %s", rpc_hostname) logger.info("RPC tracker port: %s", rpc_port) return rpc_hostname, rpc_port def parse_pass_list_str(input_string): """Parse an input string for existing passes Parameters ---------- input_string: str Possibly comma-separated string with the names of passes Returns ------- list: a list of existing passes. """ _prefix = "relay._transform." pass_list = input_string.split(",") missing_list = [ p.strip() for p in pass_list if len(p.strip()) > 0 and tvm.get_global_func(_prefix + p.strip(), True) is None ] if len(missing_list) > 0: available_list = [ n[len(_prefix) :] for n in registry.list_global_func_names() if n.startswith(_prefix) ] raise argparse.ArgumentTypeError( "Following passes are not registered within tvm: {}. Available: {}.".format( ", ".join(missing_list), ", ".join(sorted(available_list)) ) ) return pass_list def parse_shape_string(inputs_string): """Parse an input shape dictionary string to a usable dictionary. Parameters ---------- inputs_string: str A string of the form "input_name:[dim1,dim2,...,dimn] input_name2:[dim1,dim2]" that indicates the desired shape for specific model inputs. Returns ------- shape_dict: dict A dictionary mapping input names to their shape for use in relay frontend converters. """ # Create a regex pattern that extracts each separate input mapping. pattern = r"\w+\:\s*\[\-?\d+(?:\,\s*\-?\d+)*\]" input_mappings = re.findall(pattern, inputs_string) if not input_mappings: raise argparse.ArgumentTypeError( "--input-shapes argument must be of the form " '"input_name:[dim1,dim2,...,dimn] input_name2:[dim1,dim2]"' ) shape_dict = {} for mapping in input_mappings: # Remove whitespace. mapping = mapping.replace(" ", "") # Split mapping into name and shape. name, shape_string = mapping.split(":") # Convert shape string into a list of integers or Anys if negative. shape = [int(x) if int(x) > 0 else relay.Any() for x in shape_string.strip("][").split(",")] # Add parsed mapping to shape dictionary. shape_dict[name] = shape return shape_dict def get_pass_config_value(name, value, config_type): """Get a PassContext configuration value, based on its config data type. Parameters ---------- name: str config identifier name. value: str value assigned to the config, provided via command line. config_type: str data type defined to the config, as string. Returns ------- parsed_value: bool, int or str a representation of the input value, converted to the type specified by config_type. """ if config_type == "IntImm": # "Bool" configurations in the PassContext are recognized as # IntImm, so deal with this case here mapping_values = { "false": False, "true": True, } if value.isdigit(): parsed_value = int(value) else: # if not an int, accept only values on the mapping table, case insensitive parsed_value = mapping_values.get(value.lower(), None) if parsed_value is None: raise TVMCException(f"Invalid value '{value}' for configuration '{name}'. ") if config_type == "runtime.String": parsed_value = value return parsed_value def parse_configs(input_configs): """Parse configuration values set via command line. Parameters ---------- input_configs: list of str list of configurations provided via command line. Returns ------- pass_context_configs: dict a dict containing key-value configs to be used in the PassContext. """ if not input_configs: return {} all_configs = tvm.ir.transform.PassContext.list_configs() supported_config_types = ("IntImm", "runtime.String") supported_configs = [ name for name in all_configs.keys() if all_configs[name]["type"] in supported_config_types ] pass_context_configs = {} for config in input_configs: if not config: raise TVMCException( f"Invalid format for configuration '{config}', use <config>=<value>" ) # Each config is expected to be provided as "name=value" try: name, value = config.split("=") name = name.strip() value = value.strip() except ValueError: raise TVMCException( f"Invalid format for configuration '{config}', use <config>=<value>" ) if name not in all_configs: raise TVMCException( f"Configuration '{name}' is not defined in TVM. " f"These are the existing configurations: {", ".join(all_configs)}" ) if name not in supported_configs: raise TVMCException( f"Configuration '{name}' uses a data type not supported by TVMC. " f"The following configurations are supported: {", ".join(supported_configs)}" ) parsed_value = get_pass_config_value(name, value, all_configs[name]["type"]) pass_context_configs[name] = parsed_value return pass_context_configs
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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 # # http://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. """ Common utility functions shared by TVMC modules. """ import re import json import logging import os.path import argparse from urllib.parse import urlparse import tvm from tvm import relay from tvm import transform from tvm._ffi import registry # pylint: disable=invalid-name logger = logging.getLogger("TVMC") class TVMCException(Exception): """TVMC Exception""" def convert_graph_layout(mod, desired_layout): """Alter the layout of the input graph. Parameters ---------- mod : tvm.relay.Module The relay module to convert. desired_layout : str The layout to convert to. Returns ------- mod : tvm.relay.Module The converted module. """ # Assume for the time being that graphs only have # conv2d as heavily-sensitive operators. desired_layouts = { "nn.conv2d": [desired_layout, "default"], "nn.conv2d_transpose": [desired_layout, "default"], "qnn.conv2d": [desired_layout, "default"], } # Convert the layout of the graph where possible. seq = transform.Sequential( [ relay.transform.RemoveUnusedFunctions(), relay.transform.ConvertLayout(desired_layouts), ] ) with transform.PassContext(opt_level=3): try: return seq(mod) except Exception as err: raise TVMCException( "Error converting layout to {0}: {1}".format(desired_layout, str(err)) ) def validate_targets(parse_targets): """ Apply a series of validations in the targets provided via CLI. """ tvm_target_kinds = tvm.target.Target.list_kinds() targets = [t["name"] for t in parse_targets] if len(targets) > len(set(targets)): raise TVMCException("Duplicate target definitions are not allowed") if targets[-1] not in tvm_target_kinds: tvm_target_names = ", ".join(tvm_target_kinds) raise TVMCException( f"The last target needs to be a TVM target. Choices: {tvm_target_names}" ) tvm_targets = [t for t in targets if t in tvm_target_kinds] if len(tvm_targets) > 2: verbose_tvm_targets = ", ".join(tvm_targets) raise TVMCException( "Only two of the following targets can be used at a time. " f"Found: {verbose_tvm_targets}." ) def tokenize_target(target): """ Extract a list of tokens from a target specification text. It covers some corner-cases that are not covered by the built-in module 'shlex', such as the use of "+" as a punctuation character. Example ------- For the input `foo -op1=v1 -op2="v ,2", bar -op3=v-4` we should obtain: ["foo", "-op1=v1", "-op2="v ,2"", ",", "bar", "-op3=v-4"] Parameters ---------- target : str Target options sent via CLI arguments Returns ------- list of str a list of parsed tokens extracted from the target string """ # Regex to tokenize the "--target" value. It is split into five parts # to match with: # 1. target and option names e.g. llvm, -mattr=, -mcpu= # 2. option values, all together, without quotes e.g. -mattr=+foo,+opt # 3. option values, when single quotes are used e.g. -mattr='+foo, +opt' # 4. option values, when double quotes are used e.g. -mattr="+foo ,+opt" # 5. commas that separate different targets e.g. "my-target, llvm" target_pattern = ( r"(\-{0,2}[\w\-]+\=?" r"(?:[\w\+\-\.]+(?:,[\w\+\-\.])*" r"|[\'][\w\+\-,\s\.]+[\']" r"|[\"][\w\+\-,\s\.]+[\"])*" r"|,)" ) return re.findall(target_pattern, target) def parse_target(target): """ Parse a plain string of targets provided via a command-line argument. To send more than one codegen, a comma-separated list is expected. Options start with -<option_name>=<value>. We use python standard library 'shlex' to parse the argument in a POSIX compatible way, so that if options are defined as strings with spaces or commas, for example, this is considered and parsed accordingly. Example ------- For the input `--target="foo -op1=v1 -op2="v ,2", bar -op3=v-4"` we should obtain: [ { name: "foo", opts: {"op1":"v1", "op2":"v ,2"}, raw: 'foo -op1=v1 -op2="v ,2"' }, { name: "bar", opts: {"op3":"v-4"}, raw: 'bar -op3=v-4' } ] Parameters ---------- target : str Target options sent via CLI arguments Returns ------- codegens : list of dict This list preserves the order in which codegens were provided via command line. Each Dict contains three keys: 'name', containing the name of the codegen; 'opts' containing a key-value for all options passed via CLI; 'raw', containing the plain string for this codegen """ codegens = [] tvm_target_kinds = tvm.target.Target.list_kinds() parsed_tokens = tokenize_target(target) split_codegens = [] current_codegen = [] split_codegens.append(current_codegen) for token in parsed_tokens: # every time there is a comma separating # two codegen definitions, prepare for # a new codegen if token == ",": current_codegen = [] split_codegens.append(current_codegen) else: # collect a new token for the current # codegen being parsed current_codegen.append(token) # at this point we have a list of lists, # each item on the first list is a codegen definition # in the comma-separated values for codegen_def in split_codegens: # the first is expected to be the name name = codegen_def[0] is_tvm_target = name in tvm_target_kinds raw_target = " ".join(codegen_def) all_opts = codegen_def[1:] if len(codegen_def) > 1 else [] opts = {} for opt in all_opts: try: # deal with -- prefixed flags if opt.startswith("--"): opt_name = opt[2:] opt_value = True else: opt = opt[1:] if opt.startswith("-") else opt opt_name, opt_value = opt.split("=", maxsplit=1) # remove quotes from the value: quotes are only parsed if they match, # so it is safe to assume that if the string starts with quote, it ends # with quote. opt_value = opt_value[1:-1] if opt_value[0] in ('"', "'") else opt_value except ValueError: raise ValueError(f"Error when parsing '{opt}'") opts[opt_name] = opt_value codegens.append( {"name": name, "opts": opts, "raw": raw_target, "is_tvm_target": is_tvm_target} ) return codegens def is_inline_json(target): try: json.loads(target) return True except json.decoder.JSONDecodeError: return False def target_from_cli(target): """ Create a tvm.target.Target instance from a command line interface (CLI) string. Parameters ---------- target : str compilation target as plain string, inline JSON or path to a JSON file Returns ------- tvm.target.Target an instance of target device information extra_targets : list of dict This list preserves the order in which extra targets were provided via command line. Each Dict contains three keys: 'name', containing the name of the codegen; 'opts' containing a key-value for all options passed via CLI; 'raw', containing the plain string for this codegen """ extra_targets = [] if os.path.isfile(target): with open(target) as target_file: logger.debug("target input is a path: %s", target) target = "".join(target_file.readlines()) elif is_inline_json(target): logger.debug("target input is inline JSON: %s", target) else: logger.debug("target input is plain text: %s", target) try: parsed_targets = parse_target(target) except ValueError as ex: raise TVMCException(f"Error parsing target string '{target}'.\nThe error was: {ex}") validate_targets(parsed_targets) tvm_targets = [t for t in parsed_targets if t["is_tvm_target"]] # Validated target strings have 1 or 2 tvm targets, otherwise # `validate_targets` above will fail. if len(tvm_targets) == 1: target = tvm_targets[0]["raw"] target_host = None else: assert len(tvm_targets) == 2 target = tvm_targets[0]["raw"] target_host = tvm_targets[1]["raw"] extra_targets = [t for t in parsed_targets if not t["is_tvm_target"]] return tvm.target.Target(target, host=target_host), extra_targets def tracker_host_port_from_cli(rpc_tracker_str): """Extract hostname and (optional) port from strings like "1.2.3.4:9090" or "4.3.2.1". Used as a helper function to cover --rpc-tracker command line argument, in different subcommands. Parameters ---------- rpc_tracker_str : str hostname (or IP address) and port of the RPC tracker, in the format 'hostname[:port]'. Returns ------- rpc_hostname : str or None hostname or IP address, extracted from input. rpc_port : int or None port number extracted from input (9090 default). """ rpc_hostname = rpc_port = None if rpc_tracker_str: parsed_url = urlparse("//%s" % rpc_tracker_str) rpc_hostname = parsed_url.hostname rpc_port = parsed_url.port or 9090 logger.info("RPC tracker hostname: %s", rpc_hostname) logger.info("RPC tracker port: %s", rpc_port) return rpc_hostname, rpc_port def parse_pass_list_str(input_string): """Parse an input string for existing passes Parameters ---------- input_string: str Possibly comma-separated string with the names of passes Returns ------- list: a list of existing passes. """ _prefix = "relay._transform." pass_list = input_string.split(",") missing_list = [ p.strip() for p in pass_list if len(p.strip()) > 0 and tvm.get_global_func(_prefix + p.strip(), True) is None ] if len(missing_list) > 0: available_list = [ n[len(_prefix) :] for n in registry.list_global_func_names() if n.startswith(_prefix) ] raise argparse.ArgumentTypeError( "Following passes are not registered within tvm: {}. Available: {}.".format( ", ".join(missing_list), ", ".join(sorted(available_list)) ) ) return pass_list def parse_shape_string(inputs_string): """Parse an input shape dictionary string to a usable dictionary. Parameters ---------- inputs_string: str A string of the form "input_name:[dim1,dim2,...,dimn] input_name2:[dim1,dim2]" that indicates the desired shape for specific model inputs. Returns ------- shape_dict: dict A dictionary mapping input names to their shape for use in relay frontend converters. """ # Create a regex pattern that extracts each separate input mapping. pattern = r"\w+\:\s*\[\-?\d+(?:\,\s*\-?\d+)*\]" input_mappings = re.findall(pattern, inputs_string) if not input_mappings: raise argparse.ArgumentTypeError( "--input-shapes argument must be of the form " '"input_name:[dim1,dim2,...,dimn] input_name2:[dim1,dim2]"' ) shape_dict = {} for mapping in input_mappings: # Remove whitespace. mapping = mapping.replace(" ", "") # Split mapping into name and shape. name, shape_string = mapping.split(":") # Convert shape string into a list of integers or Anys if negative. shape = [int(x) if int(x) > 0 else relay.Any() for x in shape_string.strip("][").split(",")] # Add parsed mapping to shape dictionary. shape_dict[name] = shape return shape_dict def get_pass_config_value(name, value, config_type): """Get a PassContext configuration value, based on its config data type. Parameters ---------- name: str config identifier name. value: str value assigned to the config, provided via command line. config_type: str data type defined to the config, as string. Returns ------- parsed_value: bool, int or str a representation of the input value, converted to the type specified by config_type. """ if config_type == "IntImm": # "Bool" configurations in the PassContext are recognized as # IntImm, so deal with this case here mapping_values = { "false": False, "true": True, } if value.isdigit(): parsed_value = int(value) else: # if not an int, accept only values on the mapping table, case insensitive parsed_value = mapping_values.get(value.lower(), None) if parsed_value is None: raise TVMCException(f"Invalid value '{value}' for configuration '{name}'. ") if config_type == "runtime.String": parsed_value = value return parsed_value def parse_configs(input_configs): """Parse configuration values set via command line. Parameters ---------- input_configs: list of str list of configurations provided via command line. Returns ------- pass_context_configs: dict a dict containing key-value configs to be used in the PassContext. """ if not input_configs: return {} all_configs = tvm.ir.transform.PassContext.list_configs() supported_config_types = ("IntImm", "runtime.String") supported_configs = [ name for name in all_configs.keys() if all_configs[name]["type"] in supported_config_types ] pass_context_configs = {} for config in input_configs: if not config: raise TVMCException( f"Invalid format for configuration '{config}', use <config>=<value>" ) # Each config is expected to be provided as "name=value" try: name, value = config.split("=") name = name.strip() value = value.strip() except ValueError: raise TVMCException( f"Invalid format for configuration '{config}', use <config>=<value>" ) if name not in all_configs: raise TVMCException( f"Configuration '{name}' is not defined in TVM. " f"These are the existing configurations: {', '.join(all_configs)}" ) if name not in supported_configs: raise TVMCException( f"Configuration '{name}' uses a data type not supported by TVMC. " f"The following configurations are supported: {', '.join(supported_configs)}" ) parsed_value = get_pass_config_value(name, value, all_configs[name]["type"]) pass_context_configs[name] = parsed_value return pass_context_configs
from functools import partial import os import sys import aiohttp import aiohttp_jinja2 from aiohttp import web from aiohttp_security import check_authorized import api.http from app import admin_app, api_app, app as main_app from config import config from models import Room, User from models.role import Role from utils import logger subpath = os.environ.get("PA_BASEPATH", "/") if subpath[-1] == "/": subpath = subpath[:-1] async def root(request, admin_api=False): template = "admin-index.html" if admin_api else "index.html" with open(f"./templates/{template}", "rb") as f: data = f.read() if not config.getboolean("General", "allow_signups"): data = data.replace( b'name="PA-signup" content="true"', b'name="PA-signup" content="false"' ) return web.Response(body=data, content_type="text/html") async def root_dev(request, admin_api=False): port = 8081 if admin_api else 8080 target_url = f"http://localhost:{port}{request.rel_url}" data = await request.read() async with aiohttp.ClientSession() as session: async with session.request( "get", target_url, headers=request.headers, data=data ) as response: raw = await response.read() if not config.getboolean("General", "allow_signups"): raw = raw.replace( b'name="PA-signup" content="true"', b'name="PA-signup" content="false"', ) return web.Response(body=raw, status=response.status, headers=response.headers) @aiohttp_jinja2.template("planarally.jinja2") async def show_room(request): user = await check_authorized(request) creator = User.by_name(request.match_info["username"]) try: room = Room.select().where( (Room.creator == creator) & (Room.name == request.match_info["roomname"]) )[0] except IndexError: logger.info( f"{user.name} attempted to load non existing room {request.match_info["username"]}/{request.match_info["roomname"]}" ) else: for pr in room.players: if pr.user == user: return {"dm": pr.role == Role.DM} return web.HTTPFound("/rooms") @aiohttp_jinja2.template("assets.jinja2") async def show_assets(request): await check_authorized(request) # MAIN ROUTES main_app.router.add_static(f"{subpath}/static", "static") main_app.router.add_get(f"{subpath}/api/auth", api.http.auth.is_authed) main_app.router.add_post(f"{subpath}/api/users/email", api.http.users.set_email) main_app.router.add_post(f"{subpath}/api/users/password", api.http.users.set_password) main_app.router.add_post(f"{subpath}/api/users/delete", api.http.users.delete_account) main_app.router.add_post(f"{subpath}/api/login", api.http.auth.login) main_app.router.add_post(f"{subpath}/api/register", api.http.auth.register) main_app.router.add_post(f"{subpath}/api/logout", api.http.auth.logout) main_app.router.add_get(f"{subpath}/api/rooms", api.http.rooms.get_list) main_app.router.add_post(f"{subpath}/api/rooms", api.http.rooms.create) main_app.router.add_patch( f"{subpath}/api/rooms/{{creator}}/{{roomname}}", api.http.rooms.patch ) main_app.router.add_delete( f"{subpath}/api/rooms/{{creator}}/{{roomname}}", api.http.rooms.delete ) main_app.router.add_get( f"{subpath}/api/rooms/{{creator}}/{{roomname}}/info", api.http.rooms.get_info ) main_app.router.add_patch( f"{subpath}/api/rooms/{{creator}}/{{roomname}}/info", api.http.rooms.set_info ) main_app.router.add_get( f"{subpath}/api/rooms/{{creator}}/{{roomname}}/export", api.http.rooms.export ) main_app.router.add_post(f"{subpath}/api/invite", api.http.claim_invite) main_app.router.add_get(f"{subpath}/api/version", api.http.version.get_version) main_app.router.add_get(f"{subpath}/api/changelog", api.http.version.get_changelog) main_app.router.add_get(f"{subpath}/api/notifications", api.http.notifications.collect) # ADMIN ROUTES api_app.router.add_post(f"{subpath}/notifications", api.http.notifications.create) api_app.router.add_get(f"{subpath}/notifications", api.http.notifications.collect) api_app.router.add_delete( f"{subpath}/notifications/{{uuid}}", api.http.notifications.delete ) api_app.router.add_get(f"{subpath}/users", api.http.admin.users.collect) api_app.router.add_post(f"{subpath}/users/reset", api.http.admin.users.reset) api_app.router.add_post(f"{subpath}/users/remove", api.http.admin.users.remove) api_app.router.add_get(f"{subpath}/campaigns", api.http.admin.campaigns.collect) admin_app.router.add_static(f"{subpath}/static", "static") admin_app.add_subapp("/api/", api_app) if "dev" in sys.argv: main_app.router.add_route("*", "/{tail:.*}", root_dev) admin_app.router.add_route("*", "/{tail:.*}", partial(root_dev, admin_api=True)) else: main_app.router.add_route("*", "/{tail:.*}", root) admin_app.router.add_route("*", "/{tail:.*}", partial(root, admin_api=True))
from functools import partial import os import sys import aiohttp import aiohttp_jinja2 from aiohttp import web from aiohttp_security import check_authorized import api.http from app import admin_app, api_app, app as main_app from config import config from models import Room, User from models.role import Role from utils import logger subpath = os.environ.get("PA_BASEPATH", "/") if subpath[-1] == "/": subpath = subpath[:-1] async def root(request, admin_api=False): template = "admin-index.html" if admin_api else "index.html" with open(f"./templates/{template}", "rb") as f: data = f.read() if not config.getboolean("General", "allow_signups"): data = data.replace( b'name="PA-signup" content="true"', b'name="PA-signup" content="false"' ) return web.Response(body=data, content_type="text/html") async def root_dev(request, admin_api=False): port = 8081 if admin_api else 8080 target_url = f"http://localhost:{port}{request.rel_url}" data = await request.read() async with aiohttp.ClientSession() as session: async with session.request( "get", target_url, headers=request.headers, data=data ) as response: raw = await response.read() if not config.getboolean("General", "allow_signups"): raw = raw.replace( b'name="PA-signup" content="true"', b'name="PA-signup" content="false"', ) return web.Response(body=raw, status=response.status, headers=response.headers) @aiohttp_jinja2.template("planarally.jinja2") async def show_room(request): user = await check_authorized(request) creator = User.by_name(request.match_info["username"]) try: room = Room.select().where( (Room.creator == creator) & (Room.name == request.match_info["roomname"]) )[0] except IndexError: logger.info( f"{user.name} attempted to load non existing room {request.match_info['username']}/{request.match_info['roomname']}" ) else: for pr in room.players: if pr.user == user: return {"dm": pr.role == Role.DM} return web.HTTPFound("/rooms") @aiohttp_jinja2.template("assets.jinja2") async def show_assets(request): await check_authorized(request) # MAIN ROUTES main_app.router.add_static(f"{subpath}/static", "static") main_app.router.add_get(f"{subpath}/api/auth", api.http.auth.is_authed) main_app.router.add_post(f"{subpath}/api/users/email", api.http.users.set_email) main_app.router.add_post(f"{subpath}/api/users/password", api.http.users.set_password) main_app.router.add_post(f"{subpath}/api/users/delete", api.http.users.delete_account) main_app.router.add_post(f"{subpath}/api/login", api.http.auth.login) main_app.router.add_post(f"{subpath}/api/register", api.http.auth.register) main_app.router.add_post(f"{subpath}/api/logout", api.http.auth.logout) main_app.router.add_get(f"{subpath}/api/rooms", api.http.rooms.get_list) main_app.router.add_post(f"{subpath}/api/rooms", api.http.rooms.create) main_app.router.add_patch( f"{subpath}/api/rooms/{{creator}}/{{roomname}}", api.http.rooms.patch ) main_app.router.add_delete( f"{subpath}/api/rooms/{{creator}}/{{roomname}}", api.http.rooms.delete ) main_app.router.add_get( f"{subpath}/api/rooms/{{creator}}/{{roomname}}/info", api.http.rooms.get_info ) main_app.router.add_patch( f"{subpath}/api/rooms/{{creator}}/{{roomname}}/info", api.http.rooms.set_info ) main_app.router.add_get( f"{subpath}/api/rooms/{{creator}}/{{roomname}}/export", api.http.rooms.export ) main_app.router.add_post(f"{subpath}/api/invite", api.http.claim_invite) main_app.router.add_get(f"{subpath}/api/version", api.http.version.get_version) main_app.router.add_get(f"{subpath}/api/changelog", api.http.version.get_changelog) main_app.router.add_get(f"{subpath}/api/notifications", api.http.notifications.collect) # ADMIN ROUTES api_app.router.add_post(f"{subpath}/notifications", api.http.notifications.create) api_app.router.add_get(f"{subpath}/notifications", api.http.notifications.collect) api_app.router.add_delete( f"{subpath}/notifications/{{uuid}}", api.http.notifications.delete ) api_app.router.add_get(f"{subpath}/users", api.http.admin.users.collect) api_app.router.add_post(f"{subpath}/users/reset", api.http.admin.users.reset) api_app.router.add_post(f"{subpath}/users/remove", api.http.admin.users.remove) api_app.router.add_get(f"{subpath}/campaigns", api.http.admin.campaigns.collect) admin_app.router.add_static(f"{subpath}/static", "static") admin_app.add_subapp("/api/", api_app) if "dev" in sys.argv: main_app.router.add_route("*", "/{tail:.*}", root_dev) admin_app.router.add_route("*", "/{tail:.*}", partial(root_dev, admin_api=True)) else: main_app.router.add_route("*", "/{tail:.*}", root) admin_app.router.add_route("*", "/{tail:.*}", partial(root, admin_api=True))
import numpy as np import cv2 import pandas as pd male = pd.read_csv("data/names/herrenavn.csv") female = pd.read_csv("data/names/kvinnenavn.csv") maleLength = len(male['Navn']) feMaleLength = len(female['Navn']) def draw_information(image_total, loc, faces_df, analyzis_object, useRandomNames=False): currentDf = male if analyzis_object['gender'] == "Man" else female currentLength = maleLength if analyzis_object['gender'] == "Man" else feMaleLength randomInt = np.random.randint(1, currentLength) if (useRandomNames): score = 0 identity = currentDf.iloc[randomInt]['Navn'] else: if(len(faces_df['identity']) > 0): identity = faces_df.iloc[0]['identity'].split("/")[2] score = faces_df.iloc[0]['VGG-Face_cosine'] else: #choose random name if none identities was found identity = currentDf.iloc[randomInt]['Navn'] x, y, width, _ = loc # x, y is the coordinate of the top left corner. draw_rectangle_with_opacity(image_total, loc) add_text( image_total, text=f"Name: {identity} ({score:.2f})", org=(x + width + 10, y + 25) ) add_text( image_total, text = f"Age: {analyzis_object["age"]}", org = (x + width + 10, y + 75), ) add_text( image_total, text = f"Sex: {analyzis_object["gender"]}", org = (x + width + 10, y + 125), ) add_text( image_total, text = f"Emotion: {analyzis_object["dominant_emotion"]}", org = (x + width + 10, y + 175), ) add_text( image_total, text = f"Race: {analyzis_object["dominant_race"]}", org = (x + width + 10, y + 225), ) def add_text(image_total, text, org): cv2.putText( img = image_total, text = text, org = org, fontFace = cv2.FONT_HERSHEY_SIMPLEX, fontScale = 0.75, thickness = 2, color = 0 ) def draw_rectangle_with_opacity(image_total, loc): x, y, width, height = loc # x, y is the coordinate of the top left corner. sub_img = image_total[y:y+height, x+width:x+width+300] white_rect = np.ones(sub_img.shape, dtype=np.uint8) * 255 res = cv2.addWeighted(sub_img, 0.5, white_rect, 0.5, 1.0) image_total[y:y+height, x+width:x+width+300] = res def draw_bounding_box(image_total, loc, keypoints): (x, y, width, height) = loc cv2.rectangle( img = image_total, pt1 = (x, y), pt2 = (x + width, y + height), color = (0, 155, 255), thickness = 2 ) cv2.circle( img = image_total, center = (keypoints['left_eye']), radius = 2, color = (0, 155, 255), thickness = 2 ) cv2.circle(image_total, (keypoints['right_eye']), 2, (0, 155, 255), 2) cv2.circle(image_total, (keypoints['nose']), 2, (0, 155, 255), 2) cv2.circle(image_total, (keypoints['mouth_left']), 2, (0, 155, 255), 2) cv2.circle(image_total, (keypoints['mouth_right']), 2, (0, 155, 255), 2)
import numpy as np import cv2 import pandas as pd male = pd.read_csv("data/names/herrenavn.csv") female = pd.read_csv("data/names/kvinnenavn.csv") maleLength = len(male['Navn']) feMaleLength = len(female['Navn']) def draw_information(image_total, loc, faces_df, analyzis_object, useRandomNames=False): currentDf = male if analyzis_object['gender'] == "Man" else female currentLength = maleLength if analyzis_object['gender'] == "Man" else feMaleLength randomInt = np.random.randint(1, currentLength) if (useRandomNames): score = 0 identity = currentDf.iloc[randomInt]['Navn'] else: if(len(faces_df['identity']) > 0): identity = faces_df.iloc[0]['identity'].split("/")[2] score = faces_df.iloc[0]['VGG-Face_cosine'] else: #choose random name if none identities was found identity = currentDf.iloc[randomInt]['Navn'] x, y, width, _ = loc # x, y is the coordinate of the top left corner. draw_rectangle_with_opacity(image_total, loc) add_text( image_total, text=f"Name: {identity} ({score:.2f})", org=(x + width + 10, y + 25) ) add_text( image_total, text = f"Age: {analyzis_object['age']}", org = (x + width + 10, y + 75), ) add_text( image_total, text = f"Sex: {analyzis_object['gender']}", org = (x + width + 10, y + 125), ) add_text( image_total, text = f"Emotion: {analyzis_object['dominant_emotion']}", org = (x + width + 10, y + 175), ) add_text( image_total, text = f"Race: {analyzis_object['dominant_race']}", org = (x + width + 10, y + 225), ) def add_text(image_total, text, org): cv2.putText( img = image_total, text = text, org = org, fontFace = cv2.FONT_HERSHEY_SIMPLEX, fontScale = 0.75, thickness = 2, color = 0 ) def draw_rectangle_with_opacity(image_total, loc): x, y, width, height = loc # x, y is the coordinate of the top left corner. sub_img = image_total[y:y+height, x+width:x+width+300] white_rect = np.ones(sub_img.shape, dtype=np.uint8) * 255 res = cv2.addWeighted(sub_img, 0.5, white_rect, 0.5, 1.0) image_total[y:y+height, x+width:x+width+300] = res def draw_bounding_box(image_total, loc, keypoints): (x, y, width, height) = loc cv2.rectangle( img = image_total, pt1 = (x, y), pt2 = (x + width, y + height), color = (0, 155, 255), thickness = 2 ) cv2.circle( img = image_total, center = (keypoints['left_eye']), radius = 2, color = (0, 155, 255), thickness = 2 ) cv2.circle(image_total, (keypoints['right_eye']), 2, (0, 155, 255), 2) cv2.circle(image_total, (keypoints['nose']), 2, (0, 155, 255), 2) cv2.circle(image_total, (keypoints['mouth_left']), 2, (0, 155, 255), 2) cv2.circle(image_total, (keypoints['mouth_right']), 2, (0, 155, 255), 2)
"""Work with Note and Notebook classes.""" from datetime import datetime as dtime import re class Note: """Represent a note in a notebook.""" _id = 1 def __init__(self, memo: str, tags=[]): """Create a note with a certain id. :param memo: a message of the note :param tags: tags of the note like [str, ..] """ self.memo = memo self.creation_date = dtime.today() self.tags = tags self.id = Note._id Note._id += 1 def match(self, search_filter: str) -> bool: """Match the note with the search filter. Tags in the filter should be separated by any non-alphanumeric character and not by _. :param search_filter: a string to match :return: True if match is successful, otherwise False """ return ((search_filter in self.memo) or any([re.search(f"(\\W|^){tag}(\\W|$)", search_filter) for tag in self.tags])) def __str__(self): final = f"[{self.creation_date}] - {self.id}: {self.memo}" if self.tags: final += f" (+{", +".join(self.tags)})" return final def __repr__(self): return (f"Note({self.id}, {self.memo}, " f"{self.tags}, {self.creation_date})") class Notebook: """Store notes and search for them.""" def __init__(self): """Initialize an empty list of notes.""" self.notes = [] def new_note(self, memo: str, tags=[]): """Initialize a new note in the notebook. :param memo: a note's content :param tags: a note's tags (optional) """ self.notes.append(Note(memo, tags)) def modify(self, note_id: int, delete: bool = False, n_memo: str = "", n_tags: list = []): """Modify a note with memo or tags by id, or delete it. :param note_id: id of the note to modify. :param n_memo: new memo :param n_tags: new tags :param delete: whether to delete this note :return: True if operation successful, else None """ for note in self.notes: if note.id == note_id: if delete: self.notes.remove(note) return True if n_memo: note.memo = n_memo if n_tags: note.tags = n_tags return True return None def search(self, search_filter: str) -> list: """Search a note by memo or tags. :param search_filter: a string to search the note by :return: a list of all found notes """ return [note for note in self.notes if note.match(search_filter)]
"""Work with Note and Notebook classes.""" from datetime import datetime as dtime import re class Note: """Represent a note in a notebook.""" _id = 1 def __init__(self, memo: str, tags=[]): """Create a note with a certain id. :param memo: a message of the note :param tags: tags of the note like [str, ..] """ self.memo = memo self.creation_date = dtime.today() self.tags = tags self.id = Note._id Note._id += 1 def match(self, search_filter: str) -> bool: """Match the note with the search filter. Tags in the filter should be separated by any non-alphanumeric character and not by _. :param search_filter: a string to match :return: True if match is successful, otherwise False """ return ((search_filter in self.memo) or any([re.search(f"(\\W|^){tag}(\\W|$)", search_filter) for tag in self.tags])) def __str__(self): final = f"[{self.creation_date}] - {self.id}: {self.memo}" if self.tags: final += f" (+{', +'.join(self.tags)})" return final def __repr__(self): return (f"Note({self.id}, {self.memo}, " f"{self.tags}, {self.creation_date})") class Notebook: """Store notes and search for them.""" def __init__(self): """Initialize an empty list of notes.""" self.notes = [] def new_note(self, memo: str, tags=[]): """Initialize a new note in the notebook. :param memo: a note's content :param tags: a note's tags (optional) """ self.notes.append(Note(memo, tags)) def modify(self, note_id: int, delete: bool = False, n_memo: str = "", n_tags: list = []): """Modify a note with memo or tags by id, or delete it. :param note_id: id of the note to modify. :param n_memo: new memo :param n_tags: new tags :param delete: whether to delete this note :return: True if operation successful, else None """ for note in self.notes: if note.id == note_id: if delete: self.notes.remove(note) return True if n_memo: note.memo = n_memo if n_tags: note.tags = n_tags return True return None def search(self, search_filter: str) -> list: """Search a note by memo or tags. :param search_filter: a string to search the note by :return: a list of all found notes """ return [note for note in self.notes if note.match(search_filter)]
""" Copyright (c) 2022 Huawei Technologies Co.,Ltd. openGauss is licensed under Mulan PSL v2. You can use this software according to the terms and conditions of the Mulan PSL v2. You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2 THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. See the Mulan PSL v2 for more details. """ """ Case Type : security-auditing Case Name : 统一审计策略:对table对象的insert行为的审计,过滤user Description : 1.系统管理员用户创建两个用户 2.系统管理员用户创建表,并赋予用户权限 3.系统管理员用户创建资源标签 4.系统管理员用户创建统一审计策略,过滤用户1 5.用户1登录数据库执行insert语句 6.用户2登录数据库执行insert语句 7.查看/var/log/postgresql日志中是否审计了用户1的insert操作 Expect : 1.用户创建成功 2.建表成功,赋予权限 3.创建成功 4.创建成功 5.执行成功 6.执行成功 7.日志中审计到了用户1的insert操作的操作,未审计到用户2的insert操作的操作 History : """ import os import re import unittest from time import sleep from yat.test import Node from yat.test import macro from testcase.utils.Common import Common from testcase.utils.CommonSH import CommonSH from testcase.utils.Logger import Logger from testcase.utils.Constant import Constant class Security(unittest.TestCase): def setUp(self): self.logger = Logger() self.logger.info( '---Opengauss_Function_Security_Auditing_Case0133 start---') self.userNode = Node(node='PrimaryDbUser') self.primary_root = Node(node='PrimaryRoot') self.sh_primy = CommonSH('PrimaryDbUser') self.common = Common() self.constant = Constant() self.user1 = 'u01_security_auditing_0133' self.user2 = 'u02_security_auditing_0133' self.table = 'table_security_auditing_0133' self.res_label = 'rl_security_auditing_0133' self.audit_policy = 'ap_security_auditing_0133' self.log_file = '/var/log/postgresql' self.config_path = '/etc' self.default_adss = self.common.show_param('audit_dml_state_select') self.default_adml = self.common.show_param('audit_dml_state') self.default_policy = self.common.show_param('enable_security_policy') self.default_facility = self.common.show_param('syslog_facility') def test_encrypted(self): text = '---step1.1:备份配置文件并配置日志归档;expect:成功---' self.logger.info(text) cp_cmd = f"cp {os.path.join(self.config_path, "rsyslog.conf")} " \ f"{os.path.join(self.config_path, "rsyslog_bak.conf")}" self.primary_root.sh(cp_cmd).result() mod_exe = f"echo 'local0.* {self.log_file}' >> " \ f"{os.path.join(self.config_path, "rsyslog.conf")};" \ f"service rsyslog restart" self.logger.info(mod_exe) mod_msg = self.primary_root.sh(mod_exe).result() self.logger.info(mod_msg) self.assertIn('restart rsyslog.service', mod_msg, '执行失败' + text) text = '---step1.2:设置enable_security_policy=on;expect:成功---' self.logger.info(text) result = self.sh_primy.execute_gsguc('reload', self.constant.GSGUC_SUCCESS_MSG, f'enable_security_policy=on') self.assertEqual(True, result, '执行失败' + text) text = '---step1.3:设置audit_dml_state_select=1;expect:成功---' self.logger.info(text) result = self.sh_primy.execute_gsguc('reload', self.constant.GSGUC_SUCCESS_MSG, f'audit_dml_state_select=1') self.assertEqual(True, result, '执行失败' + text) text = '---step1.4:设置audit_dml_state=1;expect:成功---' self.logger.info(text) result = self.sh_primy.execute_gsguc('reload', self.constant.GSGUC_SUCCESS_MSG, f'audit_dml_state=1') self.assertEqual(True, result, '执行失败' + text) text = '---step1.5:syslog_facility=local0;expect:成功---' self.logger.info(text) if self.default_facility != 'local0': result = self.sh_primy.execute_gsguc('reload', self.constant.GSGUC_SUCCESS_MSG, f'syslog_facility=local0') self.assertEqual(True, result, '执行失败' + text) text = '---step1.6:系统管理员用户创建两个用户;expect:成功---' self.logger.info(text) sql_cmd1 = f'drop user if exists {self.user1} cascade;' \ f'create user {self.user1} password ' \ f'\'{macro.COMMON_PASSWD}\';' \ f'drop user if exists {self.user2} cascade;' \ f'create user {self.user2} ' \ f'password \'{macro.COMMON_PASSWD}\';' msg1 = self.sh_primy.execut_db_sql(sql_cmd1) self.logger.info(msg1) self.assertIn('CREATE ROLE', msg1, '执行失败' + text) text = '---step2:系统管理员用户创建表,并赋予用户权限;expect:成功---' self.logger.info(text) sql_cmd2 = f'drop table if exists {self.table} cascade;' \ f'create table {self.table}(id int,name varchar(30));' \ f'insert into {self.table} values(6,\'{self.user1}\');' \ f'grant all privileges on {self.table} to {self.user1};' \ f'grant all privileges on {self.table} to {self.user2};' msg2 = self.sh_primy.execut_db_sql(sql_cmd2) self.logger.info(msg2) self.assertTrue(msg2.count('GRANT') == 2, '执行失败' + text) text = '---step3:系统管理员用户创建资源标签;expect:成功---' self.logger.info(text) sql_cmd3 = f'drop resource label if exists {self.res_label};' \ f'create resource label {self.res_label} add table({self.table});' msg3 = self.sh_primy.execut_db_sql(sql_cmd3) self.logger.info(msg3) self.assertIn('CREATE RESOURCE LABEL', msg3, '执行失败' + text) text = '---step4:系统管理员用户创建统一审计策略,过滤用户1;expect:成功---' self.logger.info(text) sql_cmd4 = f'drop audit policy if exists {self.audit_policy};' \ f'create audit policy {self.audit_policy} access insert' \ f' on label({self.res_label}) filter on roles({self.user1});' msg4 = self.sh_primy.execut_db_sql(sql_cmd4) self.logger.info(msg4) self.assertIn('CREATE AUDIT POLICY', msg4, '执行失败' + text) text = '---step5:用户1登录数据库执行insert语句;expect:成功---' self.logger.info(text) sql_cmd5 = f'insert into {self.table} values(2,\'lily\');' excute_cmd5 = f'source {macro.DB_ENV_PATH};' \ f'gsql -d {self.userNode.db_name} -p {self.userNode.db_port} ' \ f'-U {self.user1} -W {macro.COMMON_PASSWD} -c "{sql_cmd5}"' self.logger.info(excute_cmd5) msg5 = self.userNode.sh(excute_cmd5).result() self.logger.info(msg5) self.assertIn(self.constant.INSERT_SUCCESS_MSG, msg5, '执行失败' + text) text = '---step6:用户2登录数据库执行insert语句;expect:成功---' self.logger.info(text) sql_cmd6 = f'insert into {self.table} values(3,\'bob\');' excute_cmd6 = f'source {macro.DB_ENV_PATH};' \ f'gsql -d {self.userNode.db_name} -p {self.userNode.db_port} ' \ f'-U {self.user2} -W {macro.COMMON_PASSWD} -c "{sql_cmd6}"' self.logger.info(excute_cmd6) msg6 = self.userNode.sh(excute_cmd6).result() self.logger.info(msg6) self.assertIn(self.constant.INSERT_SUCCESS_MSG, msg6, '执行失败' + text) text = '--step7:查看postgresql日志中是否审计了用户1操作;expect:成功--' self.logger.info(text) sleep(2) exe_cmd7 = f'cat {self.log_file}' msg7 = self.primary_root.sh(exe_cmd7).result() self.logger.info(msg7) assert1 = re.search( f"user name.*{self.user1}.*access type.*[INSERT].*[OK]", msg7, re.S) self.assertTrue(assert1, '执行失败:' + text) self.assertNotIn(self.user2, msg7, '执行失败:' + text) def tearDown(self): text1 = '--step1:恢复配置文件信息;expect:成功--' self.logger.info(text1) recv_cmd = f"mv {os.path.join(self.config_path, "rsyslog_bak.conf")}" \ f" {os.path.join(self.config_path, "rsyslog.conf")};" \ f"rm -rf {self.log_file};" \ f"service rsyslog restart" self.logger.info(recv_cmd) result1 = self.primary_root.sh(recv_cmd).result() text2 = '--step2:恢复参数默认值;expect:成功--' self.logger.info(text2) result2 = self.sh_primy.execute_gsguc('reload', self.constant.GSGUC_SUCCESS_MSG, f'enable_security_policy={self.default_policy}') result3 = self.sh_primy.execute_gsguc('reload', self.constant.GSGUC_SUCCESS_MSG, f'audit_dml_state_select={self.default_adss}') result4 = self.sh_primy.execute_gsguc('reload', self.constant.GSGUC_SUCCESS_MSG, f'syslog_facility={self.default_facility}') text3 = '--step3:清理用户及表;expect:成功--' self.logger.info(text3) clear_cmd = f'drop audit policy if exists {self.audit_policy};' \ f'drop resource label if exists {self.res_label};' \ f'drop table if exists {self.table} cascade;' \ f'drop user if exists {self.user1} cascade;' \ f'drop user if exists {self.user2} cascade;' clear_msg = self.sh_primy.execut_db_sql(clear_cmd) self.logger.info(clear_msg) self.assertIn('restart rsyslog.service', result1, '执行失败' + text1) self.assertEqual(True, result2, '执行失败' + text2) self.assertEqual(True, result3, '执行失败' + text2) self.assertEqual(True, result4, '执行失败' + text2) self.assertIn(self.constant.DROP_ROLE_SUCCESS_MSG, clear_msg, text3) self.assertIn(self.constant.DROP_TABLE_SUCCESS, clear_msg, text3) self.logger.info( '----Opengauss_Function_Security_Auditing_Case0133 finish----')
""" Copyright (c) 2022 Huawei Technologies Co.,Ltd. openGauss is licensed under Mulan PSL v2. You can use this software according to the terms and conditions of the Mulan PSL v2. You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2 THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. See the Mulan PSL v2 for more details. """ """ Case Type : security-auditing Case Name : 统一审计策略:对table对象的insert行为的审计,过滤user Description : 1.系统管理员用户创建两个用户 2.系统管理员用户创建表,并赋予用户权限 3.系统管理员用户创建资源标签 4.系统管理员用户创建统一审计策略,过滤用户1 5.用户1登录数据库执行insert语句 6.用户2登录数据库执行insert语句 7.查看/var/log/postgresql日志中是否审计了用户1的insert操作 Expect : 1.用户创建成功 2.建表成功,赋予权限 3.创建成功 4.创建成功 5.执行成功 6.执行成功 7.日志中审计到了用户1的insert操作的操作,未审计到用户2的insert操作的操作 History : """ import os import re import unittest from time import sleep from yat.test import Node from yat.test import macro from testcase.utils.Common import Common from testcase.utils.CommonSH import CommonSH from testcase.utils.Logger import Logger from testcase.utils.Constant import Constant class Security(unittest.TestCase): def setUp(self): self.logger = Logger() self.logger.info( '---Opengauss_Function_Security_Auditing_Case0133 start---') self.userNode = Node(node='PrimaryDbUser') self.primary_root = Node(node='PrimaryRoot') self.sh_primy = CommonSH('PrimaryDbUser') self.common = Common() self.constant = Constant() self.user1 = 'u01_security_auditing_0133' self.user2 = 'u02_security_auditing_0133' self.table = 'table_security_auditing_0133' self.res_label = 'rl_security_auditing_0133' self.audit_policy = 'ap_security_auditing_0133' self.log_file = '/var/log/postgresql' self.config_path = '/etc' self.default_adss = self.common.show_param('audit_dml_state_select') self.default_adml = self.common.show_param('audit_dml_state') self.default_policy = self.common.show_param('enable_security_policy') self.default_facility = self.common.show_param('syslog_facility') def test_encrypted(self): text = '---step1.1:备份配置文件并配置日志归档;expect:成功---' self.logger.info(text) cp_cmd = f"cp {os.path.join(self.config_path, 'rsyslog.conf')} " \ f"{os.path.join(self.config_path, 'rsyslog_bak.conf')}" self.primary_root.sh(cp_cmd).result() mod_exe = f"echo 'local0.* {self.log_file}' >> " \ f"{os.path.join(self.config_path, 'rsyslog.conf')};" \ f"service rsyslog restart" self.logger.info(mod_exe) mod_msg = self.primary_root.sh(mod_exe).result() self.logger.info(mod_msg) self.assertIn('restart rsyslog.service', mod_msg, '执行失败' + text) text = '---step1.2:设置enable_security_policy=on;expect:成功---' self.logger.info(text) result = self.sh_primy.execute_gsguc('reload', self.constant.GSGUC_SUCCESS_MSG, f'enable_security_policy=on') self.assertEqual(True, result, '执行失败' + text) text = '---step1.3:设置audit_dml_state_select=1;expect:成功---' self.logger.info(text) result = self.sh_primy.execute_gsguc('reload', self.constant.GSGUC_SUCCESS_MSG, f'audit_dml_state_select=1') self.assertEqual(True, result, '执行失败' + text) text = '---step1.4:设置audit_dml_state=1;expect:成功---' self.logger.info(text) result = self.sh_primy.execute_gsguc('reload', self.constant.GSGUC_SUCCESS_MSG, f'audit_dml_state=1') self.assertEqual(True, result, '执行失败' + text) text = '---step1.5:syslog_facility=local0;expect:成功---' self.logger.info(text) if self.default_facility != 'local0': result = self.sh_primy.execute_gsguc('reload', self.constant.GSGUC_SUCCESS_MSG, f'syslog_facility=local0') self.assertEqual(True, result, '执行失败' + text) text = '---step1.6:系统管理员用户创建两个用户;expect:成功---' self.logger.info(text) sql_cmd1 = f'drop user if exists {self.user1} cascade;' \ f'create user {self.user1} password ' \ f'\'{macro.COMMON_PASSWD}\';' \ f'drop user if exists {self.user2} cascade;' \ f'create user {self.user2} ' \ f'password \'{macro.COMMON_PASSWD}\';' msg1 = self.sh_primy.execut_db_sql(sql_cmd1) self.logger.info(msg1) self.assertIn('CREATE ROLE', msg1, '执行失败' + text) text = '---step2:系统管理员用户创建表,并赋予用户权限;expect:成功---' self.logger.info(text) sql_cmd2 = f'drop table if exists {self.table} cascade;' \ f'create table {self.table}(id int,name varchar(30));' \ f'insert into {self.table} values(6,\'{self.user1}\');' \ f'grant all privileges on {self.table} to {self.user1};' \ f'grant all privileges on {self.table} to {self.user2};' msg2 = self.sh_primy.execut_db_sql(sql_cmd2) self.logger.info(msg2) self.assertTrue(msg2.count('GRANT') == 2, '执行失败' + text) text = '---step3:系统管理员用户创建资源标签;expect:成功---' self.logger.info(text) sql_cmd3 = f'drop resource label if exists {self.res_label};' \ f'create resource label {self.res_label} add table({self.table});' msg3 = self.sh_primy.execut_db_sql(sql_cmd3) self.logger.info(msg3) self.assertIn('CREATE RESOURCE LABEL', msg3, '执行失败' + text) text = '---step4:系统管理员用户创建统一审计策略,过滤用户1;expect:成功---' self.logger.info(text) sql_cmd4 = f'drop audit policy if exists {self.audit_policy};' \ f'create audit policy {self.audit_policy} access insert' \ f' on label({self.res_label}) filter on roles({self.user1});' msg4 = self.sh_primy.execut_db_sql(sql_cmd4) self.logger.info(msg4) self.assertIn('CREATE AUDIT POLICY', msg4, '执行失败' + text) text = '---step5:用户1登录数据库执行insert语句;expect:成功---' self.logger.info(text) sql_cmd5 = f'insert into {self.table} values(2,\'lily\');' excute_cmd5 = f'source {macro.DB_ENV_PATH};' \ f'gsql -d {self.userNode.db_name} -p {self.userNode.db_port} ' \ f'-U {self.user1} -W {macro.COMMON_PASSWD} -c "{sql_cmd5}"' self.logger.info(excute_cmd5) msg5 = self.userNode.sh(excute_cmd5).result() self.logger.info(msg5) self.assertIn(self.constant.INSERT_SUCCESS_MSG, msg5, '执行失败' + text) text = '---step6:用户2登录数据库执行insert语句;expect:成功---' self.logger.info(text) sql_cmd6 = f'insert into {self.table} values(3,\'bob\');' excute_cmd6 = f'source {macro.DB_ENV_PATH};' \ f'gsql -d {self.userNode.db_name} -p {self.userNode.db_port} ' \ f'-U {self.user2} -W {macro.COMMON_PASSWD} -c "{sql_cmd6}"' self.logger.info(excute_cmd6) msg6 = self.userNode.sh(excute_cmd6).result() self.logger.info(msg6) self.assertIn(self.constant.INSERT_SUCCESS_MSG, msg6, '执行失败' + text) text = '--step7:查看postgresql日志中是否审计了用户1操作;expect:成功--' self.logger.info(text) sleep(2) exe_cmd7 = f'cat {self.log_file}' msg7 = self.primary_root.sh(exe_cmd7).result() self.logger.info(msg7) assert1 = re.search( f"user name.*{self.user1}.*access type.*[INSERT].*[OK]", msg7, re.S) self.assertTrue(assert1, '执行失败:' + text) self.assertNotIn(self.user2, msg7, '执行失败:' + text) def tearDown(self): text1 = '--step1:恢复配置文件信息;expect:成功--' self.logger.info(text1) recv_cmd = f"mv {os.path.join(self.config_path, 'rsyslog_bak.conf')}" \ f" {os.path.join(self.config_path, 'rsyslog.conf')};" \ f"rm -rf {self.log_file};" \ f"service rsyslog restart" self.logger.info(recv_cmd) result1 = self.primary_root.sh(recv_cmd).result() text2 = '--step2:恢复参数默认值;expect:成功--' self.logger.info(text2) result2 = self.sh_primy.execute_gsguc('reload', self.constant.GSGUC_SUCCESS_MSG, f'enable_security_policy={self.default_policy}') result3 = self.sh_primy.execute_gsguc('reload', self.constant.GSGUC_SUCCESS_MSG, f'audit_dml_state_select={self.default_adss}') result4 = self.sh_primy.execute_gsguc('reload', self.constant.GSGUC_SUCCESS_MSG, f'syslog_facility={self.default_facility}') text3 = '--step3:清理用户及表;expect:成功--' self.logger.info(text3) clear_cmd = f'drop audit policy if exists {self.audit_policy};' \ f'drop resource label if exists {self.res_label};' \ f'drop table if exists {self.table} cascade;' \ f'drop user if exists {self.user1} cascade;' \ f'drop user if exists {self.user2} cascade;' clear_msg = self.sh_primy.execut_db_sql(clear_cmd) self.logger.info(clear_msg) self.assertIn('restart rsyslog.service', result1, '执行失败' + text1) self.assertEqual(True, result2, '执行失败' + text2) self.assertEqual(True, result3, '执行失败' + text2) self.assertEqual(True, result4, '执行失败' + text2) self.assertIn(self.constant.DROP_ROLE_SUCCESS_MSG, clear_msg, text3) self.assertIn(self.constant.DROP_TABLE_SUCCESS, clear_msg, text3) self.logger.info( '----Opengauss_Function_Security_Auditing_Case0133 finish----')
import sys import pathlib import os from sklearn.model_selection import train_test_split from .datasets import Dataset from ..log import logger __all__ = [ 'available_transformers' ] _MODULE = sys.modules[__name__] _MODULE_DIR = pathlib.Path(os.path.dirname(os.path.abspath(__file__))) def available_transformers(keys_only=True): """Valid transformation functions This function simply returns a dict of known tranformer algorithms strings and their corresponding function call It exists to allow for a description of the mapping for each of the valid strings as a docstring The valid algorithm names, and the function they map to, are: ============ ==================================== string Transformer Function ============ ==================================== train_test_split train_test_split_xform pivot pivot index_to_date_time index_to_date_time ============ ==================================== Parameters ---------- keys_only: boolean If True, return only keys. Otherwise, return a dictionary mapping keys to algorithms """ _TRANSFORMERS = { "index_to_date_time": index_to_date_time, "pivot": pivot, "train_test_split": split_dataset_test_train, } if keys_only: return list(_TRANSFORMERS.keys()) return _TRANSFORMERS def split_dataset_test_train(dset, dump_path=None, dump_metadata=True, force=True, create_dirs=True, **split_opts): """Transformer that performs a train/test split. This transformer passes `dset` intact, but creates and dumps two new datasets as a side effect: {dset.name}_test and {dset.name}_train Parameters ---------- dump_metadata: boolean If True, also dump a standalone copy of the metadata. Useful for checking metadata without reading in the (potentially large) dataset itself dump_path: path. (default: `processed_data_path`) Directory where data will be dumped. force: boolean If False, raise an exception if any dunp files already exists If True, overwrite any existing files create_dirs: boolean If True, `dump_path` will be created (if necessary) **split_opts: Remaining options will be passed to `train_test_split` """ new_ds = {} for kind in ['train', 'test']: dset_name = f"{dset.name}_{kind}" dset_meta = {**dset.metadata, 'split':kind, 'split_opts':split_opts} new_ds[kind] = Dataset(dataset_name=dset_name, metadata=dset_meta) X_train, X_test, y_train, y_test = train_test_split(dset.data, dset.target, **split_opts) new_ds['train'].data = X_train new_ds['train'].target = y_train logger.info(f"Writing Transformed Dataset: {new_ds["train"].name}") new_ds['train'].dump(force=force, dump_path=dump_path, dump_metadata=dump_metadata, create_dirs=create_dirs) new_ds['test'].data = X_test new_ds['test'].target = y_test logger.info(f"Writing Transformed Dataset: {new_ds["test"].name}") new_ds['test'].dump(force=force, dump_path=dump_path, dump_metadata=dump_metadata, create_dirs=create_dirs) return dset def pivot(dset, **pivot_opts): """Pivot data stored as a Pandas Dataframe pivot_opts: keyword arguments passed to pandas.Dataframe.pivot_table """ pivoted = dset.data.pivot_table(**pivot_opts) ds_pivot = Dataset(name=f"{dset.name}_pivoted", metadata=dset.metadata, data=pivoted, target=None) ds_pivot.metadata['pivot_opts'] = pivot_opts return ds_pivot def index_to_date_time(dset, suffix='dt'): """Transformer: Extract a datetime index into Date and Time columns""" df = dset.data.copy() df['Time']=df.index.time df['Date']=df.index.date df.reset_index(inplace=True, drop=True) new_ds = Dataset(dataset_name=f"{dset.name}_{suffix}", metadata=dset.metadata, data=df) return new_ds
import sys import pathlib import os from sklearn.model_selection import train_test_split from .datasets import Dataset from ..log import logger __all__ = [ 'available_transformers' ] _MODULE = sys.modules[__name__] _MODULE_DIR = pathlib.Path(os.path.dirname(os.path.abspath(__file__))) def available_transformers(keys_only=True): """Valid transformation functions This function simply returns a dict of known tranformer algorithms strings and their corresponding function call It exists to allow for a description of the mapping for each of the valid strings as a docstring The valid algorithm names, and the function they map to, are: ============ ==================================== string Transformer Function ============ ==================================== train_test_split train_test_split_xform pivot pivot index_to_date_time index_to_date_time ============ ==================================== Parameters ---------- keys_only: boolean If True, return only keys. Otherwise, return a dictionary mapping keys to algorithms """ _TRANSFORMERS = { "index_to_date_time": index_to_date_time, "pivot": pivot, "train_test_split": split_dataset_test_train, } if keys_only: return list(_TRANSFORMERS.keys()) return _TRANSFORMERS def split_dataset_test_train(dset, dump_path=None, dump_metadata=True, force=True, create_dirs=True, **split_opts): """Transformer that performs a train/test split. This transformer passes `dset` intact, but creates and dumps two new datasets as a side effect: {dset.name}_test and {dset.name}_train Parameters ---------- dump_metadata: boolean If True, also dump a standalone copy of the metadata. Useful for checking metadata without reading in the (potentially large) dataset itself dump_path: path. (default: `processed_data_path`) Directory where data will be dumped. force: boolean If False, raise an exception if any dunp files already exists If True, overwrite any existing files create_dirs: boolean If True, `dump_path` will be created (if necessary) **split_opts: Remaining options will be passed to `train_test_split` """ new_ds = {} for kind in ['train', 'test']: dset_name = f"{dset.name}_{kind}" dset_meta = {**dset.metadata, 'split':kind, 'split_opts':split_opts} new_ds[kind] = Dataset(dataset_name=dset_name, metadata=dset_meta) X_train, X_test, y_train, y_test = train_test_split(dset.data, dset.target, **split_opts) new_ds['train'].data = X_train new_ds['train'].target = y_train logger.info(f"Writing Transformed Dataset: {new_ds['train'].name}") new_ds['train'].dump(force=force, dump_path=dump_path, dump_metadata=dump_metadata, create_dirs=create_dirs) new_ds['test'].data = X_test new_ds['test'].target = y_test logger.info(f"Writing Transformed Dataset: {new_ds['test'].name}") new_ds['test'].dump(force=force, dump_path=dump_path, dump_metadata=dump_metadata, create_dirs=create_dirs) return dset def pivot(dset, **pivot_opts): """Pivot data stored as a Pandas Dataframe pivot_opts: keyword arguments passed to pandas.Dataframe.pivot_table """ pivoted = dset.data.pivot_table(**pivot_opts) ds_pivot = Dataset(name=f"{dset.name}_pivoted", metadata=dset.metadata, data=pivoted, target=None) ds_pivot.metadata['pivot_opts'] = pivot_opts return ds_pivot def index_to_date_time(dset, suffix='dt'): """Transformer: Extract a datetime index into Date and Time columns""" df = dset.data.copy() df['Time']=df.index.time df['Date']=df.index.date df.reset_index(inplace=True, drop=True) new_ds = Dataset(dataset_name=f"{dset.name}_{suffix}", metadata=dset.metadata, data=df) return new_ds
""" Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file 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. This script orchestrates the enablement and centralization of GuardDuty across an enterprise of AWS accounts. It takes in a list of AWS Account Numbers, iterates through each account and region to enable GuardDuty. It creates each account as a Member in the GuardDuty Master account. It invites and accepts the invite for each Member account. """ import boto3 import json import os import time import logging import requests from botocore.exceptions import ClientError LOGGER = logging.getLogger() LOGGER.setLevel(logging.INFO) logging.getLogger('boto3').setLevel(logging.CRITICAL) logging.getLogger('botocore').setLevel(logging.CRITICAL) session = boto3.Session() def send( event, context, responseStatus, responseData, physicalResourceId=None, noEcho=False): responseUrl = event['ResponseURL'] print(responseUrl) ls = context.log_stream_name responseBody = {} responseBody['Status'] = responseStatus responseBody['Reason'] = 'See the details in CloudWatch Log Stream: ' + ls responseBody['PhysicalResourceId'] = physicalResourceId or ls responseBody['StackId'] = event['StackId'] responseBody['RequestId'] = event['RequestId'] responseBody['LogicalResourceId'] = event['LogicalResourceId'] responseBody['NoEcho'] = noEcho responseBody['Data'] = responseData json_responseBody = json.dumps(responseBody) print("Response body:\n" + json_responseBody) headers = { 'content-type': '', 'content-length': str(len(json_responseBody)) } try: response = requests.put(responseUrl, data=json_responseBody, headers=headers) print("Status code: " + response.reason) except Exception as e: print("send(..) failed executing requests.put(..): " + str(e)) def get_enabled_regions(session, regions): """ With the introduction of regions that can be disabled it is necessary to test to see if a region can be used and not just assume we can enable it. """ enabled_regions = [] for region in regions: sts_client = session.client('sts', region_name=region) try: sts_client.get_caller_identity() enabled_regions.append(region) except ClientError as e: if e.response['Error']['Code'] == "InvalidClientTokenId": LOGGER.debug(f"{region} region is disabled.") else: LOGGER.debug(f"Error {e.response["Error"]} occured " f"testing region {region}") return enabled_regions def get_account_list(): """ Gets a list of Active AWS Accounts in the Organization. This is called if the function is not executed by an Sns trigger and is used for periodic scheduling to ensure all accounts are correctly configured, and prevent gaps in security from activities like new regions being added or GuardDuty being disabled. """ aws_account_dict = dict() orgclient = session.client('organizations', region_name=session.region_name) accounts = orgclient.list_accounts() while 'NextToken' in accounts: moreaccounts = orgclient.list_accounts(NextToken=accounts['NextToken']) for acct in accounts['Accounts']: moreaccounts['Accounts'].append(acct) accounts = moreaccounts LOGGER.debug(accounts) for account in accounts['Accounts']: LOGGER.debug(account) # Filter out suspended accounts and save valid accounts in a dict if account['Status'] == 'ACTIVE': accountid = account['Id'] email = account['Email'] aws_account_dict.update({accountid: email}) return aws_account_dict def assume_role(aws_account_number, role_name): """ Assumes the provided role in each account and returns a GuardDuty client :param aws_account_number: AWS Account Number :param role_name: Role to assume in target account :param aws_region: AWS Region for the Client call, not required for IAM calls :return: GuardDuty client in the specified AWS Account and Region """ # Beginning the assume role process for account sts_client = boto3.client('sts') # Get the current partition partition = sts_client.get_caller_identity()['Arn'].split(":")[1] response = sts_client.assume_role( RoleArn=f'arn:{partition}:iam::{aws_account_number}:role/{role_name}', RoleSessionName='EnableGuardDuty' ) # Storing STS credentials sts_session = boto3.Session( aws_access_key_id=response['Credentials']['AccessKeyId'], aws_secret_access_key=response['Credentials']['SecretAccessKey'], aws_session_token=response['Credentials']['SessionToken'] ) LOGGER.debug(f"Assumed session for {aws_account_number}.") return sts_session def get_master_members(master_session, aws_region, detector_id): """ Returns a list of current members of the GuardDuty master account :param aws_region: AWS Region of the GuardDuty master account :param detector_id: DetectorId of the GuardDuty master account in the AWS Region :return: dict of AwsAccountId:RelationshipStatus """ member_dict = dict() gd_client = master_session.client('guardduty', region_name=aws_region) paginator = gd_client.get_paginator('list_members') operation_parameters = { 'DetectorId': detector_id, 'OnlyAssociated': 'false' } # Need to paginate and iterate over results page_iterator = paginator.paginate(**operation_parameters) for page in page_iterator: if page['Members']: for member in page['Members']: member_dict.update( {member['AccountId']: member['RelationshipStatus']} ) return member_dict def list_detectors(client, aws_region): """ Lists the detectors in a given Account/Region Used to detect if a detector exists already :param client: GuardDuty client :param aws_region: AWS Region :return: Dictionary of AWS_Region: DetectorId """ detector_dict = client.list_detectors() if detector_dict['DetectorIds']: for detector in detector_dict['DetectorIds']: detector_dict.update({aws_region: detector}) else: detector_dict.update({aws_region: ''}) return detector_dict def logStatus(action, account, master, region, status): """ Log status of each member account :param action: action on the account, such as Removing or Disassociating :param account: GuardDuty member account :parm master: GuardDuty master account :param aws_region: AWS Region :param: GuardDuty member account status """ LOGGER.info(f"{action} account {account} from GuardDuty master {master} " f" in region {region} because of it is {status}") def get_ct_regions(session): # This is a hack to find the control tower supported regions, as there # is no API for it right now it enumerates the # AWSControlTowerBP-BASELINE-CLOUDWATCH CloudFormation StackSet and finds # what regions it has deployed stacks too. # It doesn't have to evaluate enabled_regions as only enabled regions # will/can have stacks deployed cf = session.client('cloudformation') stacks = cf.list_stack_instances( StackSetName='AWSControlTowerBP-BASELINE-CLOUDWATCH') region_set = set() for stack in stacks['Summaries']: region_set.add(stack['Region']) return list(region_set) def list_members(client, detector_id): member_dict = dict() response = client.list_members( DetectorId=detector_id, OnlyAssociated='false' ) for member in response['Members']: member_dict.update({member['AccountId']: member['RelationshipStatus']}) return member_dict def disable_guardduty(master_session, guardduty_regions, master_account): for aws_region in guardduty_regions: gd_client = master_session.client('guardduty', region_name=aws_region) detector_dict = list_detectors(gd_client, aws_region) detector_id = detector_dict[aws_region] if detector_id != '': LOGGER.info(f"GuardDuty is active in {aws_region}") if detector_id != '': member_dict = list_members(gd_client, detector_id) if member_dict: LOGGER.info(f"There are members in {aws_region}.") response = gd_client.disassociate_members( AccountIds=list(member_dict.keys()), DetectorId=detector_id ) response = gd_client.delete_members( DetectorId=detector_id, AccountIds=list(member_dict.keys()) ) LOGGER.info(f"Deleting members for {master_account} " f"in {aws_region}") else: LOGGER.info(f"No detector found for {master_account} " f"in {aws_region}") def lambda_handler(event, context): LOGGER.debug('REQUEST RECEIVED:\n %s', event) LOGGER.debug('REQUEST RECEIVED:\n %s', context) guardduty_regions = [] master_account = os.environ['master_account'] master_session = assume_role( master_account, os.environ['assume_role'] ) if os.environ['region_filter'] == 'GuardDuty': guardduty_regions = get_enabled_regions( session, session.get_available_regions('guardduty',partition_name=os.environ['topic'].split(":")[1])) LOGGER.debug(f"Enabling members in all available GuardDuty " f"regions {guardduty_regions}") else: guardduty_regions = get_ct_regions(session) LOGGER.debug(f"Enabling members in all available ControlTower " f"regions {guardduty_regions}") # Check for Custom Resource Call if 'RequestType' in event and ( event['RequestType'] == "Delete" or event['RequestType'] == "Create" or event['RequestType'] == "Update"): action = event['RequestType'] if action == "Delete": disable_guardduty( master_session, guardduty_regions, master_account ) LOGGER.info("Sending Custom Resource Response") responseData = {} send(event, context, "SUCCESS", responseData) if action == "Delete": # Exit on delete so it doesn't re-enable existing accounts raise SystemExit() else: LOGGER.info("Sending Custom Resource Response") responseData = {} send(event, context, "SUCCESS", responseData) master_detector_id_dict = dict() aws_account_dict = dict() # detect if the function was called by Sns if 'Records' in event: message = event['Records'][0]['Sns']['Message'] LOGGER.debug(message) jsonmessage = json.loads(message) accountid = jsonmessage['AccountId'] email = jsonmessage['Email'] aws_account_dict.update({accountid: email}) else: # Not called by Sns so enumerating accounts, and recursively # calling itself via sns aws_account_dict = get_account_list() sns_client = session.client( 'sns', region_name=os.environ['AWS_REGION'] ) for accountid, email in aws_account_dict.items(): # sns is used to fan out the requests, as too many accounts # would result in the function timing out LOGGER.debug(f"Sending job to configure account {accountid}") response = sns_client.publish( TopicArn=os.environ['topic'], Message="{\"AccountId\":\""+accountid+"\"," "\"Email\":\""+email+"\"}" ) return True for aws_region in guardduty_regions: gd_client = master_session.client('guardduty', region_name=aws_region) detector_dict = list_detectors(gd_client, aws_region) if detector_dict[aws_region]: LOGGER.debug(f"Found existing detector {detector_dict[aws_region]}" f" in {aws_region} for {master_account}") master_detector_id_dict.update( {aws_region: detector_dict[aws_region]} ) else: detector_str = gd_client.create_detector(Enable=True)['DetectorId'] LOGGER.info(f"Created detector {detector_str} in {aws_region} " f"for {master_account}") master_detector_id_dict.update({aws_region: detector_str}) failed_accounts = [] for account in aws_account_dict.keys(): if account != os.environ['ct_root_account']: target_session = assume_role(account, os.environ['assume_role']) else: target_session = session for aws_region in guardduty_regions: LOGGER.debug(f"Beginning {account} in {aws_region}") gd_client = target_session.client( 'guardduty', region_name=aws_region ) detector_dict = list_detectors(gd_client, aws_region) detector_id = detector_dict[aws_region] if detector_id: LOGGER.debug(f"Found existing detector {detector_id} in " f"{aws_region} for {account}") try: detector_status = gd_client.get_detector( DetectorId=detector_id ) if detector_status['Status'] != 'ENABLED': update_result = gd_client.update_detector( DetectorId=detector_id, Enable=True, FindingPublishingFrequency=( detector_status['FindingPublishingFrequency'] ) ) LOGGER.warning(f"Re-enabled disabled detector " f"{detector_id} in {aws_region} for " f"{account} with {update_result}") except ClientError as e: LOGGER.debug(f"Error Processing Account {account}") failed_accounts.append({ 'AccountId': account, 'Region': aws_region }) else: detector_str = \ gd_client.create_detector(Enable=True)['DetectorId'] LOGGER.info(f"Created detector {detector_str} in " f"{aws_region} for {account}") detector_id = detector_str master_detector_id = master_detector_id_dict[aws_region] member_dict = get_master_members( master_session, aws_region, master_detector_id ) if ((account not in member_dict) and (account != master_account)): gd_client = master_session.client( 'guardduty', region_name=aws_region ) gd_client.create_members( AccountDetails=[ { 'AccountId': account, 'Email': aws_account_dict[account] } ], DetectorId=master_detector_id ) LOGGER.info(f"Added Account {account} to member list " f"in GuardDuty master account {master_account} " f"for region {aws_region}") start_time = int(time.time()) while account not in member_dict: if (int(time.time()) - start_time) > 300: LOGGER.debug(f"Membership did not show up for " f"account {account}, skipping") break time.sleep(5) member_dict = get_master_members( master_session, aws_region, master_detector_id ) else: LOGGER.debug(f"Account {account} is already a member of " f"{master_account} in region {aws_region}") if account != master_account: if member_dict[account] == 'Enabled': LOGGER.debug(f"Account {account} is already " f"{member_dict[account]}") else: master_gd_client = master_session.client( 'guardduty', region_name=aws_region ) gd_client = target_session.client( 'guardduty', region_name=aws_region ) start_time = int(time.time()) while member_dict[account] != 'Enabled': if (int(time.time()) - start_time) > 300: LOGGER.debug(f"Enabled status did not show up " f"for account {account}, skipping") break time.sleep(5) if member_dict[account] == 'Created': master_gd_client = master_session.client( 'guardduty', region_name=aws_region ) master_gd_client.invite_members( AccountIds=[account], DetectorId=master_detector_id, DisableEmailNotification=True ) LOGGER.info(f"Invited Account {account} to " f"GuardDuty master account " f"{master_account} in " f"region {aws_region}") elif member_dict[account] == 'Invited': response = gd_client.list_invitations() invitation_id = None for invitation in response['Invitations']: invitation_id = invitation['InvitationId'] if invitation_id is not None: gd_client.accept_invitation( DetectorId=detector_id, InvitationId=invitation_id, MasterId=str(master_account) ) LOGGER.info(f"Accepting Account {account} to " f"GuardDuty master account " f"{master_account} in " f"region {aws_region}") elif member_dict[account] == 'Resigned': response = master_gd_client.delete_members( DetectorId=master_detector_id, AccountIds=[account] ) logStatus( "Removing", account, master_account, aws_region, member_dict[account] ) elif member_dict[account] == 'Disabled': response = master_gd_client.disassociate_members( DetectorId=master_detector_id, AccountIds=[account] ) logStatus( "Disassociating", account, master_account, aws_region, member_dict[account] ) elif member_dict[account] == 'Removed': response = master_gd_client.delete_members( DetectorId=master_detector_id, AccountIds=[account] ) logStatus( "Removing", account, master_account, aws_region, member_dict[account] ) else: logStatus( "Waiting", account, master_account, aws_region, member_dict[account] ) member_dict = get_master_members( master_session, aws_region, master_detector_id ) LOGGER.debug(f"Finished {account} in {aws_region}") if len(failed_accounts) > 0: LOGGER.info("Error Processing following accounts: %s" % ( json.dumps(failed_accounts, sort_keys=True, default=str)))
""" Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file 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. This script orchestrates the enablement and centralization of GuardDuty across an enterprise of AWS accounts. It takes in a list of AWS Account Numbers, iterates through each account and region to enable GuardDuty. It creates each account as a Member in the GuardDuty Master account. It invites and accepts the invite for each Member account. """ import boto3 import json import os import time import logging import requests from botocore.exceptions import ClientError LOGGER = logging.getLogger() LOGGER.setLevel(logging.INFO) logging.getLogger('boto3').setLevel(logging.CRITICAL) logging.getLogger('botocore').setLevel(logging.CRITICAL) session = boto3.Session() def send( event, context, responseStatus, responseData, physicalResourceId=None, noEcho=False): responseUrl = event['ResponseURL'] print(responseUrl) ls = context.log_stream_name responseBody = {} responseBody['Status'] = responseStatus responseBody['Reason'] = 'See the details in CloudWatch Log Stream: ' + ls responseBody['PhysicalResourceId'] = physicalResourceId or ls responseBody['StackId'] = event['StackId'] responseBody['RequestId'] = event['RequestId'] responseBody['LogicalResourceId'] = event['LogicalResourceId'] responseBody['NoEcho'] = noEcho responseBody['Data'] = responseData json_responseBody = json.dumps(responseBody) print("Response body:\n" + json_responseBody) headers = { 'content-type': '', 'content-length': str(len(json_responseBody)) } try: response = requests.put(responseUrl, data=json_responseBody, headers=headers) print("Status code: " + response.reason) except Exception as e: print("send(..) failed executing requests.put(..): " + str(e)) def get_enabled_regions(session, regions): """ With the introduction of regions that can be disabled it is necessary to test to see if a region can be used and not just assume we can enable it. """ enabled_regions = [] for region in regions: sts_client = session.client('sts', region_name=region) try: sts_client.get_caller_identity() enabled_regions.append(region) except ClientError as e: if e.response['Error']['Code'] == "InvalidClientTokenId": LOGGER.debug(f"{region} region is disabled.") else: LOGGER.debug(f"Error {e.response['Error']} occured " f"testing region {region}") return enabled_regions def get_account_list(): """ Gets a list of Active AWS Accounts in the Organization. This is called if the function is not executed by an Sns trigger and is used for periodic scheduling to ensure all accounts are correctly configured, and prevent gaps in security from activities like new regions being added or GuardDuty being disabled. """ aws_account_dict = dict() orgclient = session.client('organizations', region_name=session.region_name) accounts = orgclient.list_accounts() while 'NextToken' in accounts: moreaccounts = orgclient.list_accounts(NextToken=accounts['NextToken']) for acct in accounts['Accounts']: moreaccounts['Accounts'].append(acct) accounts = moreaccounts LOGGER.debug(accounts) for account in accounts['Accounts']: LOGGER.debug(account) # Filter out suspended accounts and save valid accounts in a dict if account['Status'] == 'ACTIVE': accountid = account['Id'] email = account['Email'] aws_account_dict.update({accountid: email}) return aws_account_dict def assume_role(aws_account_number, role_name): """ Assumes the provided role in each account and returns a GuardDuty client :param aws_account_number: AWS Account Number :param role_name: Role to assume in target account :param aws_region: AWS Region for the Client call, not required for IAM calls :return: GuardDuty client in the specified AWS Account and Region """ # Beginning the assume role process for account sts_client = boto3.client('sts') # Get the current partition partition = sts_client.get_caller_identity()['Arn'].split(":")[1] response = sts_client.assume_role( RoleArn=f'arn:{partition}:iam::{aws_account_number}:role/{role_name}', RoleSessionName='EnableGuardDuty' ) # Storing STS credentials sts_session = boto3.Session( aws_access_key_id=response['Credentials']['AccessKeyId'], aws_secret_access_key=response['Credentials']['SecretAccessKey'], aws_session_token=response['Credentials']['SessionToken'] ) LOGGER.debug(f"Assumed session for {aws_account_number}.") return sts_session def get_master_members(master_session, aws_region, detector_id): """ Returns a list of current members of the GuardDuty master account :param aws_region: AWS Region of the GuardDuty master account :param detector_id: DetectorId of the GuardDuty master account in the AWS Region :return: dict of AwsAccountId:RelationshipStatus """ member_dict = dict() gd_client = master_session.client('guardduty', region_name=aws_region) paginator = gd_client.get_paginator('list_members') operation_parameters = { 'DetectorId': detector_id, 'OnlyAssociated': 'false' } # Need to paginate and iterate over results page_iterator = paginator.paginate(**operation_parameters) for page in page_iterator: if page['Members']: for member in page['Members']: member_dict.update( {member['AccountId']: member['RelationshipStatus']} ) return member_dict def list_detectors(client, aws_region): """ Lists the detectors in a given Account/Region Used to detect if a detector exists already :param client: GuardDuty client :param aws_region: AWS Region :return: Dictionary of AWS_Region: DetectorId """ detector_dict = client.list_detectors() if detector_dict['DetectorIds']: for detector in detector_dict['DetectorIds']: detector_dict.update({aws_region: detector}) else: detector_dict.update({aws_region: ''}) return detector_dict def logStatus(action, account, master, region, status): """ Log status of each member account :param action: action on the account, such as Removing or Disassociating :param account: GuardDuty member account :parm master: GuardDuty master account :param aws_region: AWS Region :param: GuardDuty member account status """ LOGGER.info(f"{action} account {account} from GuardDuty master {master} " f" in region {region} because of it is {status}") def get_ct_regions(session): # This is a hack to find the control tower supported regions, as there # is no API for it right now it enumerates the # AWSControlTowerBP-BASELINE-CLOUDWATCH CloudFormation StackSet and finds # what regions it has deployed stacks too. # It doesn't have to evaluate enabled_regions as only enabled regions # will/can have stacks deployed cf = session.client('cloudformation') stacks = cf.list_stack_instances( StackSetName='AWSControlTowerBP-BASELINE-CLOUDWATCH') region_set = set() for stack in stacks['Summaries']: region_set.add(stack['Region']) return list(region_set) def list_members(client, detector_id): member_dict = dict() response = client.list_members( DetectorId=detector_id, OnlyAssociated='false' ) for member in response['Members']: member_dict.update({member['AccountId']: member['RelationshipStatus']}) return member_dict def disable_guardduty(master_session, guardduty_regions, master_account): for aws_region in guardduty_regions: gd_client = master_session.client('guardduty', region_name=aws_region) detector_dict = list_detectors(gd_client, aws_region) detector_id = detector_dict[aws_region] if detector_id != '': LOGGER.info(f"GuardDuty is active in {aws_region}") if detector_id != '': member_dict = list_members(gd_client, detector_id) if member_dict: LOGGER.info(f"There are members in {aws_region}.") response = gd_client.disassociate_members( AccountIds=list(member_dict.keys()), DetectorId=detector_id ) response = gd_client.delete_members( DetectorId=detector_id, AccountIds=list(member_dict.keys()) ) LOGGER.info(f"Deleting members for {master_account} " f"in {aws_region}") else: LOGGER.info(f"No detector found for {master_account} " f"in {aws_region}") def lambda_handler(event, context): LOGGER.debug('REQUEST RECEIVED:\n %s', event) LOGGER.debug('REQUEST RECEIVED:\n %s', context) guardduty_regions = [] master_account = os.environ['master_account'] master_session = assume_role( master_account, os.environ['assume_role'] ) if os.environ['region_filter'] == 'GuardDuty': guardduty_regions = get_enabled_regions( session, session.get_available_regions('guardduty',partition_name=os.environ['topic'].split(":")[1])) LOGGER.debug(f"Enabling members in all available GuardDuty " f"regions {guardduty_regions}") else: guardduty_regions = get_ct_regions(session) LOGGER.debug(f"Enabling members in all available ControlTower " f"regions {guardduty_regions}") # Check for Custom Resource Call if 'RequestType' in event and ( event['RequestType'] == "Delete" or event['RequestType'] == "Create" or event['RequestType'] == "Update"): action = event['RequestType'] if action == "Delete": disable_guardduty( master_session, guardduty_regions, master_account ) LOGGER.info("Sending Custom Resource Response") responseData = {} send(event, context, "SUCCESS", responseData) if action == "Delete": # Exit on delete so it doesn't re-enable existing accounts raise SystemExit() else: LOGGER.info("Sending Custom Resource Response") responseData = {} send(event, context, "SUCCESS", responseData) master_detector_id_dict = dict() aws_account_dict = dict() # detect if the function was called by Sns if 'Records' in event: message = event['Records'][0]['Sns']['Message'] LOGGER.debug(message) jsonmessage = json.loads(message) accountid = jsonmessage['AccountId'] email = jsonmessage['Email'] aws_account_dict.update({accountid: email}) else: # Not called by Sns so enumerating accounts, and recursively # calling itself via sns aws_account_dict = get_account_list() sns_client = session.client( 'sns', region_name=os.environ['AWS_REGION'] ) for accountid, email in aws_account_dict.items(): # sns is used to fan out the requests, as too many accounts # would result in the function timing out LOGGER.debug(f"Sending job to configure account {accountid}") response = sns_client.publish( TopicArn=os.environ['topic'], Message="{\"AccountId\":\""+accountid+"\"," "\"Email\":\""+email+"\"}" ) return True for aws_region in guardduty_regions: gd_client = master_session.client('guardduty', region_name=aws_region) detector_dict = list_detectors(gd_client, aws_region) if detector_dict[aws_region]: LOGGER.debug(f"Found existing detector {detector_dict[aws_region]}" f" in {aws_region} for {master_account}") master_detector_id_dict.update( {aws_region: detector_dict[aws_region]} ) else: detector_str = gd_client.create_detector(Enable=True)['DetectorId'] LOGGER.info(f"Created detector {detector_str} in {aws_region} " f"for {master_account}") master_detector_id_dict.update({aws_region: detector_str}) failed_accounts = [] for account in aws_account_dict.keys(): if account != os.environ['ct_root_account']: target_session = assume_role(account, os.environ['assume_role']) else: target_session = session for aws_region in guardduty_regions: LOGGER.debug(f"Beginning {account} in {aws_region}") gd_client = target_session.client( 'guardduty', region_name=aws_region ) detector_dict = list_detectors(gd_client, aws_region) detector_id = detector_dict[aws_region] if detector_id: LOGGER.debug(f"Found existing detector {detector_id} in " f"{aws_region} for {account}") try: detector_status = gd_client.get_detector( DetectorId=detector_id ) if detector_status['Status'] != 'ENABLED': update_result = gd_client.update_detector( DetectorId=detector_id, Enable=True, FindingPublishingFrequency=( detector_status['FindingPublishingFrequency'] ) ) LOGGER.warning(f"Re-enabled disabled detector " f"{detector_id} in {aws_region} for " f"{account} with {update_result}") except ClientError as e: LOGGER.debug(f"Error Processing Account {account}") failed_accounts.append({ 'AccountId': account, 'Region': aws_region }) else: detector_str = \ gd_client.create_detector(Enable=True)['DetectorId'] LOGGER.info(f"Created detector {detector_str} in " f"{aws_region} for {account}") detector_id = detector_str master_detector_id = master_detector_id_dict[aws_region] member_dict = get_master_members( master_session, aws_region, master_detector_id ) if ((account not in member_dict) and (account != master_account)): gd_client = master_session.client( 'guardduty', region_name=aws_region ) gd_client.create_members( AccountDetails=[ { 'AccountId': account, 'Email': aws_account_dict[account] } ], DetectorId=master_detector_id ) LOGGER.info(f"Added Account {account} to member list " f"in GuardDuty master account {master_account} " f"for region {aws_region}") start_time = int(time.time()) while account not in member_dict: if (int(time.time()) - start_time) > 300: LOGGER.debug(f"Membership did not show up for " f"account {account}, skipping") break time.sleep(5) member_dict = get_master_members( master_session, aws_region, master_detector_id ) else: LOGGER.debug(f"Account {account} is already a member of " f"{master_account} in region {aws_region}") if account != master_account: if member_dict[account] == 'Enabled': LOGGER.debug(f"Account {account} is already " f"{member_dict[account]}") else: master_gd_client = master_session.client( 'guardduty', region_name=aws_region ) gd_client = target_session.client( 'guardduty', region_name=aws_region ) start_time = int(time.time()) while member_dict[account] != 'Enabled': if (int(time.time()) - start_time) > 300: LOGGER.debug(f"Enabled status did not show up " f"for account {account}, skipping") break time.sleep(5) if member_dict[account] == 'Created': master_gd_client = master_session.client( 'guardduty', region_name=aws_region ) master_gd_client.invite_members( AccountIds=[account], DetectorId=master_detector_id, DisableEmailNotification=True ) LOGGER.info(f"Invited Account {account} to " f"GuardDuty master account " f"{master_account} in " f"region {aws_region}") elif member_dict[account] == 'Invited': response = gd_client.list_invitations() invitation_id = None for invitation in response['Invitations']: invitation_id = invitation['InvitationId'] if invitation_id is not None: gd_client.accept_invitation( DetectorId=detector_id, InvitationId=invitation_id, MasterId=str(master_account) ) LOGGER.info(f"Accepting Account {account} to " f"GuardDuty master account " f"{master_account} in " f"region {aws_region}") elif member_dict[account] == 'Resigned': response = master_gd_client.delete_members( DetectorId=master_detector_id, AccountIds=[account] ) logStatus( "Removing", account, master_account, aws_region, member_dict[account] ) elif member_dict[account] == 'Disabled': response = master_gd_client.disassociate_members( DetectorId=master_detector_id, AccountIds=[account] ) logStatus( "Disassociating", account, master_account, aws_region, member_dict[account] ) elif member_dict[account] == 'Removed': response = master_gd_client.delete_members( DetectorId=master_detector_id, AccountIds=[account] ) logStatus( "Removing", account, master_account, aws_region, member_dict[account] ) else: logStatus( "Waiting", account, master_account, aws_region, member_dict[account] ) member_dict = get_master_members( master_session, aws_region, master_detector_id ) LOGGER.debug(f"Finished {account} in {aws_region}") if len(failed_accounts) > 0: LOGGER.info("Error Processing following accounts: %s" % ( json.dumps(failed_accounts, sort_keys=True, default=str)))
# app.py from flask import Flask, request, jsonify from flask_cors import CORS, cross_origin import psycopg2 import os import database app = Flask(__name__) # Eliminate CORS issue. CORS(app) @app.route('/waitlist', methods=['POST']) def post_waitlist(): param = request.get_json() print(param) # You can add the test cases you made in the previous function, but in our case here you are just testing the POST functionality if param: waitlist_spot = database.add_email(param) return jsonify({ "Message": f"Welcome {param.get("email")} to our awesome platform!!", "waitlist_spot": waitlist_spot, # Add this option to distinct the POST request "METHOD" : "POST" }) else: return jsonify({ "ERROR": "no email found, please send email." }) # A welcome message to test our server @app.route('/') def index(): return "<h1>Dude, wyd? Go somewhere else lmao... but if you need taxes done we got ur back.. btw we're planning on rolling out the rest of our bank soon. Wouldn't it make a lot of sense if your bank offered to do your taxes? And budget? And like way more than your bank now does? Yea we know.</h1>" if __name__ == '__main__': # Threaded option to enable multiple instances for multiple user access support app.run(threaded=True, port=5000)
# app.py from flask import Flask, request, jsonify from flask_cors import CORS, cross_origin import psycopg2 import os import database app = Flask(__name__) # Eliminate CORS issue. CORS(app) @app.route('/waitlist', methods=['POST']) def post_waitlist(): param = request.get_json() print(param) # You can add the test cases you made in the previous function, but in our case here you are just testing the POST functionality if param: waitlist_spot = database.add_email(param) return jsonify({ "Message": f"Welcome {param.get('email')} to our awesome platform!!", "waitlist_spot": waitlist_spot, # Add this option to distinct the POST request "METHOD" : "POST" }) else: return jsonify({ "ERROR": "no email found, please send email." }) # A welcome message to test our server @app.route('/') def index(): return "<h1>Dude, wyd? Go somewhere else lmao... but if you need taxes done we got ur back.. btw we're planning on rolling out the rest of our bank soon. Wouldn't it make a lot of sense if your bank offered to do your taxes? And budget? And like way more than your bank now does? Yea we know.</h1>" if __name__ == '__main__': # Threaded option to enable multiple instances for multiple user access support app.run(threaded=True, port=5000)
import datetime import lxml.etree as ET import re import requests import cachetools.func from settings import CACHE_TTL_SECS, CACHE_MAX_SIZE from flask_restful import abort from utils import server_log @cachetools.func.ttl_cache(ttl=CACHE_TTL_SECS, maxsize=CACHE_MAX_SIZE) def get_doi_content(user_doi): """ This function is designed to render the paper-journal network for the user given identifier. Code Grabs the latest preprint version to generate results. Args: user_doi - user provided biorxiv/medrxiv doi or arxiv id """ # create flag if xml is found xml_found = False # Check to see if user_doi is a biorxiv/medrxiv doi # if not then resort to searching for arxiv bio_med_rxiv = re.search(r"10\.1101\/", user_doi) is not None if bio_med_rxiv: # Try pinging biorxiv server first content = ping_biorxiv_or_medrxiv(user_doi, server="biorxiv") doc_url = f"http://biorxiv.org/content" # If no match found try medrxiv if content is None: content = ping_biorxiv_or_medrxiv(user_doi, server="medrxiv") doc_url = f"http://medrxiv.org/content" # If no match at all then raise the red flag if content is None: message = ( f"Cannot find document {user_doi} in either biorxiv or medrxiv." ) server_log(f"{message}\n") abort(404, message=message) latest_paper = content["collection"][-1] paper_metadata = { "title": latest_paper["title"], "authors": latest_paper["authors"], "doi": latest_paper["doi"], "accepted_date": latest_paper["date"], "publisher": "Cold Spring Harbor Laboratory", } # Grab latest version of the XML file if available accepted_date = latest_paper["date"].replace("-", "/") file_url = ( f"{doc_url}/early/{accepted_date}/{user_doi.split("/")[-1]}.source.xml" ) # If not bioRxiv/medRxiv definitely arxiv else: doc_url = f"https://export.arxiv.org/api/query?id_list={user_doi}" response = requests.get(doc_url) # If document cannot be found in arxiv log and report if response is None: message = f"Cannot reach arxiv api server." server_log(f"{message}\n") abort(404, message=message) latest_paper, latest_file_url = parse_arxiv_output(response.text) if latest_paper == None: message = f"Cannot find {user_doi} on arxiv's api server." server_log(f"{message}\n") abort(404, message=message) # I doubt this will execute but # there could be a case where a document's download link cannot be found if latest_file_url == None: message = f"Cannot find download link for {user_doi} on arxiv's api server." server_log(f"{message}\n") abort(404, message=message) paper_metadata = { "title": latest_paper["title"], "authors": latest_paper["authors"], "doi": user_doi, "accepted_date": latest_paper["date"], "publisher": "Arxiv - Cornell Univeristy", } # biorxiv has xml files available # This block here is designed to first attempt to retrieve the xml file # then defaults to pdf if xml cannot be found # Arxiv only has pdf so can skip this section if bio_med_rxiv: try: response = requests.get(file_url) if response.status_code == 200: xml_found = True except Exception as e: message = f"Cannot connect to {file_url}" server_log(f"{message}: {e}\n") # If xml not found then use PDF version if not xml_found: # Grab latest version of PDF file file_url = ( f"{doc_url}/{user_doi}v{latest_paper["version"]}.full.pdf" if bio_med_rxiv else f"https://export.arxiv.org/pdf/{latest_file_url}" ) try: response = requests.get(file_url) except Exception as e: message = f"Cannot connect to {file_url}" server_log(f"{message}: {e}\n") abort(404, message=message) if response.status_code != 200: message = f"Invalid response from {file_url}" server_log(f"{message}\n") abort(response.status_code, message=message) return response.content, paper_metadata, xml_found def parse_arxiv_output(xml_feed): """ This function is designed to parse output from the arxiv server Args: xml_feed - the xml output obtained from export.arxiv.org api server """ arxiv_api_xml_obj = ET.fromstring(str.encode(xml_feed)) # Extract the metadata title = arxiv_api_xml_obj.xpath( '/*[local-name()="feed"]/*[local-name()="entry"]' '/*[local-name()="title"]/text()' )[0] # Arxiv server reports back an error if document cannnot be found # this circumvents the rest of the code if the document cannot be found if title == "Error": return None, None # Remove pesky newlines for title if present title = title.replace("\n", "") authors = arxiv_api_xml_obj.xpath( '/*[local-name()="feed"]/*[local-name()="entry"]' '/*[local-name()="author"]/*[local-name()="name"]/text()' ) authors = ";".join(authors) accepted_date = arxiv_api_xml_obj.xpath( '/*[local-name()="feed"]/*[local-name()="entry"]' '/*[local-name()="published"]/text()' )[0] accepted_date = datetime.datetime.strptime( accepted_date, "%Y-%m-%dT%H:%M:%SZ" ).strftime("%Y-%m-%d") file_url = arxiv_api_xml_obj.xpath( '/*[local-name()="feed"]/*[local-name()="entry"]' '/*[local-name()="link"][@type="application/pdf"]' )[0] latest_file_version = file_url.attrib["href"].split("/")[-1] return dict(title=title, date=accepted_date, authors=authors), latest_file_version def ping_biorxiv_or_medrxiv(doi, server="biorxiv"): """ This function pings biorxiv or medrxiv to see if doi exists within their repository Args: doi - a doi that grabs the most current version of a preprint """ api_url = f"https://api.biorxiv.org/details/{server}/{doi}" try: response = requests.get(api_url) except Exception as e: message = f"Cannot connect to {api_url}" server_log(f"{message}: {e}\n") abort(404, message=message) if response.status_code != 200: message = f"Invalid response from {api_url}" server_log(f"{message}\n") abort(response.status_code, message=message) try: content = response.json() except Exception as e: message = f"Cannot convert response from {api_url} to json format" server_log(f"{message}: {e}\n") abort(404, message=message) if len(content["collection"]) < 1: return None return content
import datetime import lxml.etree as ET import re import requests import cachetools.func from settings import CACHE_TTL_SECS, CACHE_MAX_SIZE from flask_restful import abort from utils import server_log @cachetools.func.ttl_cache(ttl=CACHE_TTL_SECS, maxsize=CACHE_MAX_SIZE) def get_doi_content(user_doi): """ This function is designed to render the paper-journal network for the user given identifier. Code Grabs the latest preprint version to generate results. Args: user_doi - user provided biorxiv/medrxiv doi or arxiv id """ # create flag if xml is found xml_found = False # Check to see if user_doi is a biorxiv/medrxiv doi # if not then resort to searching for arxiv bio_med_rxiv = re.search(r"10\.1101\/", user_doi) is not None if bio_med_rxiv: # Try pinging biorxiv server first content = ping_biorxiv_or_medrxiv(user_doi, server="biorxiv") doc_url = f"http://biorxiv.org/content" # If no match found try medrxiv if content is None: content = ping_biorxiv_or_medrxiv(user_doi, server="medrxiv") doc_url = f"http://medrxiv.org/content" # If no match at all then raise the red flag if content is None: message = ( f"Cannot find document {user_doi} in either biorxiv or medrxiv." ) server_log(f"{message}\n") abort(404, message=message) latest_paper = content["collection"][-1] paper_metadata = { "title": latest_paper["title"], "authors": latest_paper["authors"], "doi": latest_paper["doi"], "accepted_date": latest_paper["date"], "publisher": "Cold Spring Harbor Laboratory", } # Grab latest version of the XML file if available accepted_date = latest_paper["date"].replace("-", "/") file_url = ( f"{doc_url}/early/{accepted_date}/{user_doi.split('/')[-1]}.source.xml" ) # If not bioRxiv/medRxiv definitely arxiv else: doc_url = f"https://export.arxiv.org/api/query?id_list={user_doi}" response = requests.get(doc_url) # If document cannot be found in arxiv log and report if response is None: message = f"Cannot reach arxiv api server." server_log(f"{message}\n") abort(404, message=message) latest_paper, latest_file_url = parse_arxiv_output(response.text) if latest_paper == None: message = f"Cannot find {user_doi} on arxiv's api server." server_log(f"{message}\n") abort(404, message=message) # I doubt this will execute but # there could be a case where a document's download link cannot be found if latest_file_url == None: message = f"Cannot find download link for {user_doi} on arxiv's api server." server_log(f"{message}\n") abort(404, message=message) paper_metadata = { "title": latest_paper["title"], "authors": latest_paper["authors"], "doi": user_doi, "accepted_date": latest_paper["date"], "publisher": "Arxiv - Cornell Univeristy", } # biorxiv has xml files available # This block here is designed to first attempt to retrieve the xml file # then defaults to pdf if xml cannot be found # Arxiv only has pdf so can skip this section if bio_med_rxiv: try: response = requests.get(file_url) if response.status_code == 200: xml_found = True except Exception as e: message = f"Cannot connect to {file_url}" server_log(f"{message}: {e}\n") # If xml not found then use PDF version if not xml_found: # Grab latest version of PDF file file_url = ( f"{doc_url}/{user_doi}v{latest_paper['version']}.full.pdf" if bio_med_rxiv else f"https://export.arxiv.org/pdf/{latest_file_url}" ) try: response = requests.get(file_url) except Exception as e: message = f"Cannot connect to {file_url}" server_log(f"{message}: {e}\n") abort(404, message=message) if response.status_code != 200: message = f"Invalid response from {file_url}" server_log(f"{message}\n") abort(response.status_code, message=message) return response.content, paper_metadata, xml_found def parse_arxiv_output(xml_feed): """ This function is designed to parse output from the arxiv server Args: xml_feed - the xml output obtained from export.arxiv.org api server """ arxiv_api_xml_obj = ET.fromstring(str.encode(xml_feed)) # Extract the metadata title = arxiv_api_xml_obj.xpath( '/*[local-name()="feed"]/*[local-name()="entry"]' '/*[local-name()="title"]/text()' )[0] # Arxiv server reports back an error if document cannnot be found # this circumvents the rest of the code if the document cannot be found if title == "Error": return None, None # Remove pesky newlines for title if present title = title.replace("\n", "") authors = arxiv_api_xml_obj.xpath( '/*[local-name()="feed"]/*[local-name()="entry"]' '/*[local-name()="author"]/*[local-name()="name"]/text()' ) authors = ";".join(authors) accepted_date = arxiv_api_xml_obj.xpath( '/*[local-name()="feed"]/*[local-name()="entry"]' '/*[local-name()="published"]/text()' )[0] accepted_date = datetime.datetime.strptime( accepted_date, "%Y-%m-%dT%H:%M:%SZ" ).strftime("%Y-%m-%d") file_url = arxiv_api_xml_obj.xpath( '/*[local-name()="feed"]/*[local-name()="entry"]' '/*[local-name()="link"][@type="application/pdf"]' )[0] latest_file_version = file_url.attrib["href"].split("/")[-1] return dict(title=title, date=accepted_date, authors=authors), latest_file_version def ping_biorxiv_or_medrxiv(doi, server="biorxiv"): """ This function pings biorxiv or medrxiv to see if doi exists within their repository Args: doi - a doi that grabs the most current version of a preprint """ api_url = f"https://api.biorxiv.org/details/{server}/{doi}" try: response = requests.get(api_url) except Exception as e: message = f"Cannot connect to {api_url}" server_log(f"{message}: {e}\n") abort(404, message=message) if response.status_code != 200: message = f"Invalid response from {api_url}" server_log(f"{message}\n") abort(response.status_code, message=message) try: content = response.json() except Exception as e: message = f"Cannot convert response from {api_url} to json format" server_log(f"{message}: {e}\n") abort(404, message=message) if len(content["collection"]) < 1: return None return content
import functools import inspect import logging import warnings from typing import Union, Callable from blizz import _inspect from ._helpers import doublewrap from ._primitives import Relation, Type, is_pandas_df, is_pyspark_df try: import pyspark except ImportError: # pragma: no cover pyspark = None # pragma: no cover try: import pandas except ImportError: # pragma: no cover pandas = None # pragma: no cover logger = logging.getLogger(__name__) WARN = "warn" RAISE = "raise" def _field_existence( r: Type[Relation], data: Union["pyspark.sql.DataFrame", "pandas.DataFrame"] ): missing_fields = set() if is_pyspark_df(data, r): data: pyspark.sql.DataFrame = data for t_column in r.get_fields(): if t_column.name not in data.columns: missing_fields.add(t_column.name) elif is_pandas_df(data, r): data: pandas.DataFrame = data for t_column in r.get_fields(): if t_column.name not in data.columns: missing_fields.add(t_column.name) if len(missing_fields) > 0: raise ValueError( f"Field(s) '{", ".join(missing_fields)}' not part of loaded Relation '{r.name()}'" ) logger.info(f"Relation {r.name()} has passed the field existance check.") def _field_types( r: Type[Relation], data: Union["pyspark.sql.DataFrame", "pandas.DataFrame"] ): if is_pyspark_df(data, r): data: pyspark.sql.DataFrame = data for t_column in r.get_fields(): if t_column.name in data.columns: if t_column.datatype is not None: for spark_name, spark_type in data.dtypes: if spark_name == t_column.name and not ( (t_column.datatype == spark_type) or ( inspect.isclass(t_column.datatype) and issubclass( t_column.datatype, pyspark.sql.types.DataType ) and t_column.datatype().simpleString() == spark_type ) ): raise ValueError( f"Type error for '{r.name()}.{t_column.name}': " f"got: {spark_type}, expected: {t_column.datatype}" ) elif is_pandas_df(data, r): data: pandas.DataFrame = data for t_column in r.get_fields(): if t_column.name in data.columns: if t_column.datatype is not None: if ( t_column.name not in data.select_dtypes(include=t_column.datatype).columns ): raise ValueError( f"Type error for '{r.name()}.{t_column.name}': " f"got: {data[t_column].dtype}, expected: {t_column.datatype}" ) logger.info(f"Relation {r.name()} has passed the field datatype check.") def _keys(r: Type[Relation], data: Union["pyspark.sql.DataFrame", "pandas.DataFrame"]): if is_pyspark_df(data, r): from pyspark.sql.functions import column, count duplicated_rows = ( data.groupby(r.get_key_field_names()) .agg(count("*").alias("count")) .filter(column("count") > 1) .count() ) if duplicated_rows > 0: raise ValueError( f"Key error for '{r.name()}': " f"using keys '{r.get_key_field_names()}'" f" there are {duplicated_rows} duplicates." ) elif is_pandas_df(data, r): duplicated = data[r.get_key_field_names()].duplicated() duplicated_rows = len(data[duplicated]) if duplicated_rows > 0: raise ValueError( f"Key error for '{r.name()}': " f"using keys '{r.get_key_field_names()}'" f" there are {duplicated_rows} duplicates." ) logger.info(f"Relation {r.name()} has passed the key unqiue-ness check.") @doublewrap def fields(__original_func=None, *, on_fail: str = RAISE): """ Check fields on a blizz Relation for existance. """ _verify_args(on_fail) @functools.wraps(__original_func) def _decorated(*args, **kwargs): relation = _inspect.get_class_that_defined_method(__original_func) assert relation is not None res = __original_func(*args, **kwargs) _run_check_and_handle_outcome( _field_existence, r=relation, data=res, on_fail=on_fail ) return res return _decorated @doublewrap def types(__original_func=None, *, on_fail: str = RAISE): """ Check datatypes on a blizz Relation. """ _verify_args(on_fail) @functools.wraps(__original_func) def _decorated(*args, **kwargs): relation = _inspect.get_class_that_defined_method(__original_func) assert relation is not None res = __original_func(*args, **kwargs) _run_check_and_handle_outcome( _field_types, r=relation, data=res, on_fail=on_fail ) return res return _decorated @doublewrap def keys(__original_func=None, *, on_fail: str = RAISE): """ Check keys on a blizz Relation. """ _verify_args(on_fail) @functools.wraps(__original_func) def _decorated(*args, **kwargs): relation = _inspect.get_class_that_defined_method(__original_func) assert relation is not None res = __original_func(*args, **kwargs) _run_check_and_handle_outcome(_keys, r=relation, data=res, on_fail=on_fail) return res return _decorated @doublewrap def func( __original_func=None, *, function: Callable[ [Type[Relation], Union["pyspark.sql.DataFrame", "pandas.DataFrame"]], Union["pyspark.sql.DataFrame", "pandas.DataFrame"], ], on_fail: str = RAISE, ): """Run a user defined check function to a loaded Blizz relation.""" @functools.wraps(__original_func) def _decorated(*args, **kwargs): relation = _inspect.get_class_that_defined_method(__original_func) assert relation is not None res = __original_func(*args, **kwargs) _run_check_and_handle_outcome(function, r=relation, data=res, on_fail=on_fail) return res return _decorated def _run_check_and_handle_outcome( check: callable, r: Type[Relation], data, on_fail: str ) -> None: # skip any check, if data is None, e.g. if earlier blizz.check already has failed: if data is None: return None try: check(r, data) except Exception as error: if on_fail == RAISE: raise error if on_fail == WARN: warnings.warn(error.__repr__()) def _verify_args(on_fail: str) -> None: if on_fail not in [RAISE, WARN]: raise ValueError( f"Invalid argument for 'on_fail':{on_fail}. Allowed: {RAISE}, {WARN}" )
import functools import inspect import logging import warnings from typing import Union, Callable from blizz import _inspect from ._helpers import doublewrap from ._primitives import Relation, Type, is_pandas_df, is_pyspark_df try: import pyspark except ImportError: # pragma: no cover pyspark = None # pragma: no cover try: import pandas except ImportError: # pragma: no cover pandas = None # pragma: no cover logger = logging.getLogger(__name__) WARN = "warn" RAISE = "raise" def _field_existence( r: Type[Relation], data: Union["pyspark.sql.DataFrame", "pandas.DataFrame"] ): missing_fields = set() if is_pyspark_df(data, r): data: pyspark.sql.DataFrame = data for t_column in r.get_fields(): if t_column.name not in data.columns: missing_fields.add(t_column.name) elif is_pandas_df(data, r): data: pandas.DataFrame = data for t_column in r.get_fields(): if t_column.name not in data.columns: missing_fields.add(t_column.name) if len(missing_fields) > 0: raise ValueError( f"Field(s) '{', '.join(missing_fields)}' not part of loaded Relation '{r.name()}'" ) logger.info(f"Relation {r.name()} has passed the field existance check.") def _field_types( r: Type[Relation], data: Union["pyspark.sql.DataFrame", "pandas.DataFrame"] ): if is_pyspark_df(data, r): data: pyspark.sql.DataFrame = data for t_column in r.get_fields(): if t_column.name in data.columns: if t_column.datatype is not None: for spark_name, spark_type in data.dtypes: if spark_name == t_column.name and not ( (t_column.datatype == spark_type) or ( inspect.isclass(t_column.datatype) and issubclass( t_column.datatype, pyspark.sql.types.DataType ) and t_column.datatype().simpleString() == spark_type ) ): raise ValueError( f"Type error for '{r.name()}.{t_column.name}': " f"got: {spark_type}, expected: {t_column.datatype}" ) elif is_pandas_df(data, r): data: pandas.DataFrame = data for t_column in r.get_fields(): if t_column.name in data.columns: if t_column.datatype is not None: if ( t_column.name not in data.select_dtypes(include=t_column.datatype).columns ): raise ValueError( f"Type error for '{r.name()}.{t_column.name}': " f"got: {data[t_column].dtype}, expected: {t_column.datatype}" ) logger.info(f"Relation {r.name()} has passed the field datatype check.") def _keys(r: Type[Relation], data: Union["pyspark.sql.DataFrame", "pandas.DataFrame"]): if is_pyspark_df(data, r): from pyspark.sql.functions import column, count duplicated_rows = ( data.groupby(r.get_key_field_names()) .agg(count("*").alias("count")) .filter(column("count") > 1) .count() ) if duplicated_rows > 0: raise ValueError( f"Key error for '{r.name()}': " f"using keys '{r.get_key_field_names()}'" f" there are {duplicated_rows} duplicates." ) elif is_pandas_df(data, r): duplicated = data[r.get_key_field_names()].duplicated() duplicated_rows = len(data[duplicated]) if duplicated_rows > 0: raise ValueError( f"Key error for '{r.name()}': " f"using keys '{r.get_key_field_names()}'" f" there are {duplicated_rows} duplicates." ) logger.info(f"Relation {r.name()} has passed the key unqiue-ness check.") @doublewrap def fields(__original_func=None, *, on_fail: str = RAISE): """ Check fields on a blizz Relation for existance. """ _verify_args(on_fail) @functools.wraps(__original_func) def _decorated(*args, **kwargs): relation = _inspect.get_class_that_defined_method(__original_func) assert relation is not None res = __original_func(*args, **kwargs) _run_check_and_handle_outcome( _field_existence, r=relation, data=res, on_fail=on_fail ) return res return _decorated @doublewrap def types(__original_func=None, *, on_fail: str = RAISE): """ Check datatypes on a blizz Relation. """ _verify_args(on_fail) @functools.wraps(__original_func) def _decorated(*args, **kwargs): relation = _inspect.get_class_that_defined_method(__original_func) assert relation is not None res = __original_func(*args, **kwargs) _run_check_and_handle_outcome( _field_types, r=relation, data=res, on_fail=on_fail ) return res return _decorated @doublewrap def keys(__original_func=None, *, on_fail: str = RAISE): """ Check keys on a blizz Relation. """ _verify_args(on_fail) @functools.wraps(__original_func) def _decorated(*args, **kwargs): relation = _inspect.get_class_that_defined_method(__original_func) assert relation is not None res = __original_func(*args, **kwargs) _run_check_and_handle_outcome(_keys, r=relation, data=res, on_fail=on_fail) return res return _decorated @doublewrap def func( __original_func=None, *, function: Callable[ [Type[Relation], Union["pyspark.sql.DataFrame", "pandas.DataFrame"]], Union["pyspark.sql.DataFrame", "pandas.DataFrame"], ], on_fail: str = RAISE, ): """Run a user defined check function to a loaded Blizz relation.""" @functools.wraps(__original_func) def _decorated(*args, **kwargs): relation = _inspect.get_class_that_defined_method(__original_func) assert relation is not None res = __original_func(*args, **kwargs) _run_check_and_handle_outcome(function, r=relation, data=res, on_fail=on_fail) return res return _decorated def _run_check_and_handle_outcome( check: callable, r: Type[Relation], data, on_fail: str ) -> None: # skip any check, if data is None, e.g. if earlier blizz.check already has failed: if data is None: return None try: check(r, data) except Exception as error: if on_fail == RAISE: raise error if on_fail == WARN: warnings.warn(error.__repr__()) def _verify_args(on_fail: str) -> None: if on_fail not in [RAISE, WARN]: raise ValueError( f"Invalid argument for 'on_fail':{on_fail}. Allowed: {RAISE}, {WARN}" )
import numpy as np from suzieq.poller.services.service import Service from ipaddress import ip_address, IPv4Interface class OspfIfService(Service): """OSPF Interface service. Output needs to be munged""" def _clean_linux_data(self, processed_data, raw_data): for entry in processed_data: entry["vrf"] = "default" entry["networkType"] = entry["networkType"].lower() if entry['networkType'] == 'pointopoint': entry['networkType'] = 'p2p' entry["passive"] = entry["passive"] == "Passive" entry["isUnnumbered"] = entry["isUnnumbered"] == "UNNUMBERED" return processed_data def _clean_cumulus_data(self, processed_data, raw_data): return self._clean_linux_data(processed_data, raw_data) def _clean_sonic_data(self, processed_data, raw_data): return self._clean_linux_data(processed_data, raw_data) def _clean_eos_data(self, processed_data, raw_data): vrf_loip = {} vrf_rtrid = {} drop_indices = [] for i, entry in enumerate(processed_data): if '_entryType' in entry: # Retrieve the VRF and routerID vrf_rtrid[entry.get('vrf', 'default')] = \ entry.get('routerId', '') drop_indices.append(i) continue if not entry.get('ifname', ''): drop_indices.append(i) continue vrf = entry.get('vrf', '') if entry['ifname'].startswith("Loopback"): if vrf not in vrf_loip or not vrf_loip[vrf]: vrf_loip[vrf] = entry.get('ipAddress', '') if entry.get('passive', False): entry['bfdStatus'] = "invalid" entry["networkType"] = entry["networkType"].lower() entry["isUnnumbered"] = False if entry.get('state', '') in ['dr', 'p2p', 'backupDr']: entry['state'] = 'up' for i, entry in enumerate(processed_data): if entry.get('ipAddress', '') == vrf_loip.get( entry.get('vrf', ''), ''): if not entry.get('type', '') == "loopback": entry['isUnnumbered'] = True if entry['vrf'] in vrf_rtrid: entry['routerId'] = vrf_rtrid[entry['vrf']] processed_data = np.delete(processed_data, drop_indices).tolist() return processed_data def _clean_junos_data(self, processed_data, raw_data): drop_indices = [] for i, entry in enumerate(processed_data): if entry['_entryType'] == 'overview': routerId = entry['routerId'] continue if not entry.get('ifname', ''): drop_indices.append(i) continue entry['routerId'] = routerId # Is this right? Don't have a down interface example entry['state'] = 'up' entry['passive'] = entry['passive'] == "Passive" if entry['networkType'] == "LAN": entry['networkType'] = "broadcast" entry['stub'] = not entry['stub'] == 'Not Stub' entry['ipAddress'] = IPv4Interface( f'{entry['ipAddress']}/{entry['maskLen']}').with_prefixlen entry['maskLen'] = int(entry['ipAddress'].split('/')[1]) entry['vrf'] = 'default' # Juniper doesn't provide this info entry['authType'] = entry['authType'].lower() entry['networkType'] = entry['networkType'].lower() # Skip the original record as we don't need the overview record processed_data = np.delete(processed_data, drop_indices).tolist() return processed_data[1:] def _clean_nxos_data(self, processed_data, raw_data): areas = {} # Need to come back to fixup entries drop_indices = [] for i, entry in enumerate(processed_data): if not entry.get('ifname', ''): drop_indices.append(i) continue if entry['_entryType'] == 'interfaces': entry["networkType"] = entry["networkType"].lower() if entry['ifname'].startswith('loopback'): entry['passive'] = True entry['ipAddress'] = \ f"{entry["ipAddress"]}/{entry["maskLen"]}" if entry['area'] not in areas: areas[entry['area']] = [] if entry.get('_adminState', '') == "down": entry['state'] = "adminDown" areas[entry['area']].append(entry) else: # ifname is really the area name if not entry.get('ifname', []): drop_indices.append(i) continue for j, area in enumerate(entry['ifname']): for ifentry in areas.get(area, []): ifentry['routerId'] = entry['routerId'] ifentry['authType'] = entry['authType'][j] ifentry['isBackbone'] = area == "0.0.0.0" drop_indices.append(i) processed_data = np.delete(processed_data, drop_indices).tolist() return processed_data def _clean_ios_data(self, processed_data, raw_data): drop_indices = [] for i, entry in enumerate(processed_data): if not entry.get('ifname', ''): drop_indices.append(i) continue area = entry.get('area', '') if area and area.isdecimal(): entry['area'] = str(ip_address(int(area))) entry["networkType"] = entry["networkType"].lower() entry["passive"] = entry["passive"] == "stub" entry["isUnnumbered"] = entry["isUnnumbered"] == "yes" entry['areaStub'] = entry['areaStub'] == "yes" entry['helloTime'] = int( entry['helloTime']) if entry['helloTime'] else 10 # def value entry['deadTime'] = int( entry['deadTime']) if entry['deadTime'] else 40 # def value entry['retxTime'] = int( entry['retxTime']) if entry['retxTime'] else 5 # def value entry['vrf'] = 'default' # IOS doesn't provide this info entry['authType'] = entry.get('authType', '').lower() entry['nbrCount'] = int( entry['nbrCount']) if entry['nbrCount'] else 0 entry['noSummary'] = entry.get('noSummary', False) if entry['state'] == "administratively down": entry['state'] = "down" else: entry['state'] = entry['state'].lower() processed_data = np.delete(processed_data, drop_indices).tolist() return processed_data def _clean_iosxe_data(self, processed_data, raw_data): return self._clean_ios_data(processed_data, raw_data)
import numpy as np from suzieq.poller.services.service import Service from ipaddress import ip_address, IPv4Interface class OspfIfService(Service): """OSPF Interface service. Output needs to be munged""" def _clean_linux_data(self, processed_data, raw_data): for entry in processed_data: entry["vrf"] = "default" entry["networkType"] = entry["networkType"].lower() if entry['networkType'] == 'pointopoint': entry['networkType'] = 'p2p' entry["passive"] = entry["passive"] == "Passive" entry["isUnnumbered"] = entry["isUnnumbered"] == "UNNUMBERED" return processed_data def _clean_cumulus_data(self, processed_data, raw_data): return self._clean_linux_data(processed_data, raw_data) def _clean_sonic_data(self, processed_data, raw_data): return self._clean_linux_data(processed_data, raw_data) def _clean_eos_data(self, processed_data, raw_data): vrf_loip = {} vrf_rtrid = {} drop_indices = [] for i, entry in enumerate(processed_data): if '_entryType' in entry: # Retrieve the VRF and routerID vrf_rtrid[entry.get('vrf', 'default')] = \ entry.get('routerId', '') drop_indices.append(i) continue if not entry.get('ifname', ''): drop_indices.append(i) continue vrf = entry.get('vrf', '') if entry['ifname'].startswith("Loopback"): if vrf not in vrf_loip or not vrf_loip[vrf]: vrf_loip[vrf] = entry.get('ipAddress', '') if entry.get('passive', False): entry['bfdStatus'] = "invalid" entry["networkType"] = entry["networkType"].lower() entry["isUnnumbered"] = False if entry.get('state', '') in ['dr', 'p2p', 'backupDr']: entry['state'] = 'up' for i, entry in enumerate(processed_data): if entry.get('ipAddress', '') == vrf_loip.get( entry.get('vrf', ''), ''): if not entry.get('type', '') == "loopback": entry['isUnnumbered'] = True if entry['vrf'] in vrf_rtrid: entry['routerId'] = vrf_rtrid[entry['vrf']] processed_data = np.delete(processed_data, drop_indices).tolist() return processed_data def _clean_junos_data(self, processed_data, raw_data): drop_indices = [] for i, entry in enumerate(processed_data): if entry['_entryType'] == 'overview': routerId = entry['routerId'] continue if not entry.get('ifname', ''): drop_indices.append(i) continue entry['routerId'] = routerId # Is this right? Don't have a down interface example entry['state'] = 'up' entry['passive'] = entry['passive'] == "Passive" if entry['networkType'] == "LAN": entry['networkType'] = "broadcast" entry['stub'] = not entry['stub'] == 'Not Stub' entry['ipAddress'] = IPv4Interface( f'{entry["ipAddress"]}/{entry["maskLen"]}').with_prefixlen entry['maskLen'] = int(entry['ipAddress'].split('/')[1]) entry['vrf'] = 'default' # Juniper doesn't provide this info entry['authType'] = entry['authType'].lower() entry['networkType'] = entry['networkType'].lower() # Skip the original record as we don't need the overview record processed_data = np.delete(processed_data, drop_indices).tolist() return processed_data[1:] def _clean_nxos_data(self, processed_data, raw_data): areas = {} # Need to come back to fixup entries drop_indices = [] for i, entry in enumerate(processed_data): if not entry.get('ifname', ''): drop_indices.append(i) continue if entry['_entryType'] == 'interfaces': entry["networkType"] = entry["networkType"].lower() if entry['ifname'].startswith('loopback'): entry['passive'] = True entry['ipAddress'] = \ f"{entry['ipAddress']}/{entry['maskLen']}" if entry['area'] not in areas: areas[entry['area']] = [] if entry.get('_adminState', '') == "down": entry['state'] = "adminDown" areas[entry['area']].append(entry) else: # ifname is really the area name if not entry.get('ifname', []): drop_indices.append(i) continue for j, area in enumerate(entry['ifname']): for ifentry in areas.get(area, []): ifentry['routerId'] = entry['routerId'] ifentry['authType'] = entry['authType'][j] ifentry['isBackbone'] = area == "0.0.0.0" drop_indices.append(i) processed_data = np.delete(processed_data, drop_indices).tolist() return processed_data def _clean_ios_data(self, processed_data, raw_data): drop_indices = [] for i, entry in enumerate(processed_data): if not entry.get('ifname', ''): drop_indices.append(i) continue area = entry.get('area', '') if area and area.isdecimal(): entry['area'] = str(ip_address(int(area))) entry["networkType"] = entry["networkType"].lower() entry["passive"] = entry["passive"] == "stub" entry["isUnnumbered"] = entry["isUnnumbered"] == "yes" entry['areaStub'] = entry['areaStub'] == "yes" entry['helloTime'] = int( entry['helloTime']) if entry['helloTime'] else 10 # def value entry['deadTime'] = int( entry['deadTime']) if entry['deadTime'] else 40 # def value entry['retxTime'] = int( entry['retxTime']) if entry['retxTime'] else 5 # def value entry['vrf'] = 'default' # IOS doesn't provide this info entry['authType'] = entry.get('authType', '').lower() entry['nbrCount'] = int( entry['nbrCount']) if entry['nbrCount'] else 0 entry['noSummary'] = entry.get('noSummary', False) if entry['state'] == "administratively down": entry['state'] = "down" else: entry['state'] = entry['state'].lower() processed_data = np.delete(processed_data, drop_indices).tolist() return processed_data def _clean_iosxe_data(self, processed_data, raw_data): return self._clean_ios_data(processed_data, raw_data)
import torch import random import torchaudio from pathlib import Path from torch import Tensor from torchaudio import transforms as T from torch.nn import functional as F from torch.utils.data import Dataset, DataLoader from typing import Tuple from .transforms import mixup_augment class FSDKaggle2018(Dataset): CLASSES = ["Acoustic_guitar", "Applause", "Bark", "Bass_drum", "Burping_or_eructation", "Bus", "Cello", "Chime", "Clarinet", "Computer_keyboard", "Cough", "Cowbell", "Double_bass", "Drawer_open_or_close", "Electric_piano", "Fart", "Finger_snapping", "Fireworks", "Flute", "Glockenspiel", "Gong", "Gunshot_or_gunfire", "Harmonica", "Hi-hat", "Keys_jangling", "Knock", "Laughter", "Meow", "Microwave_oven", "Oboe", "Saxophone", "Scissors", "Shatter", "Snare_drum", "Squeak", "Tambourine", "Tearing", "Telephone", "Trumpet", "Violin_or_fiddle", "Writing"] def __init__(self, split, data_cfg, mixup_cfg=None, transform=None, spec_transform=None) -> None: super().__init__() assert split in ['train', 'val'] split = 'train' if split == 'train' else 'test' self.num_classes = len(self.CLASSES) self.transform = transform self.spec_transform = spec_transform self.mixup = mixup_cfg['MIXUP'] if mixup_cfg is not None else 0.0 self.mixup_alpha = mixup_cfg['MIXUP_ALPHA'] if mixup_cfg is not None else 0.0 self.label_smooth = mixup_cfg['SMOOTHING'] if mixup_cfg is not None else 0.0 self.num_frames = data_cfg['SAMPLE_RATE'] * data_cfg['AUDIO_LENGTH'] self.mel_tf = T.MelSpectrogram(data_cfg['SAMPLE_RATE'], data_cfg['WIN_LENGTH'], data_cfg['WIN_LENGTH'], data_cfg['HOP_LENGTH'], data_cfg['FMIN'], data_cfg['FMAX'], n_mels=data_cfg['N_MELS'], norm='slaney') # using mel_scale='slaney' is better self.resample = T.Resample(data_cfg['SOURCE_SAMPLE'], data_cfg['SAMPLE_RATE']) self.data, self.targets = self.get_data(data_cfg['ROOT'], split) print(f"Found {len(self.data)} {split} audios in {data_cfg["ROOT"]}.") def get_data(self, root: str, split: str): root = Path(root) csv_path = 'train_post_competition.csv' if split == 'train' else 'test_post_competition_scoring_clips.csv' files, targets = [], [] with open(root / 'FSDKaggle2018.meta' / csv_path) as f: lines = f.read().splitlines()[1:] for line in lines: fname, label, *_ = line.split(',') files.append(str(root / f"audio_{split}" / fname)) targets.append(int(self.CLASSES.index(label))) return files, targets def __len__(self) -> int: return len(self.data) def cut_pad(self, audio: Tensor) -> Tensor: if audio.shape[1] < self.num_frames: # if less than 5s, pad the audio audio = torch.cat([audio, torch.zeros(1, self.num_frames-audio.shape[1])], dim=-1) else: # if not, trim the audio to 5s audio = audio[:, :self.num_frames] return audio def __getitem__(self, index: int) -> Tuple[Tensor, Tensor]: audio, _ = torchaudio.load(self.data[index]) audio = self.resample(audio) # resample to 32kHz audio = self.cut_pad(audio) target = torch.tensor(self.targets[index]) if self.transform: audio = self.transform(audio) if random.random() < self.mixup: next_index = random.randint(0, len(self.data)-1) next_audio, _ = torchaudio.load(self.data[next_index]) next_audio = self.resample(next_audio) next_audio = self.cut_pad(next_audio) next_target = torch.tensor(self.targets[next_index]) audio, target = mixup_augment(audio, target, next_audio, next_target, self.mixup_alpha, self.num_classes, self.label_smooth) else: target = F.one_hot(target, self.num_classes).float() audio = self.mel_tf(audio) # convert to mel spectrogram audio = 10.0 * audio.clamp_(1e-10).log10() # convert to log mel spectrogram if self.spec_transform: audio = self.spec_transform(audio) return audio, target if __name__ == '__main__': data_cfg = { 'ROOT': 'C:/Users/sithu/Documents/Datasets/FSDKaggle2018', 'SOURCE_SAMPLE': 44100, 'SAMPLE_RATE': 32000, 'AUDIO_LENGTH': 5, 'WIN_LENGTH': 1024, 'HOP_LENGTH': 320, 'N_MELS': 64, 'FMIN': 50, 'FMAX': 14000 } aug_cfg = { 'MIXUP': 0.5, 'MIXUP_ALPHA': 10, 'SMOOTHING': 0.1 } dataset = FSDKaggle2018('val', data_cfg, aug_cfg) dataloader = DataLoader(dataset, 2, True) for audio, target in dataloader: print(audio.shape, target.argmax(dim=1)) print(audio.min(), audio.max()) break
import torch import random import torchaudio from pathlib import Path from torch import Tensor from torchaudio import transforms as T from torch.nn import functional as F from torch.utils.data import Dataset, DataLoader from typing import Tuple from .transforms import mixup_augment class FSDKaggle2018(Dataset): CLASSES = ["Acoustic_guitar", "Applause", "Bark", "Bass_drum", "Burping_or_eructation", "Bus", "Cello", "Chime", "Clarinet", "Computer_keyboard", "Cough", "Cowbell", "Double_bass", "Drawer_open_or_close", "Electric_piano", "Fart", "Finger_snapping", "Fireworks", "Flute", "Glockenspiel", "Gong", "Gunshot_or_gunfire", "Harmonica", "Hi-hat", "Keys_jangling", "Knock", "Laughter", "Meow", "Microwave_oven", "Oboe", "Saxophone", "Scissors", "Shatter", "Snare_drum", "Squeak", "Tambourine", "Tearing", "Telephone", "Trumpet", "Violin_or_fiddle", "Writing"] def __init__(self, split, data_cfg, mixup_cfg=None, transform=None, spec_transform=None) -> None: super().__init__() assert split in ['train', 'val'] split = 'train' if split == 'train' else 'test' self.num_classes = len(self.CLASSES) self.transform = transform self.spec_transform = spec_transform self.mixup = mixup_cfg['MIXUP'] if mixup_cfg is not None else 0.0 self.mixup_alpha = mixup_cfg['MIXUP_ALPHA'] if mixup_cfg is not None else 0.0 self.label_smooth = mixup_cfg['SMOOTHING'] if mixup_cfg is not None else 0.0 self.num_frames = data_cfg['SAMPLE_RATE'] * data_cfg['AUDIO_LENGTH'] self.mel_tf = T.MelSpectrogram(data_cfg['SAMPLE_RATE'], data_cfg['WIN_LENGTH'], data_cfg['WIN_LENGTH'], data_cfg['HOP_LENGTH'], data_cfg['FMIN'], data_cfg['FMAX'], n_mels=data_cfg['N_MELS'], norm='slaney') # using mel_scale='slaney' is better self.resample = T.Resample(data_cfg['SOURCE_SAMPLE'], data_cfg['SAMPLE_RATE']) self.data, self.targets = self.get_data(data_cfg['ROOT'], split) print(f"Found {len(self.data)} {split} audios in {data_cfg['ROOT']}.") def get_data(self, root: str, split: str): root = Path(root) csv_path = 'train_post_competition.csv' if split == 'train' else 'test_post_competition_scoring_clips.csv' files, targets = [], [] with open(root / 'FSDKaggle2018.meta' / csv_path) as f: lines = f.read().splitlines()[1:] for line in lines: fname, label, *_ = line.split(',') files.append(str(root / f"audio_{split}" / fname)) targets.append(int(self.CLASSES.index(label))) return files, targets def __len__(self) -> int: return len(self.data) def cut_pad(self, audio: Tensor) -> Tensor: if audio.shape[1] < self.num_frames: # if less than 5s, pad the audio audio = torch.cat([audio, torch.zeros(1, self.num_frames-audio.shape[1])], dim=-1) else: # if not, trim the audio to 5s audio = audio[:, :self.num_frames] return audio def __getitem__(self, index: int) -> Tuple[Tensor, Tensor]: audio, _ = torchaudio.load(self.data[index]) audio = self.resample(audio) # resample to 32kHz audio = self.cut_pad(audio) target = torch.tensor(self.targets[index]) if self.transform: audio = self.transform(audio) if random.random() < self.mixup: next_index = random.randint(0, len(self.data)-1) next_audio, _ = torchaudio.load(self.data[next_index]) next_audio = self.resample(next_audio) next_audio = self.cut_pad(next_audio) next_target = torch.tensor(self.targets[next_index]) audio, target = mixup_augment(audio, target, next_audio, next_target, self.mixup_alpha, self.num_classes, self.label_smooth) else: target = F.one_hot(target, self.num_classes).float() audio = self.mel_tf(audio) # convert to mel spectrogram audio = 10.0 * audio.clamp_(1e-10).log10() # convert to log mel spectrogram if self.spec_transform: audio = self.spec_transform(audio) return audio, target if __name__ == '__main__': data_cfg = { 'ROOT': 'C:/Users/sithu/Documents/Datasets/FSDKaggle2018', 'SOURCE_SAMPLE': 44100, 'SAMPLE_RATE': 32000, 'AUDIO_LENGTH': 5, 'WIN_LENGTH': 1024, 'HOP_LENGTH': 320, 'N_MELS': 64, 'FMIN': 50, 'FMAX': 14000 } aug_cfg = { 'MIXUP': 0.5, 'MIXUP_ALPHA': 10, 'SMOOTHING': 0.1 } dataset = FSDKaggle2018('val', data_cfg, aug_cfg) dataloader = DataLoader(dataset, 2, True) for audio, target in dataloader: print(audio.shape, target.argmax(dim=1)) print(audio.min(), audio.max()) break
# AUTOGENERATED! DO NOT EDIT! File to edit: Widgets.ipynb (unless otherwise specified). __all__ = ['css_style', 'dark_colors', 'light_colors', 'simple_colors', 'default_colors', 'get_files_gui', 'InputGui', 'generate_summary', 'VasprunApp', 'KPathApp'] # Cell import os, textwrap import json from time import sleep # Widgets Imports from IPython.display import display, Markdown from IPython import get_ipython #For SLides import ipywidgets as ipw from ipywidgets import Layout,Label,Button,Box,HBox,VBox,Dropdown,Text,Checkbox, SelectMultiple from ipywidgets.embed import embed_minimal_html, dependency_state # More exports import numpy as np import pandas as pd import plotly.graph_objects as go # Inside packages import to work both with package and jupyter notebook. try: from pivotpy import g_utils as gu from pivotpy import vr_parser as vp from pivotpy import i_plots as ip from pivotpy import s_plots as sp from pivotpy import sio except: import pivotpy.g_utils as gu import pivotpy.vr_parser as vp import pivotpy.i_plots as ip import pivotpy.s_plots as sp import pivotpy.sio as sio # Cell def css_style(colors_dict,_class = 'main_wrapper'): """Return style based on colors_dict available as pp.light_colors, pp.dark_colors etc""" return """<style> .{_class} h1,h2,h3,h4,h5,h6 {{ color: {accent} !important; }} .{_class} .widget-label-basic {{ background-color: transparent !important; color: {main_fg} !important; }} .{_class} .widget-text input {{ background-color: {next_bg} !important; border-radius:20px !important; padding: 0px 10px 0px 10px !important; border: 1px solid {next_bg} !important; color: {main_fg} !important; }} .{_class} .widget-text input:focus {{ border: 1px solid {hover_bg} !important; }} .{_class} .widget-text input:hover {{ border: 1px solid {hover_bg} !important; }} .{_class} .widget-dropdown > select {{ background-color: {next_bg} !important; border:none !important; border-bottom: 1px solid {hover_bg} !important; box-shadow: inset 0 -20px 10px -20px {hover_bg}; color: {main_fg} !important; }} .{_class} .widget-dropdown > select:hover {{ background-color: {hover_bg} !important; }} .{_class} .widget-dropdown > select > option {{ color: {main_fg} !important; background-color: {next_bg} !important; }} .{_class} .widget-dropdown > select > option:focus {{ background-color: {hover_bg} !important; }} .{_class} .widget-label {{ color: {main_fg} !important; }} .{_class} .widget-html {{ color: {main_fg} !important; }} .{_class} .widget-box, .{_class}.widget-box {{ background-color: {main_bg} !important; border-radius:5px !important; padding:1px !important; border: 1px solid {next_bg} !important; box-shadow: 1px 1px 1px 1px {next_bg} !important; }} .{_class} .borderless, .{_class}.borderless {{ border: 1px solid transparent !important; box-shadow: none !important; border-radius: 4px !important; margin:4px !important; }} .{_class} .marginless, .{_class}.marginless {{ margin: 0px !important; border-radius: 0px !important; }} .{_class} .output, .{_class}.output {{ color: {main_fg} !important; background-color: inherit !important; }} .{_class} .widget-tab, .{_class}.widget-tab {{ background-color: {main_bg} !important; border: none !important; box-shadow: 1px 1px 1px 1px {next_bg} !important; padding: 0px 2px 2px 2px !important; }} .{_class} .widget-tab-contents, .{_class}.widget-tab > .widget-tab-contents {{ width: 100%; box-sizing: border-box; margin: 0px !important; padding: 0px !important; flex-grow: 1; overflow: auto; border: none !important; background-color: {main_bg} !important; }} .{_class} .widget-tab > .p-TabBar .p-TabBar-tab, .{_class}.widget-tab > .p-TabBar .p-TabBar-tab {{ background-color:{main_bg} !important; border: none !important; color: {accent} !important; font-weight: bold !important; font-size: 16px !important; font-family: "Times","serif" !important; text-align: center !important; }} .{_class} table {{ color: {main_fg} !important; }} .{_class} tr:nth-child(odd) {{ background-color: {next_bg} !important; }} .{_class} tr:nth-child(even) {{ background-color: {main_bg} !important; }} .{_class} .widget-button,.widget-toggle-button {{ color: {accent} !important; min-width: max-content !important; background-color: {next_bg}; border-radius: 5px !important; }} .{_class} tr:hover {{ background-color: {hover_bg} !important; }} </style> """.format(**colors_dict,_class= _class) dark_colors = { 'main_fg' : '#ABB2BF', 'main_bg' : '#21252B', 'next_bg' : '#282C34', 'hover_bg' : '#414855', 'accent' : '#61AFEF' } light_colors = { 'next_bg' : 'white', 'hover_bg' : '#abe4ff', 'accent' : 'navy', 'main_bg' : '#F3F3F3', 'main_fg' : 'black' } simple_colors = { 'hover_bg' : 'lightgray', 'accent' : 'black', 'main_bg' : 'white', 'main_fg' : 'black', 'next_bg' : 'whitesmoke' } default_colors = { # Adopt Jupyterlab theme 'main_fg' : 'var(--jp-inverse-layout-color0,black)', 'main_bg' : 'var(--jp-layout-color0,#F3F3F3)', 'next_bg' : 'var(--jp-layout-color2,white)', 'hover_bg': 'var(--jp-border-color1,lightblue)', 'accent' : 'var(--jp-brand-color2,navy)' } # Cell def get_files_gui(auto_fill = 'vasprun.xml', theme_colors = None, height=320): """ - Creates a GUI interface for files/folders filtering. - **Parmeters** - auto_fill : Default is `vasprun.xml`, any file/folder. - theme_colors : None,Any of pivotpy.[dark,light,simple]_colors. - height : Height of Grid box. - **Returns** - Tuple(GUI_gridbox,Files_Dropdown). Access second one by item itself. """ files_w = ipw.Dropdown(continuous_update=False) pw = ipw.Text(value=os.getcwd()) incldue_w = ipw.Text(value=auto_fill) excldue_w = ipw.Text() d_layout = Layout(width='30%') l_layout = Layout(width='19%') depth_w = ipw.Dropdown(options=[None,1,2,3,4,5],value=4,layout=d_layout) item_w = ipw.Dropdown(options=['Both','Files','Folders'],value='Files',layout=d_layout) item_box = ipw.HBox([ipw.Label('Depth: ',layout=l_layout),depth_w,ipw.Label('Type: ',layout=l_layout),item_w]) item_box.add_class('borderless').add_class('marginless') applybtn_w = ipw.Button(description='Apply Filters') gci_output = ipw.Output(layout=Layout(height='{}px'.format(height-70))) label_head = ipw.HTML("<h3>Your Filtered Files List</h3>") def filter_gci(applybtn_w): applybtn_w.description = 'Applying...' applybtn_w.disabled = True if os.path.isdir(pw.value): path = pw.value else: with gci_output: print("Given path does not exists.") print("Falling back to PWD: {}".format(os.getcwd())) path = os.getcwd() pw.value = path gci = vp.Dict2Data({'children':[],'parent':path}) if 'Files' in item_w.value: file_type = dict(filesOnly=True) elif 'Folders' in item_w.value: file_type = dict(dirsOnly=True) else: file_type = {} try: gci = gu.get_child_items(path=path, **file_type, include= incldue_w.value, exclude= excldue_w.value, depth=depth_w.value) except: with gci_output: print('Something went wrong') # Enable before any error occur. applybtn_w.disabled = False files_w.options = [(name, os.path.join(gci.parent,name)) for name in gci.children] applybtn_w.description = 'Successful!' label_head.value = "<h3>From: {}</h3>".format(gci.parent) with gci_output: display(ipw.HTML("<h4>{} files found.</h4>".format(len(gci.children)))) display(ipw.HTML("<ol>{}<ol>".format(''.join(['<li>{}</li>'.format(i) for i in gci.children])))) applybtn_w.description = 'Apply Filters' gci_output.clear_output(wait=True) applybtn_w.on_click(filter_gci) out_box = ipw.Box([gci_output]) right_box = ipw.VBox([label_head,out_box]) out_box.add_class('borderless') right_box.add_class('borderless') i_layout = Layout(width='99%') incldue_w.layout = i_layout excldue_w.layout = i_layout pw.layout = i_layout input_box = ipw.VBox([ ipw.Label('Path to Project Folder',layout=i_layout),pw, ipw.Label('Items to Include (separate by |)',layout=i_layout),incldue_w, ipw.Label('Items to Exclude (separate by |)',layout=i_layout),excldue_w, item_box, applybtn_w],layout=Layout(width='330px')) _class = 'custom-'+''.join(np.random.randint(9,size=(23,)).astype(str)) #Random class html_style = css_style(theme_colors,_class = _class) if theme_colors else '' full_box = ipw.HBox([ipw.HTML(html_style),input_box, right_box], layout=Layout(height='{}px'.format(height))).add_class(_class) full_box.add_class('borderless').add_class('marginless') return full_box, files_w # Cell class InputGui: def __init__(self,sys_info=None,theme_colors = None,height=400): """ - Creates a GUI interface for input/selection of orbitals/elms projection. - **Parmeters** - theme_colors : None,Any of pivotpy.[dark,light,simple]_colors. - height : Height of Grid box, Can set to None for auto-resizing. - sys_info : `export_vasprun().sys_info`. Can change later using `self.update_options` mthod. - **Output Parameters** - output: Dictionary that contains kwargs for plot functions. - html : A widget which can be used to bserve change in output, used in `VasprunApp`. """ self.sys_info = sys_info if sys_info else vp.Dict2Data({'fields':['s'], 'ElemIndex':[0,1],'ElemName':['A']}) self.output = dict(elements = [[],[],[]],orbs = [[],[],[]],labels = ['','','']) layout = Layout(width='30%') l_width = Layout(width='20%') self.html = ipw.HTML() # For Display in Big App as well. Very important self.dds = { 'elms': Dropdown(layout=layout), 'orbs': Dropdown(layout=layout), 'rgb' : Dropdown(options=[('Red',0),('Green',1),('Blue',2)],value=0,layout=layout) } self.texts = { 'orbs' : Text(layout=layout,continuous_update=False), 'elms' : Text(layout=layout,continuous_update=False), 'label': Text(layout=layout,continuous_update=False) } self.update_options(self.sys_info) # In start if given _class = 'custom-'+''.join(np.random.randint(9,size=(23,)).astype(str)) #Random class html_style = css_style(theme_colors,_class = _class) if theme_colors else '' self.box = VBox([ipw.HTML(html_style), self.html, HBox([Label('Color: ',layout=l_width), self.dds['rgb'], Label('Label: ',layout=l_width),self.texts['label'] ]).add_class('borderless').add_class('marginless'), HBox([Label('Ions: ',layout=l_width),self.dds['elms'], Label('::>>:: ',layout=l_width),self.texts['elms'] ]).add_class('borderless').add_class('marginless'), HBox([Label('Orbs: ',layout=l_width),self.dds['orbs'], Label('::>>:: ',layout=l_width),self.texts['orbs'] ]).add_class('borderless').add_class('marginless') ],layout=Layout(height="{}px".format(height)) ).add_class(_class).add_class('marginless') #Obsever self.dds['rgb'].observe(self.__see_input,'value') self.texts['label'].observe(self.__read_pro,'value') self.texts['orbs'].observe(self.__read_pro,'value') self.texts['elms'].observe(self.__read_pro,'value') # Link ipw.dlink((self.dds['elms'],'value'),(self.texts['elms'],'value')) ipw.dlink((self.dds['orbs'],'value'),(self.texts['orbs'],'value')) def update_options(self,sys_info=None): if sys_info: orbs_opts = [(str(i)+': '+item,str(i)) for i,item in enumerate(sys_info.fields)] if len(sys_info.fields) == 9: orbs_opts = [*orbs_opts,('1-3: p','1-3'),('4-8: d','4-8')] if len(sys_info.fields) == 16: orbs_opts = [*orbs_opts,('9-15: f','9-15')] max_ind = len(sys_info.fields)-1 orbs_opts = [('0-{}: All'.format(max_ind), "0-{}".format(max_ind)),*orbs_opts] inds = sys_info.ElemIndex ions_opts = [("{}-{}: {}".format(inds[i],inds[i+1]-1,item),"{}-{}".format( inds[i],inds[i+1]-1)) for i,item in enumerate(sys_info.ElemName)] self.dds['elms'].options = [*ions_opts,('0-{}: All'.format(inds[-1]-1),'0-{}'.format(inds[-1]-1))] self.dds['orbs'].options = orbs_opts self.sys_info = sys_info # Update it as well. def __read_pro(self,btn): def read(cell_value): _out = [] for v in (cell_value.split(",") if cell_value else ''): if v and '-' in v: i, f = [int(k) for k in v.split("-")] _out = [*_out,*list(range(i,f+1))] elif v: _out = [*_out,int(v)] return _out index = self.dds['rgb'].value self.output['elements'][index] = read(self.texts['elms'].value) self.output['orbs'][index] = read(self.texts['orbs'].value) _text,_ion,_orb = self.texts['label'].value,self.texts['elms'].value,self.texts['orbs'].value self.output['labels'][index] = _text if _text else "{}:{}".format(_ion,_orb) self.html.value = """<div style='border: 2px solid {0}!important; background-color:{0} !important;'> </div> """.format(self.dds['rgb'].label.lower()) sleep(1) self.html.value = '' def __see_input(self,change): # Unobserve first to avoid overwriting self.texts['label'].unobserve(self.__read_pro,'value') self.texts['orbs'].unobserve(self.__read_pro,'value') self.texts['elms'].unobserve(self.__read_pro,'value') # Look up while not observing x = self.dds['rgb'].value self.texts['elms'].value = ','.join([str(i) for i in self.output['elements'][x]]) self.texts['orbs'].value = ','.join([str(i) for i in self.output['orbs'][x]]) self.texts['label'].value = self.output['labels'][x] # Observe Back Again self.texts['label'].observe(self.__read_pro,'value') self.texts['orbs'].observe(self.__read_pro,'value') self.texts['elms'].observe(self.__read_pro,'value') def show(self): return self.box # Cell #mouse event handler def _click_data(sel_en_w,fermi_w,data_dict,fig,bd_w): def handle_click(trace, points, state): if(points.ys!=[]): e_fermi = (float(fermi_w.value) if fermi_w.value else 0) v_clicked = points.ys[0] if bd_w.value=='Bands' else points.xs[0] val = np.round(float(v_clicked) + e_fermi,4) #exact value for key in sel_en_w.options: if key in sel_en_w.value and key != 'None': data_dict[key] = val # Assign value back if 'Fermi' in sel_en_w.value: fermi_w.value = str(val) # change fermi # Shift Graph for Fermi value if 'Fermi' in sel_en_w.value: with fig.batch_animate(): for trace in fig.data: # Shift graph as Fermi Changes if bd_w.value == 'Bands': trace.y = [y - data_dict['Fermi'] + e_fermi for y in trace.y] else: trace.x = [x - data_dict['Fermi'] + e_fermi for x in trace.x] # Update Fermi, SO etc if data_dict['VBM'] and data_dict['CBM']: data_dict['E_gap'] = np.round(data_dict['CBM'] - data_dict['VBM'], 4) if data_dict['so_max'] and data_dict['so_min']: data_dict['Δ_SO'] = np.round(data_dict['so_max'] - data_dict['so_min'], 4) # Cycle energy types on graph click and chnage table as well unless it is None. if sel_en_w.value == 'CBM': # Avoid accidental SO calculation sel_en_w.value = 'None' if sel_en_w.value != 'None': # Keep usually as None _this = sel_en_w.options.index(sel_en_w.value) _next = _this + 1 if _this < len(sel_en_w.options) - 1 else 0 sel_en_w.value = sel_en_w.options[_next] #To simulate as it changes for trace in fig.data: trace.on_click(handle_click) # Display Table def _tabulate_data(data_dict): new_dict = {k:v for k,v in data_dict.items() if v != '' and k not in ['sys','so_max','so_min','Fermi']} ls = list(new_dict.keys()) ds = list(new_dict.values()) if len(ls) % 2 != 0: ls.append('') ds.append('') tab_data = [ls[:int(len(ls)/2)],ds[:int(len(ls)/2)],ls[int(len(ls)/2):],ds[int(len(ls)/2):]] htm_string = """<style>table {border-collapse: collapse !important; min-width: 100% !important; margin: 1px 1px 1px 1px !important; font-size: small !important; font-family: "Times New Roman", "Times", "serif" !important;} th, td {text-align: center !important; padding: 0px 8px 0px 8px !important;} tr { width: 100% !important;} tr:nth-child(odd) {font-weight:bold !important;} </style>""" htm_string += "<table><tr>{}</tr></table>".format( '</tr><tr>'.join( '<td>{}</td>'.format('</td><td>'.join(str(_) for _ in row)) for row in tab_data) ) return htm_string # Send Data def _save_data(out_w1,data_dict): out_f = os.path.join(os.path.split(out_w1.value)[0],'result.json') vp.dump_dict(data_dict,dump_to='json',outfile=out_f) # Cell def _color_toggle(tog_w,fig,rd_btn): if tog_w.icon == 'toggle-off': tog_w.icon = 'toggle-on' with fig.batch_animate(): if rd_btn.value == 'DOS': for trace in fig.data: trace.fill='tozeroy' else: for trace in fig.data[:1]: trace.mode='markers+lines' trace.line.color='rgba(222,222,220,0.1)' else: tog_w.icon = 'toggle-off' with fig.batch_animate(): if rd_btn.value == 'DOS': for trace in fig.data: trace.fill=None else: for trace in fig.data[:1]: trace.mode='lines' trace.line.width=1.5 trace.line.color='skyblue' # Cell def generate_summary(paths_list=None): # Make Data Frame result_paths = [] common_prefix = '' #placeholder if paths_list: common_prefix = os.path.commonprefix(paths_list) for item in paths_list: if item and os.path.isdir(item): result_paths.append(os.path.join(item,'result.json')) elif item and os.path.isfile(item): result_paths.append(os.path.join(os.path.split(item)[0],'result.json')) result_dicts = [] for path in result_paths: try: _p_ = os.path.split(path)[0].split(common_prefix)[1] except: _p_ = '' #In current directory try: with open(path,'r') as f: l_d = json.load(f) l_d.update({'rel_path':_p_}) result_dicts.append(l_d) except: pass out_dict = {} # placeholder if result_dicts: out_dict.update({k:[v] if v!='' else [np.nan] for k,v in result_dicts[0].items()}) for i,d in enumerate(result_dicts): if i != 0: for k,v in d.items(): v = np.nan if v=='' else v try: out_dict[k].append(v) except: out_dict.update({k:[np.nan for l in range(i)]}) #if not key before, add to all previous out_dict[k].append(v) # Then append for current value # If next dictionary does not have key for k in out_dict.keys(): if k not in d.keys(): out_dict[k].append(np.nan) try: out_dict.pop('Fermi',None) # Remove Fermi as not necessary except: pass df = pd.DataFrame(out_dict) if common_prefix: return df.style.set_caption("Root Path: {}".format(common_prefix)) # return with header return df #return simple # Cell class VasprunApp: """ Display a GUI for vasp output analysis. `self.theme_colors` can be used to edit custom theme. - **Usage Example** ```python import pivotpy as pp va = pp.VasprunApp() va.cache_data = False #Turn off cache globally. va.evr_kws['elim'] = [-2,2] #Only Bands in this range will be included. Global accross project, can change anytime. va.evr_kws['try_pwsh'] = False #Defult is True. Tries to load Powershell exported data. va.ibands_kws['mode'] = 'bands' #Change graph mode from 'markers' to 'bands'. Setting it to 'lines' is not recommended in live graph, it could hang all UI. va.show() #Displays App and do work! va.theme_colors = pp.dark_colors #Set theme to dark externally and edit dictionary values to make your own theme va.splot(**kwargs) #Get matplotlib plot of current data. va.df #After you do some analysis and hit `Project Summary` button, get DataFrame. va.fig #Get current fig in Notebook cell. ``` """ output = ipw.Output().add_class('output') def __init__(self,height=580): self.height = height tab = ipw.Tab(layout = ipw.Layout(min_height=f'{height}px', max_height='100vh', min_width='700px', max_width='100vw') ).add_class('marginless').add_class('borderless') # Main Tab try: for i,item in enumerate(['Home','Graphs','STD(out/err)']): tab.set_title(i,item) except: tab.titles = ['Home','Graphs','STD(out/err)'] self.main_class = 'custom-'+''.join(np.random.randint(9,size=(22,)).astype(str)) #Random class self.tab = tab.add_class(self.main_class) # Main layout self.data = None # Export vasprun object. self.__path = None # current path self.fig = go.FigureWidget() # plotly's figure widget self.fig.update_layout(autosize=True) self.df = None # Summary DataFrame self.result = {'sys':'','V':'','a':'','b':'','c':'','Fermi': None, 'VBM':'','CBM':'','so_max':'','so_min':''} # Table widget value self.files_gui,self.files_dd = get_files_gui(height=300) self.InGui = InputGui(height=None) self.input = {'E_Fermi':0} # Dictionary for input self.fig_gui = HBox() # Middle Tab self.theme_colors = light_colors.copy() # Avoid Modification # Permeannet Parameters self.idos_kws = dict(colormap='RGB',tdos_color=(0.5, 0.95, 0),linewidth=2,fill_area=True, spin='both',interp_nk={},title=None) self.ibands_kws = dict(mode='markers',skipk=None,max_width=6,title=None,interp_nk={}) self.evr_kws = dict(skipk=None,elim=[],try_pwsh = True) self.cache_data = True l_btn = ipw.Layout(width='max-content') self.buttons = {'load_data' : Button(description='Load Data',layout=l_btn,tooltip='Load and Cache Data'), 'load_graph': Button(description='Load Graph',layout=l_btn,tooltip='Create Graph'), 'confirm' : Button(description='Confirm Delete',layout=l_btn,icon='trash'), 'summary' : Button(description='Project Summary',layout=l_btn,tootltip='Make DataFrame'), 'expand' : Button(icon = "fa-expand",layout=l_btn,tooltip='Expand Fig'), 'toggle' : Button(description='RGB',layout=l_btn,icon='toggle-on',tooltip='Toggle Colors'), 'save_fig' : Button(description='Save Fig',icon='download',layout=l_btn,tooltip='') } b_out = Layout(width='30%') en_options = ['Fermi','VBM','CBM','so_max','so_min','None'] self.dds = {'band_dos': Dropdown(options=['Bands','DOS'],value='Bands', layout= Layout(width='80px')), 'en_type' : Dropdown(options = en_options,value='None',layout=b_out), 'cache' : Dropdown(options=['Table Data','PWD Cache','All Cache','None'], value='None',layout=b_out), 'theme' : Dropdown(options=['Default','Light','Dark','Custom'], value='Default',layout=l_btn), 'style' : Dropdown(options=["plotly", "plotly_white", "plotly_dark", "ggplot2", "seaborn", "simple_white", "none"],layout=l_btn), } self.texts = {'kticks': Text(value='',layout=b_out,continuous_update=False), 'ktickv': Text(value='',layout=b_out,continuous_update=False), 'kjoin' : Text(value='',layout=b_out,continuous_update=False), 'elim' : Text(value='',layout=b_out,continuous_update=False), 'fermi' : Text(value='',layout=b_out,continuous_update=False), 'xyt' : Text(value='',continuous_update=False) } self.htmls = {'theme': ipw.HTML(css_style(light_colors,_class = self.main_class)), 'table': ipw.HTML()} # Observing self.InGui.html.observe(self.__update_input,"value") self.dds['band_dos'].observe(self.__update_input,"value") self.texts['fermi'].observe(self.__update_input,"value") self.texts['kjoin'].observe(self.__update_input,"value") self.texts['kticks'].observe(self.__update_xyt,"value") self.texts['ktickv'].observe(self.__update_xyt,"value") self.texts['elim'].observe(self.__update_xyt,"value") self.texts['xyt'].observe(self.__update_xyt) self.dds['theme'].observe(self.__update_theme,"value") self.dds['style'].observe(self.__update_plot_style,"value") self.files_dd.observe(self.__load_previous,"value") self.buttons['load_data'].on_click(self.__on_load) self.dds['band_dos'].observe(self.__figure_tab,"value") self.files_dd.observe(self.__update_table,'value') self.buttons['load_data'].observe(self.__update_table,'value') self.buttons['summary'].on_click(self.__df_out) self.buttons['confirm'].on_click(self.__deleter) self.buttons['toggle'].on_click(self.__tog_b) self.buttons['save_fig'].on_click(self.__save_connected) self.buttons['expand'].on_click(self.__expand_fig) self.buttons['load_graph'].on_click(self.__update_graph) self.dds['en_type'].observe(self.__update_table,"value") # This works from _click_data # Build Layout self.__build() def set_theme_colors(self,theme_colors): "Get self.theme_colors and after edit set back" if 'dds' in self.__dict__.keys(): self.dds['theme'].value = 'Custom' if 'htmls' in self.__dict__.keys(): self.htmls['theme'].value = css_style(theme_colors) def __figure_tab(self,change): l_out = Layout(width='20%') cache_box = HBox([Label('Delete Cache:'),self.dds['cache'],self.buttons['confirm']] ).add_class('marginless') upper_box = VBox([ HBox([Label('File:',layout=Layout(width='50px')),self.files_dd ]).add_class('borderless').add_class('marginless'), HBox([Label('View:',layout=Layout(width='50px')), self.dds['band_dos'],self.buttons['load_data'] ]).add_class('borderless').add_class('marginless') ]).add_class('marginless').add_class('borderless') points_box = HBox([Box([Label('E Type:',layout=l_out), self.dds['en_type'], Label('E-Fermi:',layout=l_out), self.texts['fermi'] ]).add_class('marginless').add_class('borderless'), self.buttons['load_graph'] ],layout=Layout(width='100%')).add_class('marginless') in_box = VBox([self.InGui.box, ]).add_class('marginless').add_class('borderless') top_right = HBox([self.buttons['load_graph'], Label('Style:'), self.dds['style'], Label('Theme:'), self.dds['theme'], self.buttons['expand'] ]).add_class('marginless') fig_box = Box([self.fig],layout=Layout(min_height='380px')).add_class('marginless') right_box = VBox([top_right,fig_box,self.htmls['table'] ],layout=Layout(min_width='60%')).add_class('marginless').add_class('borderless') if 'Bands' in self.dds['band_dos'].value: in_box.children = [Label('---------- Projections ----------'),self.InGui.box, Label('---- Other Arguments/Options ----'), VBox([HBox([Label('Ticks At: ',layout=l_out), self.texts['kticks'], Label('Labels: ',layout=l_out), self.texts['ktickv'] ]).add_class('borderless').add_class('marginless'), HBox([Label('Join At: ',layout=l_out), self.texts['kjoin'], Label('E Range: ',layout=l_out), self.texts['elim'] ]).add_class('marginless').add_class('borderless') ]).add_class('marginless')] right_box.children = [top_right,fig_box,points_box] self.buttons['toggle'].description = 'RGB' else: in_box.children = [Label('---------- Projections ----------'),self.InGui.box, Label('---- Other Arguments/Options ----'), HBox([Label('E Range:',layout=l_out), self.texts['elim'], Label('E-Fermi:',layout=l_out), self.texts['fermi'] ]).add_class('marginless')] right_box.children = [top_right,fig_box,points_box] self.dds['en_type'].value = 'None' # no scatter collection in DOS. self.buttons['toggle'].description = 'Fill' left_box = VBox([upper_box, in_box, HBox([Label('X, Y, Title'),self.texts['xyt']]).add_class('borderless'), HBox([Label('Options:'),self.buttons['summary'],self.buttons['save_fig'],self.buttons['toggle']]), cache_box, self.htmls['table']],layout=Layout(max_width='40%'), ).add_class('marginless').add_class('borderless') self.fig_gui.children = (left_box,right_box) self.buttons['load_graph'].icon = 'fa-refresh' return self.fig_gui # Return for use in show @output.capture() def __build(self): intro_html = ipw.HTML("<h2>Pivotpy</h2><p>Filter files here and switch tab to Graphs. You can create cache ahead of time to load quickly while working. If anything does not seem to work, see the error in STD(out/err) tab. For large files, do `Export-VaspRun` in Powershell to access fast. <a href=https://massgh.github.io/pivotpy/Widgets.html#VasprunApp target='_blank'>See More</a></p><marquee style='color:blue'>Pivotpy GUI based on ipywidgets!</marquee>") header_box = HBox([intro_html, Label('Theme:',layout=Layout(width='80px')), self.dds['theme'] ]).add_class('marginless').add_class('borderless') summary_gui = HBox([ipw.Label(), self.buttons['summary']] ).add_class('borderless') intro_box = VBox([self.htmls['theme'], header_box, self.files_gui, summary_gui] ).add_class('marginless').add_class('borderless').add_class('marginless') self.fig_gui = self.__figure_tab(1) #Start self.tab.children = (intro_box, self.fig_gui, VBox([HBox([ipw.HTML("<h3>Functions Logging/Output</h3>"), Box([ Label('Theme:',layout=Layout(width='80px')), self.dds['theme']],layout=Layout(left='50%')).add_class('borderless') ]).add_class('borderless').add_class('marginless'), VasprunApp.output]) ) self.dds['style'].value = 'plotly' # to trigger first callback on graph. self.app = self.tab #Need to access it self.__update_theme(True) #Good option in jupyterlab for following theme. def show(self): return display(self.tab) def __fill_ticks(self): kpath = os.path.join(os.path.split(self.files_dd.value)[0],'KPOINTS') tvs = sio.read_ticks(kpath) #ticks values segments if tvs['ktick_inds']: #If is must, if not present, avoid overwritting custom input self.texts['kticks'].value = ','.join([str(v) for v in tvs['ktick_inds']]) if tvs['ktick_vals']: self.texts['ktickv'].value = ','.join(tvs['ktick_vals']) if tvs['kseg_inds']: self.texts['kjoin'].value = ','.join([str(v) for v in tvs['kseg_inds']]) def __update_theme(self,change): if self.dds['theme'].value == 'Dark': self.htmls['theme'].value = css_style(dark_colors,_class=self.main_class) self.fig.update_layout(template='plotly_dark') self.dds['style'].value = 'plotly_dark' elif self.dds['theme'].value == 'Light': self.htmls['theme'].value = css_style(light_colors,_class=self.main_class) self.fig.update_layout(template='ggplot2') self.dds['style'].value = 'ggplot2' elif self.dds['theme'].value == 'Custom': self.htmls['theme'].value = css_style(simple_colors,_class=self.main_class) self.fig.update_layout(template='none') self.dds['style'].value = 'none' else: self.htmls['theme'].value = css_style(default_colors,_class=self.main_class) self.fig.update_layout(template='plotly') self.dds['style'].value = 'plotly' def __update_plot_style(self,change): self.fig.update_layout(template = self.dds['style'].value) @output.capture(clear_output=True,wait=True) def __load_previous(self,change): path = self.files_dd.value try: _dir = os.path.split(path)[0] r_f = os.path.join(_dir,'result.json') self.result = vp.load_from_dump(r_f,keep_as_dict=True) print('Previous Analysis loaded in Table for {}'.format(path)) except: print('Previous Analysis does not exist for {}'.format(path)) @output.capture(clear_output=True,wait=True) def __read_data(self,poscar=None,sys_info=None): if sys_info != None: self.result["sys"] = sys_info.SYSTEM if poscar != None: self.result["V"] = np.round(poscar.volume,5) a,b,c = np.round(np.linalg.norm(poscar.basis,axis=1),5) self.result["a"] = a self.result["b"] = b self.result["c"] = c @output.capture(clear_output=True,wait=True) def __on_load(self,button): self.__fill_ticks() # First fill ticks, then update input self.__update_input(change=None) # Fix input right here. self.__load_previous(change=button) # previous calculations. self.tab.selected_index = 2 self.buttons['load_data'].description='Loading ...' _dir = os.path.split(self.files_dd.value)[0] # directory try: sys_info = vp.load_from_dump(os.path.join(_dir,'sys_info.pickle')) self.data = vp.load_from_dump(os.path.join(_dir,'vasprun.pickle')) print('Cache Loaded') except: print('Trying Loading from Python ...') self.data = vp.export_vasprun(self.files_dd.value, **self.evr_kws) if self.cache_data: print('Caching From: {}'.format(self.files_dd.value)) #Cache result vp.dump_dict(self.data.sys_info,outfile=os.path.join(_dir,'sys_info.pickle')) vp.dump_dict(self.data,outfile=os.path.join(_dir,'vasprun.pickle')) sys_info = self.data.sys_info # required here. print('Done') _ = self.__read_data(self.data.poscar,sys_info) # Update Table data on load self.texts['fermi'].value = str(sys_info.E_Fermi) # Needs each time new data loads up. self.tab.selected_index = 1 # Revamp input dropdowns on load ========== self.InGui.update_options(sys_info=sys_info) #Upadate elements/orbs/labels #=========================================== self.buttons['load_data'].description='Load Data' self.__path = self.files_dd.value # Update in __on_load or graph to make sure data loads once self.buttons['load_data'].tooltip = "Current System\n{!r}".format(self.data.sys_info) self.buttons['load_graph'].icon = 'fa-refresh' @output.capture(clear_output=True,wait=True) def __update_input(self,change): self.input.update(self.InGui.output) elim_str = [v for v in self.texts['elim'].value.split(',') if v!=''] fermi_str = self.texts['fermi'].value self.input['E_Fermi'] = float(fermi_str) if fermi_str else 0 # Change now, keep zero else must. self.input['elim'] = [float(v) for v in elim_str if v!='-'][:2] if len(elim_str) >= 2 else None if self.dds['band_dos'].value == 'Bands': kjoin_str = [v for v in self.texts['kjoin'].value.split(',') if v!=''] kticks_str = [v for v in self.texts['kticks'].value.split(',') if v!=''] ktickv_str = [v for v in self.texts['ktickv'].value.split(',') if v!=''] self.input['kseg_inds'] = [int(v) for v in kjoin_str if v!='-'] if kjoin_str else None self.input['ktick_inds'] = [int(v) for v in kticks_str if v!='-'] if kticks_str else [0,-1] self.input['ktick_vals'] = [v for v in ktickv_str if v!=''] if ktickv_str else ['A','B'] else: self.input = {k:v for k,v in self.input.items() if k not in ['ktick_inds','ktick_vals','kseg_inds']} #Update at last self.InGui.output = self.input self.buttons['load_graph'].tooltip = "Current Input\n{!r}".format(vp.Dict2Data(self.input)) self.buttons['load_graph'].icon = 'fa-refresh' @output.capture(clear_output=True,wait=True) def __update_table(self,change): self.htmls['table'].value = _tabulate_data(self.result) _save_data(self.files_dd,self.result) # save data as well. @output.capture(clear_output=True,wait=True) def __df_out(self,btn): self.tab.selected_index = 2 self.buttons['summary'].description = 'See STD(out/err) Tab' paths = [v for (k,v) in self.files_dd.options] df = generate_summary(paths_list=paths) display(df) self.df = df # Assign print('Get above DataFrame by app_name.df\nNote: app_name is variable name assigned to VasprunApp()') print('==================== OR =========================') _code = "import pivotpy as pp\npaths = ['{}']\ndf = pp.generate_summary(paths_list=paths)\ndf".format("',\n '".join([str(p).replace('\\','/') for p in paths])) _code += "\n#ax = pp.init_figure()\n#df.plot(ax=ax,x='sys',y=['V','a'])" display(Markdown("```python\n{}\n```".format(_code))) self.buttons['summary'].description = 'Project Summary' @output.capture(clear_output=True,wait=True) def __deleter(self,btn): self.buttons['confirm'].description = 'Deleting ...' if self.files_dd.value: print('Deleting Selected Cache...') self.__clear_cache() # Deleting print('Done') self.__update_table(1) #Update when delete data self.buttons['confirm'].description='Confirm Delete' @output.capture(clear_output=True,wait=True) def __update_xyt(self,change): if self.texts['xyt'].value: xyt_text = self.texts['xyt'].value.split(',') try: self.fig.update_xaxes(title=xyt_text[0]) self.fig.update_yaxes(title=xyt_text[1]) self.fig.update_layout(title=xyt_text[2]) except: pass #do nothing else if self.texts['ktickv'].value or self.texts['kticks'].value or self.texts['elim'].value: self.__update_input(change=None) if self.dds['band_dos'].value == 'Bands' and self.data: tickvals = [self.data.kpath[i] for i in self.input['ktick_inds']] self.fig.update_xaxes(ticktext=self.input['ktick_vals'], tickvals=tickvals) if self.texts['elim'].value and self.input['elim'] != None and len(self.input['elim']) == 2: if self.dds['band_dos'].value == 'Bands': self.fig.update_yaxes(range = self.input['elim']) else: self.fig.update_xaxes(range = self.input['elim']) @output.capture(clear_output=True,wait=True) def __tog_b(self,tog_w): _color_toggle(self.buttons['toggle'],self.fig,self.dds['band_dos']) @output.capture(clear_output=True,wait=True) def __save_connected(self,btn): s_p = os.path.split(self.files_dd.value)[0] filename = os.path.join(s_p,'ConnectedFig.html') filename = gu.prevent_overwrite(filename) self.buttons['save_fig'].description = 'Saving...' views = VBox([self.htmls['theme'],self.fig,self.htmls['table']], layout=Layout(width='500px',height='490px')).add_class('borderless') embed_minimal_html(filename, views=[views], state=dependency_state([views])) self.buttons['save_fig'].description = 'Save Fig' self.buttons['save_fig'].tooltip = 'Recently Saved\n{!r}'.format(filename) @output.capture(clear_output=True,wait=True) def __expand_fig(self,btn): self.tab.selected_index = 2 self.dds['en_type'].value = 'None' # To avoid accidental clicks display(self.fig) # Garph @output.capture(clear_output=True,wait=True) def __update_graph(self,btn): path = self.files_dd.value if path: self.__fill_ticks() # First fill ticks, then update input self.__update_input(change=None) # Update input here as well self.tab.selected_index = 2 self.fig.data = [] if self.data and path == self.__path: # Same load and data exists, heeps in fast print('Data already loaded') else: try: self.buttons['load_graph'].description = 'Loading pickle...' print('Trying to Load Cache for Graph ...') file = os.path.join(os.path.split(path)[0],'vasprun.pickle') self.buttons['load_graph'].description = file self.data = vp.load_from_dump(file) self.buttons['load_graph'].description = 'Load Graph' except: self.buttons['load_graph'].description = 'Loading export...' print('No cache found. Loading from file {} ...'.format(path)) self.data = vp.export_vasprun(path, **self.evr_kws) self.buttons['load_graph'].description = "Load Graph" print('Done') self.__path = self.files_dd.value #update here or __on_load. Useful to match things self.buttons['load_graph'].description = 'Load Graph' _ = self.__read_data(self.data.poscar,self.data.sys_info) # Update Table data # Do Not Read Fermi, its 0 or given by user if self.dds['band_dos'].value == 'Bands': fig_data = ip.iplot_rgb_lines(path_evr=self.data,**self.input,**self.ibands_kws) else: self.dds['en_type'].value = 'None' # Avoid random clicks fig_data = ip.iplot_dos_lines(path_evr=self.data,**self.input,**self.idos_kws) # input auto-modified self.tab.selected_index = 1 with self.fig.batch_animate(): for d in fig_data.data: self.fig.add_trace(d) fig_data.layout.template = self.dds['style'].value # before layout to avoid color blink self.fig.layout = fig_data.layout _click_data(self.dds['en_type'],self.texts['fermi'],self.result,self.fig,self.dds['band_dos']) self.buttons['load_graph'].icon = 'fa-check' @output.capture(clear_output=True,wait=True) def __clear_cache(self): self.tab.selected_index = 2 _dir = os.path.split(self.files_dd.value)[0] if 'Table' in self.dds['cache'].value: for k in self.result.keys(): # Avoid deleting V,a,b,Fermi if k not in ['sys','V','a','b','c','Fermi']: self.result[k] = '' if 'PWD' in self.dds['cache'].value: _files = [os.path.join(_dir,f) for f in ['sys_info.pickle','vasprun.pickle']] _ = [[print("Deleting", _file),os.remove(_file)] for _file in _files if os.path.isfile(_file)] if 'All' in self.dds['cache'].value: for (key, value) in self.files_dd.options: _dir = os.path.split(value)[0] _files = [os.path.join(_dir,f) for f in ['sys_info.pickle','vasprun.pickle']] _ = [[print("Deleting", _file),os.remove(_file)] for _file in _files if os.path.isfile(_file)] self.tab.selected_index = 1 def iplot(self,**kwargs): "Returns a detached interactive Figure. `kwargs` are passed to `iplot_rgb_lines` or `iplot_dos_lines` based on current figure. `kwargs` should exclude whatever inside `self.input` and `path_evr`" kwargs = {k:v for k,v in kwargs.items() if k not in self.input.keys() or k!='path_evr'} if self.dds['band_dos'].value == 'Bands': return ip.iplot_rgb_lines(path_evr=self.data,**self.input,**kwargs) else: return ip.iplot_dos_lines(path_evr=self.data,**self.input,**kwargs) def splot(self,**kwargs): "Returns matplotlib Axes.`kwargs` are passed to `splot_rgb_lines` or `splot_dos_lines` based on current figure. `kwargs` should exclude whatever inside `self.input` and `path_evr`" kwargs = {k:v for k,v in kwargs.items() if k not in self.input.keys() or k!='path_evr'} if self.dds['band_dos'].value == 'Bands': return sp.splot_rgb_lines(path_evr=self.data,**self.input,**kwargs) else: return sp.splot_dos_lines(path_evr=self.data,**self.input,**kwargs) # Cell class KPathApp: """View and trace path on BZ. - **Usage** > ka = KPathApp() > ka.show() #Display app > ka.splot() #get matplotlib figure """ output = ipw.Output().add_class('output') def __init__(self,path='POSCAR'): self.path = path self.files_gui, self.files_dd = get_files_gui(auto_fill='POSCAR') self.files_dd.layout.width = '50%' self.main_class = 'custom-'+''.join(np.random.randint(9,size=(21,)).astype(str)) #Random class self.tab = ipw.Tab(children=[self.files_gui,Box([]),KPathApp.output]).add_class(self.main_class) self.tab.add_class('marginless').add_class('borderless') self.tab.layout = Layout(width='100%',min_width='100%',height='450px',min_height='450px') try: for i,title in enumerate(['Home','Main','STDERR']): self.tab.set_title(i,title) except: self.tab.titles = ['Home','Main','STDERR'] self.app = self.tab self.fig = go.FigureWidget() self.fig.layout.template = 'plotly_white' #Forces to avoid colored patch in background self.bz = None self.kcsn = [] #KPOINTS, COORDS,SYMBOLS, N_per_interval and box symbol in dictionary per item self.buttons = {'delete':Button(description='Delete Selection'), 'add':Button(description='Add Point'), 'patch':Button(description='Split Path'), 'fig_up': Button(description='Update Figure'), 'theme': Button(description='Dark Theme')} self.sm = SelectMultiple(layout=Layout(width='100%')) self.texts = {'label':Text(description='Label, N',indent=False), 'kxyz':Text(description='kx, ky, kz',indent=False)} self.theme_html = ipw.HTML(css_style(light_colors,_class=self.main_class)) self.buttons['delete'].on_click(self.__delete) self.buttons['add'].on_click(self.__add) self.buttons['patch'].on_click(self.__add_patch) self.buttons['theme'].on_click(self.__toggle_theme) self.buttons['fig_up'].on_click(self.__update_fig) self.texts['label'].on_submit(self.__label) self.texts['kxyz'].on_submit(self.__manual_k) self.__update_fig() self.__build() @output.capture(clear_output=True,wait=True) def __toggle_theme(self,change): _style = '''<style>.widget-select-multiple>select {{ font-family: "Cascadia Code","Ubuntu Mono","SimSun-ExtB","Courier New"; background:{next_bg};border-radius:0;color:{accent};border:none; height:auto;min-height:160px;padding:5px;margin:0px;overflow:auto;}} .widget-select-multiple>select>option:hover, .widget-select-multiple>select>option:focus{{background:{hover_bg};}}</style>''' if self.buttons['theme'].description == 'Dark Theme': self.theme_html.value = css_style(dark_colors,_class = self.main_class) + _style.format(**dark_colors) self.fig.layout.template = 'plotly_dark' self.fig.layout.paper_bgcolor = dark_colors['main_bg'] #important self.buttons['theme'].description = 'Light Theme' else: self.theme_html.value = css_style(light_colors,_class=self.main_class) + _style.format(**light_colors) self.fig.layout.template = 'plotly_white' self.fig.layout.paper_bgcolor = light_colors['main_bg'] self.buttons['theme'].description = 'Dark Theme' @output.capture(clear_output=True,wait=True) def __manual_k(self,change): for i in self.sm.value: self.kcsn[i]['k'] = [float(v) for v in self.texts['kxyz'].value.split(',') if v != ''][:3] self.texts['kxyz'].value = '' # clean it self.__update_label() self.__update_selection() #Change on graph too def __label_at(self,i): self.kcsn[0]['b'], self.kcsn[-1]['b'] = '┌', '└' #Avoid clashes _ln_ = f"─ {self.kcsn[i]["n"]}" if self.kcsn[i]['n'] and i < (len(self.sm.options) - 1) else "" if self.kcsn[i]['k']: return "{0} {1} {2:>8.4f}{3:>8.4f}{4:>8.4f} {5}".format(self.kcsn[i]['b'],self.kcsn[i]['s'],*self.kcsn[i]['k'],_ln_) return f"{self.kcsn[i]["b"]} {self.kcsn[i]["s"]} {_ln_}" def __update_label(self): opt = list(self.sm.options) vs = self.sm.value # get before it goes away for i in vs: opt[i] = (self.__label_at(i),i) self.sm.options = tuple(opt) if vs[-1:]: try: self.sm.value = (vs[-1] + 1,) except:pass @output.capture(clear_output=True,wait=True) def __build(self): for k,b in self.buttons.items(): b.layout.width = 'max-content' for k,t in self.texts.items(): t.layout.width='85%' top_row = HBox([self.files_dd,self.buttons['fig_up']]).add_class('borderless') _buttons1 = HBox([self.buttons[b] for b in ['add','delete']]).add_class('borderless') _buttons2 = HBox([self.buttons[b] for b in ['patch','theme']]).add_class('borderless') self.tab.children = [self.tab.children[0], HBox([ VBox([self.theme_html, VBox([top_row,_buttons1,_buttons2], layout = Layout(min_height='140px')), Box([self.sm]).add_class('marginless').add_class('borderless'), *self.texts.values()], layout=Layout(min_width='320px')).add_class('borderless'), Box([self.fig]).add_class('borderless')], layout=Layout(height='400px',width='auto')).add_class('borderless'), self.tab.children[-1]] def show(self): return display(self.tab) @output.capture(clear_output=True,wait=True) def __delete(self,change): v = self.sm.value for i, kp in enumerate(self.kcsn): self.kcsn[i]['b'] = '├' #Break Path Retrieve first self.kcsn = [k for i,k in enumerate(self.kcsn) if i not in v] self.sm.options = [(self.__label_at(i),i) for i,op in enumerate(self.kcsn)] @output.capture(clear_output=True,wait=True) def __add(self,change): if self.kcsn: self.kcsn.append({'k':[],'c':[],'s':'','n':'', 'b': '└'}) else: self.kcsn.append({'k':[],'c':[],'s':'','n':'', 'b': '┌'}) for i, kp in enumerate(self.kcsn[1:-1]): self.kcsn[i+1]['b'] = '├' self.sm.options = [*self.sm.options,('You just added me',len(self.sm.options))] self.sm.value = (len(self.sm.options) - 1,) # make available @output.capture(clear_output=True,wait=True) def __add_patch(self,change): vs = [v for v in self.sm.value if v > 1 and v < len(self.sm.options) - 1] opts = list(self.sm.options) for i,v in enumerate(self.sm.options): # Clean previous action if i > 0 and i < len(opts) - 1: #Avoid end points self.kcsn[i]['b'] = '├' opts[i] = (self.__label_at(i),i) #Patch before selection if i in vs: self.kcsn[i]['b'] = '┌' self.kcsn[i-1]['b'] = '└' opts[i] = (self.__label_at(i),i) opts[i-1] = (self.__label_at(i-1),i-1) self.sm.options = opts self.__update_selection() @output.capture(clear_output=True,wait=True) def get_coords_labels(self): "`coords` are calculated for current `bz` even if `kpoints` were from other one. Useful in case of same kind of Zones with just basis changed." if self.bz: for i, kp in enumerate(self.kcsn): self.kcsn[i]['c'] = sio.to_R3(self.bz.basis,kp['k']).tolist() if kp['k'] else [] coords = [kp['c'] for kp in self.kcsn] labels = [kp['s'] for kp in self.kcsn] j = 0 for p in self.get_patches()[:-1]: labels.insert(p.stop+j,'NaN') coords.insert(p.stop+j,[np.nan,np.nan,np.nan]) j += 1 coords = np.array([c for c in coords if c]) labels = [l for l in labels if l] return coords,labels @output.capture(clear_output=True,wait=True) def __update_selection(self): coords,labels = self.get_coords_labels() with self.fig.batch_animate(): for trace in self.fig.data: if 'path' in trace.name and coords.any(): trace.x = coords[:,0] trace.y = coords[:,1] trace.z = coords[:,2] trace.text = labels @output.capture(clear_output=True,wait=True) def __click(self): def handle_click(trace, points, state): if points.ys != []: index = points.point_inds[0] kp = trace.hovertext[index] kp = [float(k) for k in kp.split('[')[1].split(']')[0].split()] cp = [trace.x[index],trace.y[index],trace.z[index]] for i in self.sm.value: self.kcsn[i]['k'] = kp self.kcsn[i]['c'] = cp self.__update_label() self.__update_selection() for trace in self.fig.data: if 'HSK' in trace.name: trace.on_click(handle_click) @output.capture(clear_output=True,wait=True) def __update_fig(self,change=None): if self.files_dd.value: self.path = self.files_dd.value self.bz = sio.get_bz(self.path) fig_data = sio.iplot_bz(self.bz,fill=False,color='red',background='rgba(1,1,1,0)') self.fig.data = [] with self.fig.batch_animate(): self.fig.add_trace(go.Scatter3d(x = [],y = [],z = [], mode='lines+text+markers',name='path',text=[], textfont_size=18)) self.__update_selection() #Show previous path on current fig. for trace in fig_data.data: self.fig.add_trace(trace) self.fig.layout = fig_data.layout self.fig.layout.autosize=True self.fig.layout.scene.aspectmode = 'data' #very important self.__click() self.__toggle_theme(None) #Important to let text appear correctly @output.capture(clear_output=True,wait=True) def __label(self,change): for i in self.sm.value: inbox = self.texts['label'].value.split(',') self.kcsn[i]['s'] = 'Γ' if 'am' in inbox[0] else inbox[0] #fix gamma try: self.kcsn[i]['n'] = int(inbox[1]) except: pass self.texts['label'].value = '' # Clear it self.__update_label() self.__update_selection() def get_patches(self): bs = [kp['b'] for kp in self.kcsn] patches = [*[i for i,b in enumerate(bs) if '┌' in b],len(self.kcsn)] _patches = [range(i,j) for i,j in zip(patches[:-1],patches[1:])] if _patches and len(_patches) <= 1: return [] return _patches def get_data(self): obj = [{k:v for k,v in kp.items() if k != 'b'} for kp in self.kcsn] patches = self.get_patches() fmt_str = "{0:>16.10f}{1:>16.10f}{2:>16.10f} !{3} {4}" if patches: p_strs = ['\n'.join([fmt_str.format( *self.kcsn[p]['k'],self.kcsn[p]['s'],self.kcsn[p]['n'] ) for p in ps]) for ps in patches] return obj, '\n\n'.join(p_strs) else: return obj,'\n'.join([fmt_str.format(*kp['k'],kp['s'],kp['n']) for kp in self.kcsn]) def get_kpath(self,n=5,weight=None,ibzkpt=None,outfile=None): "See Docs of pp.str2kpath for details." kws = dict(n=n,weight=weight,ibzkpt=ibzkpt,outfile=outfile) _, k_str = self.get_data() return sio.str2kpath(k_str,**kws) def splot(self,**kwargs): "Same as `pp.splot_bz` except it also plots path on BZ. `kwargs` are passed to `pp.splot_bz`" ax = sio.splot_bz(path_pos_bz=self.path,**kwargs) coords,labels = self.get_coords_labels() plane = kwargs.get('plane',None) if plane != None and plane in 'xyzxzyx': ind = 'xyzxzyx'.index(plane) arr = [0,1,2,0,2,1,0] ix,iy = arr[ind],arr[ind+1] coords = coords[:,[ix,iy]] if coords.any(): #To avoid errors if not coords ax.plot(*coords.T,'-o',color='blue',lw=0.8) _ = [ax.text(*vs,lab) for vs,lab in zip(coords,labels) if lab!='NaN'] return ax def iplot(self): "Returns disconnected current plotly figure" return go.Figure(data=self.fig.data, layout=self.fig.layout)
# AUTOGENERATED! DO NOT EDIT! File to edit: Widgets.ipynb (unless otherwise specified). __all__ = ['css_style', 'dark_colors', 'light_colors', 'simple_colors', 'default_colors', 'get_files_gui', 'InputGui', 'generate_summary', 'VasprunApp', 'KPathApp'] # Cell import os, textwrap import json from time import sleep # Widgets Imports from IPython.display import display, Markdown from IPython import get_ipython #For SLides import ipywidgets as ipw from ipywidgets import Layout,Label,Button,Box,HBox,VBox,Dropdown,Text,Checkbox, SelectMultiple from ipywidgets.embed import embed_minimal_html, dependency_state # More exports import numpy as np import pandas as pd import plotly.graph_objects as go # Inside packages import to work both with package and jupyter notebook. try: from pivotpy import g_utils as gu from pivotpy import vr_parser as vp from pivotpy import i_plots as ip from pivotpy import s_plots as sp from pivotpy import sio except: import pivotpy.g_utils as gu import pivotpy.vr_parser as vp import pivotpy.i_plots as ip import pivotpy.s_plots as sp import pivotpy.sio as sio # Cell def css_style(colors_dict,_class = 'main_wrapper'): """Return style based on colors_dict available as pp.light_colors, pp.dark_colors etc""" return """<style> .{_class} h1,h2,h3,h4,h5,h6 {{ color: {accent} !important; }} .{_class} .widget-label-basic {{ background-color: transparent !important; color: {main_fg} !important; }} .{_class} .widget-text input {{ background-color: {next_bg} !important; border-radius:20px !important; padding: 0px 10px 0px 10px !important; border: 1px solid {next_bg} !important; color: {main_fg} !important; }} .{_class} .widget-text input:focus {{ border: 1px solid {hover_bg} !important; }} .{_class} .widget-text input:hover {{ border: 1px solid {hover_bg} !important; }} .{_class} .widget-dropdown > select {{ background-color: {next_bg} !important; border:none !important; border-bottom: 1px solid {hover_bg} !important; box-shadow: inset 0 -20px 10px -20px {hover_bg}; color: {main_fg} !important; }} .{_class} .widget-dropdown > select:hover {{ background-color: {hover_bg} !important; }} .{_class} .widget-dropdown > select > option {{ color: {main_fg} !important; background-color: {next_bg} !important; }} .{_class} .widget-dropdown > select > option:focus {{ background-color: {hover_bg} !important; }} .{_class} .widget-label {{ color: {main_fg} !important; }} .{_class} .widget-html {{ color: {main_fg} !important; }} .{_class} .widget-box, .{_class}.widget-box {{ background-color: {main_bg} !important; border-radius:5px !important; padding:1px !important; border: 1px solid {next_bg} !important; box-shadow: 1px 1px 1px 1px {next_bg} !important; }} .{_class} .borderless, .{_class}.borderless {{ border: 1px solid transparent !important; box-shadow: none !important; border-radius: 4px !important; margin:4px !important; }} .{_class} .marginless, .{_class}.marginless {{ margin: 0px !important; border-radius: 0px !important; }} .{_class} .output, .{_class}.output {{ color: {main_fg} !important; background-color: inherit !important; }} .{_class} .widget-tab, .{_class}.widget-tab {{ background-color: {main_bg} !important; border: none !important; box-shadow: 1px 1px 1px 1px {next_bg} !important; padding: 0px 2px 2px 2px !important; }} .{_class} .widget-tab-contents, .{_class}.widget-tab > .widget-tab-contents {{ width: 100%; box-sizing: border-box; margin: 0px !important; padding: 0px !important; flex-grow: 1; overflow: auto; border: none !important; background-color: {main_bg} !important; }} .{_class} .widget-tab > .p-TabBar .p-TabBar-tab, .{_class}.widget-tab > .p-TabBar .p-TabBar-tab {{ background-color:{main_bg} !important; border: none !important; color: {accent} !important; font-weight: bold !important; font-size: 16px !important; font-family: "Times","serif" !important; text-align: center !important; }} .{_class} table {{ color: {main_fg} !important; }} .{_class} tr:nth-child(odd) {{ background-color: {next_bg} !important; }} .{_class} tr:nth-child(even) {{ background-color: {main_bg} !important; }} .{_class} .widget-button,.widget-toggle-button {{ color: {accent} !important; min-width: max-content !important; background-color: {next_bg}; border-radius: 5px !important; }} .{_class} tr:hover {{ background-color: {hover_bg} !important; }} </style> """.format(**colors_dict,_class= _class) dark_colors = { 'main_fg' : '#ABB2BF', 'main_bg' : '#21252B', 'next_bg' : '#282C34', 'hover_bg' : '#414855', 'accent' : '#61AFEF' } light_colors = { 'next_bg' : 'white', 'hover_bg' : '#abe4ff', 'accent' : 'navy', 'main_bg' : '#F3F3F3', 'main_fg' : 'black' } simple_colors = { 'hover_bg' : 'lightgray', 'accent' : 'black', 'main_bg' : 'white', 'main_fg' : 'black', 'next_bg' : 'whitesmoke' } default_colors = { # Adopt Jupyterlab theme 'main_fg' : 'var(--jp-inverse-layout-color0,black)', 'main_bg' : 'var(--jp-layout-color0,#F3F3F3)', 'next_bg' : 'var(--jp-layout-color2,white)', 'hover_bg': 'var(--jp-border-color1,lightblue)', 'accent' : 'var(--jp-brand-color2,navy)' } # Cell def get_files_gui(auto_fill = 'vasprun.xml', theme_colors = None, height=320): """ - Creates a GUI interface for files/folders filtering. - **Parmeters** - auto_fill : Default is `vasprun.xml`, any file/folder. - theme_colors : None,Any of pivotpy.[dark,light,simple]_colors. - height : Height of Grid box. - **Returns** - Tuple(GUI_gridbox,Files_Dropdown). Access second one by item itself. """ files_w = ipw.Dropdown(continuous_update=False) pw = ipw.Text(value=os.getcwd()) incldue_w = ipw.Text(value=auto_fill) excldue_w = ipw.Text() d_layout = Layout(width='30%') l_layout = Layout(width='19%') depth_w = ipw.Dropdown(options=[None,1,2,3,4,5],value=4,layout=d_layout) item_w = ipw.Dropdown(options=['Both','Files','Folders'],value='Files',layout=d_layout) item_box = ipw.HBox([ipw.Label('Depth: ',layout=l_layout),depth_w,ipw.Label('Type: ',layout=l_layout),item_w]) item_box.add_class('borderless').add_class('marginless') applybtn_w = ipw.Button(description='Apply Filters') gci_output = ipw.Output(layout=Layout(height='{}px'.format(height-70))) label_head = ipw.HTML("<h3>Your Filtered Files List</h3>") def filter_gci(applybtn_w): applybtn_w.description = 'Applying...' applybtn_w.disabled = True if os.path.isdir(pw.value): path = pw.value else: with gci_output: print("Given path does not exists.") print("Falling back to PWD: {}".format(os.getcwd())) path = os.getcwd() pw.value = path gci = vp.Dict2Data({'children':[],'parent':path}) if 'Files' in item_w.value: file_type = dict(filesOnly=True) elif 'Folders' in item_w.value: file_type = dict(dirsOnly=True) else: file_type = {} try: gci = gu.get_child_items(path=path, **file_type, include= incldue_w.value, exclude= excldue_w.value, depth=depth_w.value) except: with gci_output: print('Something went wrong') # Enable before any error occur. applybtn_w.disabled = False files_w.options = [(name, os.path.join(gci.parent,name)) for name in gci.children] applybtn_w.description = 'Successful!' label_head.value = "<h3>From: {}</h3>".format(gci.parent) with gci_output: display(ipw.HTML("<h4>{} files found.</h4>".format(len(gci.children)))) display(ipw.HTML("<ol>{}<ol>".format(''.join(['<li>{}</li>'.format(i) for i in gci.children])))) applybtn_w.description = 'Apply Filters' gci_output.clear_output(wait=True) applybtn_w.on_click(filter_gci) out_box = ipw.Box([gci_output]) right_box = ipw.VBox([label_head,out_box]) out_box.add_class('borderless') right_box.add_class('borderless') i_layout = Layout(width='99%') incldue_w.layout = i_layout excldue_w.layout = i_layout pw.layout = i_layout input_box = ipw.VBox([ ipw.Label('Path to Project Folder',layout=i_layout),pw, ipw.Label('Items to Include (separate by |)',layout=i_layout),incldue_w, ipw.Label('Items to Exclude (separate by |)',layout=i_layout),excldue_w, item_box, applybtn_w],layout=Layout(width='330px')) _class = 'custom-'+''.join(np.random.randint(9,size=(23,)).astype(str)) #Random class html_style = css_style(theme_colors,_class = _class) if theme_colors else '' full_box = ipw.HBox([ipw.HTML(html_style),input_box, right_box], layout=Layout(height='{}px'.format(height))).add_class(_class) full_box.add_class('borderless').add_class('marginless') return full_box, files_w # Cell class InputGui: def __init__(self,sys_info=None,theme_colors = None,height=400): """ - Creates a GUI interface for input/selection of orbitals/elms projection. - **Parmeters** - theme_colors : None,Any of pivotpy.[dark,light,simple]_colors. - height : Height of Grid box, Can set to None for auto-resizing. - sys_info : `export_vasprun().sys_info`. Can change later using `self.update_options` mthod. - **Output Parameters** - output: Dictionary that contains kwargs for plot functions. - html : A widget which can be used to bserve change in output, used in `VasprunApp`. """ self.sys_info = sys_info if sys_info else vp.Dict2Data({'fields':['s'], 'ElemIndex':[0,1],'ElemName':['A']}) self.output = dict(elements = [[],[],[]],orbs = [[],[],[]],labels = ['','','']) layout = Layout(width='30%') l_width = Layout(width='20%') self.html = ipw.HTML() # For Display in Big App as well. Very important self.dds = { 'elms': Dropdown(layout=layout), 'orbs': Dropdown(layout=layout), 'rgb' : Dropdown(options=[('Red',0),('Green',1),('Blue',2)],value=0,layout=layout) } self.texts = { 'orbs' : Text(layout=layout,continuous_update=False), 'elms' : Text(layout=layout,continuous_update=False), 'label': Text(layout=layout,continuous_update=False) } self.update_options(self.sys_info) # In start if given _class = 'custom-'+''.join(np.random.randint(9,size=(23,)).astype(str)) #Random class html_style = css_style(theme_colors,_class = _class) if theme_colors else '' self.box = VBox([ipw.HTML(html_style), self.html, HBox([Label('Color: ',layout=l_width), self.dds['rgb'], Label('Label: ',layout=l_width),self.texts['label'] ]).add_class('borderless').add_class('marginless'), HBox([Label('Ions: ',layout=l_width),self.dds['elms'], Label('::>>:: ',layout=l_width),self.texts['elms'] ]).add_class('borderless').add_class('marginless'), HBox([Label('Orbs: ',layout=l_width),self.dds['orbs'], Label('::>>:: ',layout=l_width),self.texts['orbs'] ]).add_class('borderless').add_class('marginless') ],layout=Layout(height="{}px".format(height)) ).add_class(_class).add_class('marginless') #Obsever self.dds['rgb'].observe(self.__see_input,'value') self.texts['label'].observe(self.__read_pro,'value') self.texts['orbs'].observe(self.__read_pro,'value') self.texts['elms'].observe(self.__read_pro,'value') # Link ipw.dlink((self.dds['elms'],'value'),(self.texts['elms'],'value')) ipw.dlink((self.dds['orbs'],'value'),(self.texts['orbs'],'value')) def update_options(self,sys_info=None): if sys_info: orbs_opts = [(str(i)+': '+item,str(i)) for i,item in enumerate(sys_info.fields)] if len(sys_info.fields) == 9: orbs_opts = [*orbs_opts,('1-3: p','1-3'),('4-8: d','4-8')] if len(sys_info.fields) == 16: orbs_opts = [*orbs_opts,('9-15: f','9-15')] max_ind = len(sys_info.fields)-1 orbs_opts = [('0-{}: All'.format(max_ind), "0-{}".format(max_ind)),*orbs_opts] inds = sys_info.ElemIndex ions_opts = [("{}-{}: {}".format(inds[i],inds[i+1]-1,item),"{}-{}".format( inds[i],inds[i+1]-1)) for i,item in enumerate(sys_info.ElemName)] self.dds['elms'].options = [*ions_opts,('0-{}: All'.format(inds[-1]-1),'0-{}'.format(inds[-1]-1))] self.dds['orbs'].options = orbs_opts self.sys_info = sys_info # Update it as well. def __read_pro(self,btn): def read(cell_value): _out = [] for v in (cell_value.split(",") if cell_value else ''): if v and '-' in v: i, f = [int(k) for k in v.split("-")] _out = [*_out,*list(range(i,f+1))] elif v: _out = [*_out,int(v)] return _out index = self.dds['rgb'].value self.output['elements'][index] = read(self.texts['elms'].value) self.output['orbs'][index] = read(self.texts['orbs'].value) _text,_ion,_orb = self.texts['label'].value,self.texts['elms'].value,self.texts['orbs'].value self.output['labels'][index] = _text if _text else "{}:{}".format(_ion,_orb) self.html.value = """<div style='border: 2px solid {0}!important; background-color:{0} !important;'> </div> """.format(self.dds['rgb'].label.lower()) sleep(1) self.html.value = '' def __see_input(self,change): # Unobserve first to avoid overwriting self.texts['label'].unobserve(self.__read_pro,'value') self.texts['orbs'].unobserve(self.__read_pro,'value') self.texts['elms'].unobserve(self.__read_pro,'value') # Look up while not observing x = self.dds['rgb'].value self.texts['elms'].value = ','.join([str(i) for i in self.output['elements'][x]]) self.texts['orbs'].value = ','.join([str(i) for i in self.output['orbs'][x]]) self.texts['label'].value = self.output['labels'][x] # Observe Back Again self.texts['label'].observe(self.__read_pro,'value') self.texts['orbs'].observe(self.__read_pro,'value') self.texts['elms'].observe(self.__read_pro,'value') def show(self): return self.box # Cell #mouse event handler def _click_data(sel_en_w,fermi_w,data_dict,fig,bd_w): def handle_click(trace, points, state): if(points.ys!=[]): e_fermi = (float(fermi_w.value) if fermi_w.value else 0) v_clicked = points.ys[0] if bd_w.value=='Bands' else points.xs[0] val = np.round(float(v_clicked) + e_fermi,4) #exact value for key in sel_en_w.options: if key in sel_en_w.value and key != 'None': data_dict[key] = val # Assign value back if 'Fermi' in sel_en_w.value: fermi_w.value = str(val) # change fermi # Shift Graph for Fermi value if 'Fermi' in sel_en_w.value: with fig.batch_animate(): for trace in fig.data: # Shift graph as Fermi Changes if bd_w.value == 'Bands': trace.y = [y - data_dict['Fermi'] + e_fermi for y in trace.y] else: trace.x = [x - data_dict['Fermi'] + e_fermi for x in trace.x] # Update Fermi, SO etc if data_dict['VBM'] and data_dict['CBM']: data_dict['E_gap'] = np.round(data_dict['CBM'] - data_dict['VBM'], 4) if data_dict['so_max'] and data_dict['so_min']: data_dict['Δ_SO'] = np.round(data_dict['so_max'] - data_dict['so_min'], 4) # Cycle energy types on graph click and chnage table as well unless it is None. if sel_en_w.value == 'CBM': # Avoid accidental SO calculation sel_en_w.value = 'None' if sel_en_w.value != 'None': # Keep usually as None _this = sel_en_w.options.index(sel_en_w.value) _next = _this + 1 if _this < len(sel_en_w.options) - 1 else 0 sel_en_w.value = sel_en_w.options[_next] #To simulate as it changes for trace in fig.data: trace.on_click(handle_click) # Display Table def _tabulate_data(data_dict): new_dict = {k:v for k,v in data_dict.items() if v != '' and k not in ['sys','so_max','so_min','Fermi']} ls = list(new_dict.keys()) ds = list(new_dict.values()) if len(ls) % 2 != 0: ls.append('') ds.append('') tab_data = [ls[:int(len(ls)/2)],ds[:int(len(ls)/2)],ls[int(len(ls)/2):],ds[int(len(ls)/2):]] htm_string = """<style>table {border-collapse: collapse !important; min-width: 100% !important; margin: 1px 1px 1px 1px !important; font-size: small !important; font-family: "Times New Roman", "Times", "serif" !important;} th, td {text-align: center !important; padding: 0px 8px 0px 8px !important;} tr { width: 100% !important;} tr:nth-child(odd) {font-weight:bold !important;} </style>""" htm_string += "<table><tr>{}</tr></table>".format( '</tr><tr>'.join( '<td>{}</td>'.format('</td><td>'.join(str(_) for _ in row)) for row in tab_data) ) return htm_string # Send Data def _save_data(out_w1,data_dict): out_f = os.path.join(os.path.split(out_w1.value)[0],'result.json') vp.dump_dict(data_dict,dump_to='json',outfile=out_f) # Cell def _color_toggle(tog_w,fig,rd_btn): if tog_w.icon == 'toggle-off': tog_w.icon = 'toggle-on' with fig.batch_animate(): if rd_btn.value == 'DOS': for trace in fig.data: trace.fill='tozeroy' else: for trace in fig.data[:1]: trace.mode='markers+lines' trace.line.color='rgba(222,222,220,0.1)' else: tog_w.icon = 'toggle-off' with fig.batch_animate(): if rd_btn.value == 'DOS': for trace in fig.data: trace.fill=None else: for trace in fig.data[:1]: trace.mode='lines' trace.line.width=1.5 trace.line.color='skyblue' # Cell def generate_summary(paths_list=None): # Make Data Frame result_paths = [] common_prefix = '' #placeholder if paths_list: common_prefix = os.path.commonprefix(paths_list) for item in paths_list: if item and os.path.isdir(item): result_paths.append(os.path.join(item,'result.json')) elif item and os.path.isfile(item): result_paths.append(os.path.join(os.path.split(item)[0],'result.json')) result_dicts = [] for path in result_paths: try: _p_ = os.path.split(path)[0].split(common_prefix)[1] except: _p_ = '' #In current directory try: with open(path,'r') as f: l_d = json.load(f) l_d.update({'rel_path':_p_}) result_dicts.append(l_d) except: pass out_dict = {} # placeholder if result_dicts: out_dict.update({k:[v] if v!='' else [np.nan] for k,v in result_dicts[0].items()}) for i,d in enumerate(result_dicts): if i != 0: for k,v in d.items(): v = np.nan if v=='' else v try: out_dict[k].append(v) except: out_dict.update({k:[np.nan for l in range(i)]}) #if not key before, add to all previous out_dict[k].append(v) # Then append for current value # If next dictionary does not have key for k in out_dict.keys(): if k not in d.keys(): out_dict[k].append(np.nan) try: out_dict.pop('Fermi',None) # Remove Fermi as not necessary except: pass df = pd.DataFrame(out_dict) if common_prefix: return df.style.set_caption("Root Path: {}".format(common_prefix)) # return with header return df #return simple # Cell class VasprunApp: """ Display a GUI for vasp output analysis. `self.theme_colors` can be used to edit custom theme. - **Usage Example** ```python import pivotpy as pp va = pp.VasprunApp() va.cache_data = False #Turn off cache globally. va.evr_kws['elim'] = [-2,2] #Only Bands in this range will be included. Global accross project, can change anytime. va.evr_kws['try_pwsh'] = False #Defult is True. Tries to load Powershell exported data. va.ibands_kws['mode'] = 'bands' #Change graph mode from 'markers' to 'bands'. Setting it to 'lines' is not recommended in live graph, it could hang all UI. va.show() #Displays App and do work! va.theme_colors = pp.dark_colors #Set theme to dark externally and edit dictionary values to make your own theme va.splot(**kwargs) #Get matplotlib plot of current data. va.df #After you do some analysis and hit `Project Summary` button, get DataFrame. va.fig #Get current fig in Notebook cell. ``` """ output = ipw.Output().add_class('output') def __init__(self,height=580): self.height = height tab = ipw.Tab(layout = ipw.Layout(min_height=f'{height}px', max_height='100vh', min_width='700px', max_width='100vw') ).add_class('marginless').add_class('borderless') # Main Tab try: for i,item in enumerate(['Home','Graphs','STD(out/err)']): tab.set_title(i,item) except: tab.titles = ['Home','Graphs','STD(out/err)'] self.main_class = 'custom-'+''.join(np.random.randint(9,size=(22,)).astype(str)) #Random class self.tab = tab.add_class(self.main_class) # Main layout self.data = None # Export vasprun object. self.__path = None # current path self.fig = go.FigureWidget() # plotly's figure widget self.fig.update_layout(autosize=True) self.df = None # Summary DataFrame self.result = {'sys':'','V':'','a':'','b':'','c':'','Fermi': None, 'VBM':'','CBM':'','so_max':'','so_min':''} # Table widget value self.files_gui,self.files_dd = get_files_gui(height=300) self.InGui = InputGui(height=None) self.input = {'E_Fermi':0} # Dictionary for input self.fig_gui = HBox() # Middle Tab self.theme_colors = light_colors.copy() # Avoid Modification # Permeannet Parameters self.idos_kws = dict(colormap='RGB',tdos_color=(0.5, 0.95, 0),linewidth=2,fill_area=True, spin='both',interp_nk={},title=None) self.ibands_kws = dict(mode='markers',skipk=None,max_width=6,title=None,interp_nk={}) self.evr_kws = dict(skipk=None,elim=[],try_pwsh = True) self.cache_data = True l_btn = ipw.Layout(width='max-content') self.buttons = {'load_data' : Button(description='Load Data',layout=l_btn,tooltip='Load and Cache Data'), 'load_graph': Button(description='Load Graph',layout=l_btn,tooltip='Create Graph'), 'confirm' : Button(description='Confirm Delete',layout=l_btn,icon='trash'), 'summary' : Button(description='Project Summary',layout=l_btn,tootltip='Make DataFrame'), 'expand' : Button(icon = "fa-expand",layout=l_btn,tooltip='Expand Fig'), 'toggle' : Button(description='RGB',layout=l_btn,icon='toggle-on',tooltip='Toggle Colors'), 'save_fig' : Button(description='Save Fig',icon='download',layout=l_btn,tooltip='') } b_out = Layout(width='30%') en_options = ['Fermi','VBM','CBM','so_max','so_min','None'] self.dds = {'band_dos': Dropdown(options=['Bands','DOS'],value='Bands', layout= Layout(width='80px')), 'en_type' : Dropdown(options = en_options,value='None',layout=b_out), 'cache' : Dropdown(options=['Table Data','PWD Cache','All Cache','None'], value='None',layout=b_out), 'theme' : Dropdown(options=['Default','Light','Dark','Custom'], value='Default',layout=l_btn), 'style' : Dropdown(options=["plotly", "plotly_white", "plotly_dark", "ggplot2", "seaborn", "simple_white", "none"],layout=l_btn), } self.texts = {'kticks': Text(value='',layout=b_out,continuous_update=False), 'ktickv': Text(value='',layout=b_out,continuous_update=False), 'kjoin' : Text(value='',layout=b_out,continuous_update=False), 'elim' : Text(value='',layout=b_out,continuous_update=False), 'fermi' : Text(value='',layout=b_out,continuous_update=False), 'xyt' : Text(value='',continuous_update=False) } self.htmls = {'theme': ipw.HTML(css_style(light_colors,_class = self.main_class)), 'table': ipw.HTML()} # Observing self.InGui.html.observe(self.__update_input,"value") self.dds['band_dos'].observe(self.__update_input,"value") self.texts['fermi'].observe(self.__update_input,"value") self.texts['kjoin'].observe(self.__update_input,"value") self.texts['kticks'].observe(self.__update_xyt,"value") self.texts['ktickv'].observe(self.__update_xyt,"value") self.texts['elim'].observe(self.__update_xyt,"value") self.texts['xyt'].observe(self.__update_xyt) self.dds['theme'].observe(self.__update_theme,"value") self.dds['style'].observe(self.__update_plot_style,"value") self.files_dd.observe(self.__load_previous,"value") self.buttons['load_data'].on_click(self.__on_load) self.dds['band_dos'].observe(self.__figure_tab,"value") self.files_dd.observe(self.__update_table,'value') self.buttons['load_data'].observe(self.__update_table,'value') self.buttons['summary'].on_click(self.__df_out) self.buttons['confirm'].on_click(self.__deleter) self.buttons['toggle'].on_click(self.__tog_b) self.buttons['save_fig'].on_click(self.__save_connected) self.buttons['expand'].on_click(self.__expand_fig) self.buttons['load_graph'].on_click(self.__update_graph) self.dds['en_type'].observe(self.__update_table,"value") # This works from _click_data # Build Layout self.__build() def set_theme_colors(self,theme_colors): "Get self.theme_colors and after edit set back" if 'dds' in self.__dict__.keys(): self.dds['theme'].value = 'Custom' if 'htmls' in self.__dict__.keys(): self.htmls['theme'].value = css_style(theme_colors) def __figure_tab(self,change): l_out = Layout(width='20%') cache_box = HBox([Label('Delete Cache:'),self.dds['cache'],self.buttons['confirm']] ).add_class('marginless') upper_box = VBox([ HBox([Label('File:',layout=Layout(width='50px')),self.files_dd ]).add_class('borderless').add_class('marginless'), HBox([Label('View:',layout=Layout(width='50px')), self.dds['band_dos'],self.buttons['load_data'] ]).add_class('borderless').add_class('marginless') ]).add_class('marginless').add_class('borderless') points_box = HBox([Box([Label('E Type:',layout=l_out), self.dds['en_type'], Label('E-Fermi:',layout=l_out), self.texts['fermi'] ]).add_class('marginless').add_class('borderless'), self.buttons['load_graph'] ],layout=Layout(width='100%')).add_class('marginless') in_box = VBox([self.InGui.box, ]).add_class('marginless').add_class('borderless') top_right = HBox([self.buttons['load_graph'], Label('Style:'), self.dds['style'], Label('Theme:'), self.dds['theme'], self.buttons['expand'] ]).add_class('marginless') fig_box = Box([self.fig],layout=Layout(min_height='380px')).add_class('marginless') right_box = VBox([top_right,fig_box,self.htmls['table'] ],layout=Layout(min_width='60%')).add_class('marginless').add_class('borderless') if 'Bands' in self.dds['band_dos'].value: in_box.children = [Label('---------- Projections ----------'),self.InGui.box, Label('---- Other Arguments/Options ----'), VBox([HBox([Label('Ticks At: ',layout=l_out), self.texts['kticks'], Label('Labels: ',layout=l_out), self.texts['ktickv'] ]).add_class('borderless').add_class('marginless'), HBox([Label('Join At: ',layout=l_out), self.texts['kjoin'], Label('E Range: ',layout=l_out), self.texts['elim'] ]).add_class('marginless').add_class('borderless') ]).add_class('marginless')] right_box.children = [top_right,fig_box,points_box] self.buttons['toggle'].description = 'RGB' else: in_box.children = [Label('---------- Projections ----------'),self.InGui.box, Label('---- Other Arguments/Options ----'), HBox([Label('E Range:',layout=l_out), self.texts['elim'], Label('E-Fermi:',layout=l_out), self.texts['fermi'] ]).add_class('marginless')] right_box.children = [top_right,fig_box,points_box] self.dds['en_type'].value = 'None' # no scatter collection in DOS. self.buttons['toggle'].description = 'Fill' left_box = VBox([upper_box, in_box, HBox([Label('X, Y, Title'),self.texts['xyt']]).add_class('borderless'), HBox([Label('Options:'),self.buttons['summary'],self.buttons['save_fig'],self.buttons['toggle']]), cache_box, self.htmls['table']],layout=Layout(max_width='40%'), ).add_class('marginless').add_class('borderless') self.fig_gui.children = (left_box,right_box) self.buttons['load_graph'].icon = 'fa-refresh' return self.fig_gui # Return for use in show @output.capture() def __build(self): intro_html = ipw.HTML("<h2>Pivotpy</h2><p>Filter files here and switch tab to Graphs. You can create cache ahead of time to load quickly while working. If anything does not seem to work, see the error in STD(out/err) tab. For large files, do `Export-VaspRun` in Powershell to access fast. <a href=https://massgh.github.io/pivotpy/Widgets.html#VasprunApp target='_blank'>See More</a></p><marquee style='color:blue'>Pivotpy GUI based on ipywidgets!</marquee>") header_box = HBox([intro_html, Label('Theme:',layout=Layout(width='80px')), self.dds['theme'] ]).add_class('marginless').add_class('borderless') summary_gui = HBox([ipw.Label(), self.buttons['summary']] ).add_class('borderless') intro_box = VBox([self.htmls['theme'], header_box, self.files_gui, summary_gui] ).add_class('marginless').add_class('borderless').add_class('marginless') self.fig_gui = self.__figure_tab(1) #Start self.tab.children = (intro_box, self.fig_gui, VBox([HBox([ipw.HTML("<h3>Functions Logging/Output</h3>"), Box([ Label('Theme:',layout=Layout(width='80px')), self.dds['theme']],layout=Layout(left='50%')).add_class('borderless') ]).add_class('borderless').add_class('marginless'), VasprunApp.output]) ) self.dds['style'].value = 'plotly' # to trigger first callback on graph. self.app = self.tab #Need to access it self.__update_theme(True) #Good option in jupyterlab for following theme. def show(self): return display(self.tab) def __fill_ticks(self): kpath = os.path.join(os.path.split(self.files_dd.value)[0],'KPOINTS') tvs = sio.read_ticks(kpath) #ticks values segments if tvs['ktick_inds']: #If is must, if not present, avoid overwritting custom input self.texts['kticks'].value = ','.join([str(v) for v in tvs['ktick_inds']]) if tvs['ktick_vals']: self.texts['ktickv'].value = ','.join(tvs['ktick_vals']) if tvs['kseg_inds']: self.texts['kjoin'].value = ','.join([str(v) for v in tvs['kseg_inds']]) def __update_theme(self,change): if self.dds['theme'].value == 'Dark': self.htmls['theme'].value = css_style(dark_colors,_class=self.main_class) self.fig.update_layout(template='plotly_dark') self.dds['style'].value = 'plotly_dark' elif self.dds['theme'].value == 'Light': self.htmls['theme'].value = css_style(light_colors,_class=self.main_class) self.fig.update_layout(template='ggplot2') self.dds['style'].value = 'ggplot2' elif self.dds['theme'].value == 'Custom': self.htmls['theme'].value = css_style(simple_colors,_class=self.main_class) self.fig.update_layout(template='none') self.dds['style'].value = 'none' else: self.htmls['theme'].value = css_style(default_colors,_class=self.main_class) self.fig.update_layout(template='plotly') self.dds['style'].value = 'plotly' def __update_plot_style(self,change): self.fig.update_layout(template = self.dds['style'].value) @output.capture(clear_output=True,wait=True) def __load_previous(self,change): path = self.files_dd.value try: _dir = os.path.split(path)[0] r_f = os.path.join(_dir,'result.json') self.result = vp.load_from_dump(r_f,keep_as_dict=True) print('Previous Analysis loaded in Table for {}'.format(path)) except: print('Previous Analysis does not exist for {}'.format(path)) @output.capture(clear_output=True,wait=True) def __read_data(self,poscar=None,sys_info=None): if sys_info != None: self.result["sys"] = sys_info.SYSTEM if poscar != None: self.result["V"] = np.round(poscar.volume,5) a,b,c = np.round(np.linalg.norm(poscar.basis,axis=1),5) self.result["a"] = a self.result["b"] = b self.result["c"] = c @output.capture(clear_output=True,wait=True) def __on_load(self,button): self.__fill_ticks() # First fill ticks, then update input self.__update_input(change=None) # Fix input right here. self.__load_previous(change=button) # previous calculations. self.tab.selected_index = 2 self.buttons['load_data'].description='Loading ...' _dir = os.path.split(self.files_dd.value)[0] # directory try: sys_info = vp.load_from_dump(os.path.join(_dir,'sys_info.pickle')) self.data = vp.load_from_dump(os.path.join(_dir,'vasprun.pickle')) print('Cache Loaded') except: print('Trying Loading from Python ...') self.data = vp.export_vasprun(self.files_dd.value, **self.evr_kws) if self.cache_data: print('Caching From: {}'.format(self.files_dd.value)) #Cache result vp.dump_dict(self.data.sys_info,outfile=os.path.join(_dir,'sys_info.pickle')) vp.dump_dict(self.data,outfile=os.path.join(_dir,'vasprun.pickle')) sys_info = self.data.sys_info # required here. print('Done') _ = self.__read_data(self.data.poscar,sys_info) # Update Table data on load self.texts['fermi'].value = str(sys_info.E_Fermi) # Needs each time new data loads up. self.tab.selected_index = 1 # Revamp input dropdowns on load ========== self.InGui.update_options(sys_info=sys_info) #Upadate elements/orbs/labels #=========================================== self.buttons['load_data'].description='Load Data' self.__path = self.files_dd.value # Update in __on_load or graph to make sure data loads once self.buttons['load_data'].tooltip = "Current System\n{!r}".format(self.data.sys_info) self.buttons['load_graph'].icon = 'fa-refresh' @output.capture(clear_output=True,wait=True) def __update_input(self,change): self.input.update(self.InGui.output) elim_str = [v for v in self.texts['elim'].value.split(',') if v!=''] fermi_str = self.texts['fermi'].value self.input['E_Fermi'] = float(fermi_str) if fermi_str else 0 # Change now, keep zero else must. self.input['elim'] = [float(v) for v in elim_str if v!='-'][:2] if len(elim_str) >= 2 else None if self.dds['band_dos'].value == 'Bands': kjoin_str = [v for v in self.texts['kjoin'].value.split(',') if v!=''] kticks_str = [v for v in self.texts['kticks'].value.split(',') if v!=''] ktickv_str = [v for v in self.texts['ktickv'].value.split(',') if v!=''] self.input['kseg_inds'] = [int(v) for v in kjoin_str if v!='-'] if kjoin_str else None self.input['ktick_inds'] = [int(v) for v in kticks_str if v!='-'] if kticks_str else [0,-1] self.input['ktick_vals'] = [v for v in ktickv_str if v!=''] if ktickv_str else ['A','B'] else: self.input = {k:v for k,v in self.input.items() if k not in ['ktick_inds','ktick_vals','kseg_inds']} #Update at last self.InGui.output = self.input self.buttons['load_graph'].tooltip = "Current Input\n{!r}".format(vp.Dict2Data(self.input)) self.buttons['load_graph'].icon = 'fa-refresh' @output.capture(clear_output=True,wait=True) def __update_table(self,change): self.htmls['table'].value = _tabulate_data(self.result) _save_data(self.files_dd,self.result) # save data as well. @output.capture(clear_output=True,wait=True) def __df_out(self,btn): self.tab.selected_index = 2 self.buttons['summary'].description = 'See STD(out/err) Tab' paths = [v for (k,v) in self.files_dd.options] df = generate_summary(paths_list=paths) display(df) self.df = df # Assign print('Get above DataFrame by app_name.df\nNote: app_name is variable name assigned to VasprunApp()') print('==================== OR =========================') _code = "import pivotpy as pp\npaths = ['{}']\ndf = pp.generate_summary(paths_list=paths)\ndf".format("',\n '".join([str(p).replace('\\','/') for p in paths])) _code += "\n#ax = pp.init_figure()\n#df.plot(ax=ax,x='sys',y=['V','a'])" display(Markdown("```python\n{}\n```".format(_code))) self.buttons['summary'].description = 'Project Summary' @output.capture(clear_output=True,wait=True) def __deleter(self,btn): self.buttons['confirm'].description = 'Deleting ...' if self.files_dd.value: print('Deleting Selected Cache...') self.__clear_cache() # Deleting print('Done') self.__update_table(1) #Update when delete data self.buttons['confirm'].description='Confirm Delete' @output.capture(clear_output=True,wait=True) def __update_xyt(self,change): if self.texts['xyt'].value: xyt_text = self.texts['xyt'].value.split(',') try: self.fig.update_xaxes(title=xyt_text[0]) self.fig.update_yaxes(title=xyt_text[1]) self.fig.update_layout(title=xyt_text[2]) except: pass #do nothing else if self.texts['ktickv'].value or self.texts['kticks'].value or self.texts['elim'].value: self.__update_input(change=None) if self.dds['band_dos'].value == 'Bands' and self.data: tickvals = [self.data.kpath[i] for i in self.input['ktick_inds']] self.fig.update_xaxes(ticktext=self.input['ktick_vals'], tickvals=tickvals) if self.texts['elim'].value and self.input['elim'] != None and len(self.input['elim']) == 2: if self.dds['band_dos'].value == 'Bands': self.fig.update_yaxes(range = self.input['elim']) else: self.fig.update_xaxes(range = self.input['elim']) @output.capture(clear_output=True,wait=True) def __tog_b(self,tog_w): _color_toggle(self.buttons['toggle'],self.fig,self.dds['band_dos']) @output.capture(clear_output=True,wait=True) def __save_connected(self,btn): s_p = os.path.split(self.files_dd.value)[0] filename = os.path.join(s_p,'ConnectedFig.html') filename = gu.prevent_overwrite(filename) self.buttons['save_fig'].description = 'Saving...' views = VBox([self.htmls['theme'],self.fig,self.htmls['table']], layout=Layout(width='500px',height='490px')).add_class('borderless') embed_minimal_html(filename, views=[views], state=dependency_state([views])) self.buttons['save_fig'].description = 'Save Fig' self.buttons['save_fig'].tooltip = 'Recently Saved\n{!r}'.format(filename) @output.capture(clear_output=True,wait=True) def __expand_fig(self,btn): self.tab.selected_index = 2 self.dds['en_type'].value = 'None' # To avoid accidental clicks display(self.fig) # Garph @output.capture(clear_output=True,wait=True) def __update_graph(self,btn): path = self.files_dd.value if path: self.__fill_ticks() # First fill ticks, then update input self.__update_input(change=None) # Update input here as well self.tab.selected_index = 2 self.fig.data = [] if self.data and path == self.__path: # Same load and data exists, heeps in fast print('Data already loaded') else: try: self.buttons['load_graph'].description = 'Loading pickle...' print('Trying to Load Cache for Graph ...') file = os.path.join(os.path.split(path)[0],'vasprun.pickle') self.buttons['load_graph'].description = file self.data = vp.load_from_dump(file) self.buttons['load_graph'].description = 'Load Graph' except: self.buttons['load_graph'].description = 'Loading export...' print('No cache found. Loading from file {} ...'.format(path)) self.data = vp.export_vasprun(path, **self.evr_kws) self.buttons['load_graph'].description = "Load Graph" print('Done') self.__path = self.files_dd.value #update here or __on_load. Useful to match things self.buttons['load_graph'].description = 'Load Graph' _ = self.__read_data(self.data.poscar,self.data.sys_info) # Update Table data # Do Not Read Fermi, its 0 or given by user if self.dds['band_dos'].value == 'Bands': fig_data = ip.iplot_rgb_lines(path_evr=self.data,**self.input,**self.ibands_kws) else: self.dds['en_type'].value = 'None' # Avoid random clicks fig_data = ip.iplot_dos_lines(path_evr=self.data,**self.input,**self.idos_kws) # input auto-modified self.tab.selected_index = 1 with self.fig.batch_animate(): for d in fig_data.data: self.fig.add_trace(d) fig_data.layout.template = self.dds['style'].value # before layout to avoid color blink self.fig.layout = fig_data.layout _click_data(self.dds['en_type'],self.texts['fermi'],self.result,self.fig,self.dds['band_dos']) self.buttons['load_graph'].icon = 'fa-check' @output.capture(clear_output=True,wait=True) def __clear_cache(self): self.tab.selected_index = 2 _dir = os.path.split(self.files_dd.value)[0] if 'Table' in self.dds['cache'].value: for k in self.result.keys(): # Avoid deleting V,a,b,Fermi if k not in ['sys','V','a','b','c','Fermi']: self.result[k] = '' if 'PWD' in self.dds['cache'].value: _files = [os.path.join(_dir,f) for f in ['sys_info.pickle','vasprun.pickle']] _ = [[print("Deleting", _file),os.remove(_file)] for _file in _files if os.path.isfile(_file)] if 'All' in self.dds['cache'].value: for (key, value) in self.files_dd.options: _dir = os.path.split(value)[0] _files = [os.path.join(_dir,f) for f in ['sys_info.pickle','vasprun.pickle']] _ = [[print("Deleting", _file),os.remove(_file)] for _file in _files if os.path.isfile(_file)] self.tab.selected_index = 1 def iplot(self,**kwargs): "Returns a detached interactive Figure. `kwargs` are passed to `iplot_rgb_lines` or `iplot_dos_lines` based on current figure. `kwargs` should exclude whatever inside `self.input` and `path_evr`" kwargs = {k:v for k,v in kwargs.items() if k not in self.input.keys() or k!='path_evr'} if self.dds['band_dos'].value == 'Bands': return ip.iplot_rgb_lines(path_evr=self.data,**self.input,**kwargs) else: return ip.iplot_dos_lines(path_evr=self.data,**self.input,**kwargs) def splot(self,**kwargs): "Returns matplotlib Axes.`kwargs` are passed to `splot_rgb_lines` or `splot_dos_lines` based on current figure. `kwargs` should exclude whatever inside `self.input` and `path_evr`" kwargs = {k:v for k,v in kwargs.items() if k not in self.input.keys() or k!='path_evr'} if self.dds['band_dos'].value == 'Bands': return sp.splot_rgb_lines(path_evr=self.data,**self.input,**kwargs) else: return sp.splot_dos_lines(path_evr=self.data,**self.input,**kwargs) # Cell class KPathApp: """View and trace path on BZ. - **Usage** > ka = KPathApp() > ka.show() #Display app > ka.splot() #get matplotlib figure """ output = ipw.Output().add_class('output') def __init__(self,path='POSCAR'): self.path = path self.files_gui, self.files_dd = get_files_gui(auto_fill='POSCAR') self.files_dd.layout.width = '50%' self.main_class = 'custom-'+''.join(np.random.randint(9,size=(21,)).astype(str)) #Random class self.tab = ipw.Tab(children=[self.files_gui,Box([]),KPathApp.output]).add_class(self.main_class) self.tab.add_class('marginless').add_class('borderless') self.tab.layout = Layout(width='100%',min_width='100%',height='450px',min_height='450px') try: for i,title in enumerate(['Home','Main','STDERR']): self.tab.set_title(i,title) except: self.tab.titles = ['Home','Main','STDERR'] self.app = self.tab self.fig = go.FigureWidget() self.fig.layout.template = 'plotly_white' #Forces to avoid colored patch in background self.bz = None self.kcsn = [] #KPOINTS, COORDS,SYMBOLS, N_per_interval and box symbol in dictionary per item self.buttons = {'delete':Button(description='Delete Selection'), 'add':Button(description='Add Point'), 'patch':Button(description='Split Path'), 'fig_up': Button(description='Update Figure'), 'theme': Button(description='Dark Theme')} self.sm = SelectMultiple(layout=Layout(width='100%')) self.texts = {'label':Text(description='Label, N',indent=False), 'kxyz':Text(description='kx, ky, kz',indent=False)} self.theme_html = ipw.HTML(css_style(light_colors,_class=self.main_class)) self.buttons['delete'].on_click(self.__delete) self.buttons['add'].on_click(self.__add) self.buttons['patch'].on_click(self.__add_patch) self.buttons['theme'].on_click(self.__toggle_theme) self.buttons['fig_up'].on_click(self.__update_fig) self.texts['label'].on_submit(self.__label) self.texts['kxyz'].on_submit(self.__manual_k) self.__update_fig() self.__build() @output.capture(clear_output=True,wait=True) def __toggle_theme(self,change): _style = '''<style>.widget-select-multiple>select {{ font-family: "Cascadia Code","Ubuntu Mono","SimSun-ExtB","Courier New"; background:{next_bg};border-radius:0;color:{accent};border:none; height:auto;min-height:160px;padding:5px;margin:0px;overflow:auto;}} .widget-select-multiple>select>option:hover, .widget-select-multiple>select>option:focus{{background:{hover_bg};}}</style>''' if self.buttons['theme'].description == 'Dark Theme': self.theme_html.value = css_style(dark_colors,_class = self.main_class) + _style.format(**dark_colors) self.fig.layout.template = 'plotly_dark' self.fig.layout.paper_bgcolor = dark_colors['main_bg'] #important self.buttons['theme'].description = 'Light Theme' else: self.theme_html.value = css_style(light_colors,_class=self.main_class) + _style.format(**light_colors) self.fig.layout.template = 'plotly_white' self.fig.layout.paper_bgcolor = light_colors['main_bg'] self.buttons['theme'].description = 'Dark Theme' @output.capture(clear_output=True,wait=True) def __manual_k(self,change): for i in self.sm.value: self.kcsn[i]['k'] = [float(v) for v in self.texts['kxyz'].value.split(',') if v != ''][:3] self.texts['kxyz'].value = '' # clean it self.__update_label() self.__update_selection() #Change on graph too def __label_at(self,i): self.kcsn[0]['b'], self.kcsn[-1]['b'] = '┌', '└' #Avoid clashes _ln_ = f"─ {self.kcsn[i]['n']}" if self.kcsn[i]['n'] and i < (len(self.sm.options) - 1) else "" if self.kcsn[i]['k']: return "{0} {1} {2:>8.4f}{3:>8.4f}{4:>8.4f} {5}".format(self.kcsn[i]['b'],self.kcsn[i]['s'],*self.kcsn[i]['k'],_ln_) return f"{self.kcsn[i]['b']} {self.kcsn[i]['s']} {_ln_}" def __update_label(self): opt = list(self.sm.options) vs = self.sm.value # get before it goes away for i in vs: opt[i] = (self.__label_at(i),i) self.sm.options = tuple(opt) if vs[-1:]: try: self.sm.value = (vs[-1] + 1,) except:pass @output.capture(clear_output=True,wait=True) def __build(self): for k,b in self.buttons.items(): b.layout.width = 'max-content' for k,t in self.texts.items(): t.layout.width='85%' top_row = HBox([self.files_dd,self.buttons['fig_up']]).add_class('borderless') _buttons1 = HBox([self.buttons[b] for b in ['add','delete']]).add_class('borderless') _buttons2 = HBox([self.buttons[b] for b in ['patch','theme']]).add_class('borderless') self.tab.children = [self.tab.children[0], HBox([ VBox([self.theme_html, VBox([top_row,_buttons1,_buttons2], layout = Layout(min_height='140px')), Box([self.sm]).add_class('marginless').add_class('borderless'), *self.texts.values()], layout=Layout(min_width='320px')).add_class('borderless'), Box([self.fig]).add_class('borderless')], layout=Layout(height='400px',width='auto')).add_class('borderless'), self.tab.children[-1]] def show(self): return display(self.tab) @output.capture(clear_output=True,wait=True) def __delete(self,change): v = self.sm.value for i, kp in enumerate(self.kcsn): self.kcsn[i]['b'] = '├' #Break Path Retrieve first self.kcsn = [k for i,k in enumerate(self.kcsn) if i not in v] self.sm.options = [(self.__label_at(i),i) for i,op in enumerate(self.kcsn)] @output.capture(clear_output=True,wait=True) def __add(self,change): if self.kcsn: self.kcsn.append({'k':[],'c':[],'s':'','n':'', 'b': '└'}) else: self.kcsn.append({'k':[],'c':[],'s':'','n':'', 'b': '┌'}) for i, kp in enumerate(self.kcsn[1:-1]): self.kcsn[i+1]['b'] = '├' self.sm.options = [*self.sm.options,('You just added me',len(self.sm.options))] self.sm.value = (len(self.sm.options) - 1,) # make available @output.capture(clear_output=True,wait=True) def __add_patch(self,change): vs = [v for v in self.sm.value if v > 1 and v < len(self.sm.options) - 1] opts = list(self.sm.options) for i,v in enumerate(self.sm.options): # Clean previous action if i > 0 and i < len(opts) - 1: #Avoid end points self.kcsn[i]['b'] = '├' opts[i] = (self.__label_at(i),i) #Patch before selection if i in vs: self.kcsn[i]['b'] = '┌' self.kcsn[i-1]['b'] = '└' opts[i] = (self.__label_at(i),i) opts[i-1] = (self.__label_at(i-1),i-1) self.sm.options = opts self.__update_selection() @output.capture(clear_output=True,wait=True) def get_coords_labels(self): "`coords` are calculated for current `bz` even if `kpoints` were from other one. Useful in case of same kind of Zones with just basis changed." if self.bz: for i, kp in enumerate(self.kcsn): self.kcsn[i]['c'] = sio.to_R3(self.bz.basis,kp['k']).tolist() if kp['k'] else [] coords = [kp['c'] for kp in self.kcsn] labels = [kp['s'] for kp in self.kcsn] j = 0 for p in self.get_patches()[:-1]: labels.insert(p.stop+j,'NaN') coords.insert(p.stop+j,[np.nan,np.nan,np.nan]) j += 1 coords = np.array([c for c in coords if c]) labels = [l for l in labels if l] return coords,labels @output.capture(clear_output=True,wait=True) def __update_selection(self): coords,labels = self.get_coords_labels() with self.fig.batch_animate(): for trace in self.fig.data: if 'path' in trace.name and coords.any(): trace.x = coords[:,0] trace.y = coords[:,1] trace.z = coords[:,2] trace.text = labels @output.capture(clear_output=True,wait=True) def __click(self): def handle_click(trace, points, state): if points.ys != []: index = points.point_inds[0] kp = trace.hovertext[index] kp = [float(k) for k in kp.split('[')[1].split(']')[0].split()] cp = [trace.x[index],trace.y[index],trace.z[index]] for i in self.sm.value: self.kcsn[i]['k'] = kp self.kcsn[i]['c'] = cp self.__update_label() self.__update_selection() for trace in self.fig.data: if 'HSK' in trace.name: trace.on_click(handle_click) @output.capture(clear_output=True,wait=True) def __update_fig(self,change=None): if self.files_dd.value: self.path = self.files_dd.value self.bz = sio.get_bz(self.path) fig_data = sio.iplot_bz(self.bz,fill=False,color='red',background='rgba(1,1,1,0)') self.fig.data = [] with self.fig.batch_animate(): self.fig.add_trace(go.Scatter3d(x = [],y = [],z = [], mode='lines+text+markers',name='path',text=[], textfont_size=18)) self.__update_selection() #Show previous path on current fig. for trace in fig_data.data: self.fig.add_trace(trace) self.fig.layout = fig_data.layout self.fig.layout.autosize=True self.fig.layout.scene.aspectmode = 'data' #very important self.__click() self.__toggle_theme(None) #Important to let text appear correctly @output.capture(clear_output=True,wait=True) def __label(self,change): for i in self.sm.value: inbox = self.texts['label'].value.split(',') self.kcsn[i]['s'] = 'Γ' if 'am' in inbox[0] else inbox[0] #fix gamma try: self.kcsn[i]['n'] = int(inbox[1]) except: pass self.texts['label'].value = '' # Clear it self.__update_label() self.__update_selection() def get_patches(self): bs = [kp['b'] for kp in self.kcsn] patches = [*[i for i,b in enumerate(bs) if '┌' in b],len(self.kcsn)] _patches = [range(i,j) for i,j in zip(patches[:-1],patches[1:])] if _patches and len(_patches) <= 1: return [] return _patches def get_data(self): obj = [{k:v for k,v in kp.items() if k != 'b'} for kp in self.kcsn] patches = self.get_patches() fmt_str = "{0:>16.10f}{1:>16.10f}{2:>16.10f} !{3} {4}" if patches: p_strs = ['\n'.join([fmt_str.format( *self.kcsn[p]['k'],self.kcsn[p]['s'],self.kcsn[p]['n'] ) for p in ps]) for ps in patches] return obj, '\n\n'.join(p_strs) else: return obj,'\n'.join([fmt_str.format(*kp['k'],kp['s'],kp['n']) for kp in self.kcsn]) def get_kpath(self,n=5,weight=None,ibzkpt=None,outfile=None): "See Docs of pp.str2kpath for details." kws = dict(n=n,weight=weight,ibzkpt=ibzkpt,outfile=outfile) _, k_str = self.get_data() return sio.str2kpath(k_str,**kws) def splot(self,**kwargs): "Same as `pp.splot_bz` except it also plots path on BZ. `kwargs` are passed to `pp.splot_bz`" ax = sio.splot_bz(path_pos_bz=self.path,**kwargs) coords,labels = self.get_coords_labels() plane = kwargs.get('plane',None) if plane != None and plane in 'xyzxzyx': ind = 'xyzxzyx'.index(plane) arr = [0,1,2,0,2,1,0] ix,iy = arr[ind],arr[ind+1] coords = coords[:,[ix,iy]] if coords.any(): #To avoid errors if not coords ax.plot(*coords.T,'-o',color='blue',lw=0.8) _ = [ax.text(*vs,lab) for vs,lab in zip(coords,labels) if lab!='NaN'] return ax def iplot(self): "Returns disconnected current plotly figure" return go.Figure(data=self.fig.data, layout=self.fig.layout)
from os import path from sys import argv from pynput import keyboard from pynput.keyboard import Controller from pynput.keyboard import Key from modules.audio_input import audioRecords from modules.search import SearchACT # default value if there is no **kwargs PATH_OF_SCRIPT = path.dirname(argv[0]) PATH_DICT_DATA = path.join(PATH_OF_SCRIPT, "_dict_data.pkl") # The key combination to check flag = False class keyboardCatcher(keyboard.Listener): """ Keyboard class inherit from keyboard.Listener Use to catch on special keyboard press """ def __init__(self, *args, **kwargs): super().__init__( on_press=self.on_press, on_release=self.on_release, *args, **kwargs ) self.SearchACT = kwargs.pop("SearchACT", SearchACT) self.contact = kwargs.pop("contact") self.audio = kwargs.pop("audio", audioRecords()) self.controller = Controller() def on_press(self, key): global flag # Use this to monitor event of keyboard pressing if key == keyboard.Key.esc: self.controller.press("e") self.controller.release("e") self.controller.press("x") self.controller.release("x") self.controller.press(Key.enter) self.controller.release(Key.enter) elif key == keyboard.Key.media_volume_up: if not flag: flag = True self.enter_audio_mode() def on_release(self, key): global flag # Use this when you want to Stop listener if key == keyboard.Key.esc: # Stop listener return False def enter_audio_mode(self): global flag # print("Try to say something!", flush=True) print("\nMicrophone >>> ", end="") response = self.audio.recognize_speech_from_microphone() if response["Success"] is True: input_text = response["prediction"] searchact = self.SearchACT(self.contact.DICT_MAPPING_DATA) print(input_text, flush=True) ls_persons = searchact.get_person(input_text) if ls_persons: for person in ls_persons: print("\n", ">" + "\t".join(person)) else: print(f'\n "{input_text}" not found. Retry or type "exit" to exit.') else: print(f'\n{response['error']}') print("Seach >>> ", end="", flush=True) flag = False def main(): KC = keyboardCatcher() KC.start() if __name__ == "__main__": main()
from os import path from sys import argv from pynput import keyboard from pynput.keyboard import Controller from pynput.keyboard import Key from modules.audio_input import audioRecords from modules.search import SearchACT # default value if there is no **kwargs PATH_OF_SCRIPT = path.dirname(argv[0]) PATH_DICT_DATA = path.join(PATH_OF_SCRIPT, "_dict_data.pkl") # The key combination to check flag = False class keyboardCatcher(keyboard.Listener): """ Keyboard class inherit from keyboard.Listener Use to catch on special keyboard press """ def __init__(self, *args, **kwargs): super().__init__( on_press=self.on_press, on_release=self.on_release, *args, **kwargs ) self.SearchACT = kwargs.pop("SearchACT", SearchACT) self.contact = kwargs.pop("contact") self.audio = kwargs.pop("audio", audioRecords()) self.controller = Controller() def on_press(self, key): global flag # Use this to monitor event of keyboard pressing if key == keyboard.Key.esc: self.controller.press("e") self.controller.release("e") self.controller.press("x") self.controller.release("x") self.controller.press(Key.enter) self.controller.release(Key.enter) elif key == keyboard.Key.media_volume_up: if not flag: flag = True self.enter_audio_mode() def on_release(self, key): global flag # Use this when you want to Stop listener if key == keyboard.Key.esc: # Stop listener return False def enter_audio_mode(self): global flag # print("Try to say something!", flush=True) print("\nMicrophone >>> ", end="") response = self.audio.recognize_speech_from_microphone() if response["Success"] is True: input_text = response["prediction"] searchact = self.SearchACT(self.contact.DICT_MAPPING_DATA) print(input_text, flush=True) ls_persons = searchact.get_person(input_text) if ls_persons: for person in ls_persons: print("\n", ">" + "\t".join(person)) else: print(f'\n "{input_text}" not found. Retry or type "exit" to exit.') else: print(f'\n{response["error"]}') print("Seach >>> ", end="", flush=True) flag = False def main(): KC = keyboardCatcher() KC.start() if __name__ == "__main__": main()
# https://github.com/checktheroads/hyperglass """ Imports configuration varibles from configuration files and returns default values if undefined. """ # Standard Imports import os import math import logging # Module Imports import toml import logzero from logzero import logger # Project Imports import hyperglass # Project Directories working_dir = os.path.dirname(os.path.abspath(__file__)) hyperglass_root = os.path.dirname(hyperglass.__file__) # TOML Imports config = toml.load(os.path.join(working_dir, "configuration.toml")) devices = toml.load(os.path.join(working_dir, "devices.toml")) def debug_state(): """Returns string for logzero log level""" state = config.get("debug", False) return state # Logzero Configuration if debug_state(): logzero.loglevel(logging.DEBUG) else: logzero.loglevel(logging.INFO) def blacklist(): """Returns list of subnets/IPs defined in blacklist.toml""" blacklist_config = config["blacklist"] return blacklist_config def requires_ipv6_cidr(nos): """Returns boolean for input NOS association with the NOS list defined in \ requires_ipv6_cidr.toml""" nos_list = config["requires_ipv6_cidr"] return bool(nos in nos_list) def networks(): """Returns dictionary of ASNs as keys, list of associated locations as values. Imported as a \ Jinja2 variable on the main page that populates the network/ASN select class.""" asn_dict = {} routers_list = devices["router"] for router_config in routers_list.values(): asn = router_config["asn"] if asn in asn_dict: asn_dict[asn].append(router_config["location"]) else: asn_dict[asn] = [router_config["location"]] return asn_dict def hostnames(): """Returns list of all router hostnames for input validation""" hostname_list = [] routers_list = devices["router"] for router in routers_list: hostname_list.append(router) return hostname_list def locations_list(): """Returns a dictionary of ASNs as keys, list of associated locations, router hostnames, and \ router display names as keys. Used by Flask to populate the /routers/<asn> route, which is \ ingested by a JS Ajax call to populate the list of locations associated with the selected \ network/ASN on the main page.""" networks_dict = {} routers_list = devices["router"] for router in routers_list: asn = routers_list[router]["asn"] if asn in networks_dict: networks_dict[asn].append( dict( location=routers_list[router]["location"], hostname=router, display_name=routers_list[router]["display_name"], ) ) else: networks_dict[asn] = [ dict( location=routers_list[router]["location"], hostname=router, display_name=routers_list[router]["display_name"], ) ] return networks_dict def codes(): """Reusable status code numbers""" code_dict = { # 200: renders standard display text "success": 200, # 405: Renders Bulma "warning" class notification with message text "warning": 405, # 415: Renders Bulma "danger" class notification with message text "danger": 415, # 504: Renders Bulma "danger" class notifiction, used for Ping/Traceroute errors "error": 504, } return code_dict def codes_reason(): """Reusable status code descriptions""" code_desc_dict = { "200": "Valid Query", "405": "Query Not Allowed", "415": "Query Invalid", "504": "Unable to reach Ping target", } return code_desc_dict def rest_list(): """Returns list of supported hyperglass API types""" rest = ["frr", "bird"] return rest def scrape_list(): """Returns list of configured network operating systems""" config_commands = toml.load(os.path.join(working_dir, "commands.toml")) scrape = [] for nos in config_commands: scrape.append(nos) return scrape def supported_nos(): """Combines scrape_list & rest_list for full list of supported network operating systems""" scrape = scrape_list() rest = rest_list() supported = scrape + rest return supported def command(nos): """Associates input NOS with matched commands defined in commands.toml""" config_commands = toml.load(os.path.join(working_dir, "commands.toml")) commands = None if nos in scrape_list(): commands = { "dual": config_commands[nos][0]["dual"], "ipv4": config_commands[nos][0]["ipv4"], "ipv6": config_commands[nos][0]["ipv6"], } return commands def credential(cred): """Associates input credential key name with configured credential username & password in \ devices.toml.""" c_list = devices["credential"] return dict(username=c_list[cred]["username"], password=c_list[cred]["password"]) def device(dev): """Associates input device key name with configured device attributes in devices.toml""" device_config = devices["router"][dev] return dict( address=device_config.get("address"), asn=device_config.get("asn"), src_addr_ipv4=device_config.get("src_addr_ipv4"), src_addr_ipv6=device_config.get("src_addr_ipv6"), credential=device_config.get("credential"), location=device_config.get("location"), display_name=device_config.get("display_name"), port=device_config.get("port"), type=device_config.get("type"), proxy=device_config.get("proxy"), ) def proxy(prx): """Associates input proxy key name with configured proxy attributes in devices.toml""" proxy_config = devices["proxy"][prx] return dict( address=proxy_config["address"], username=proxy_config["username"], password=proxy_config["password"], type=proxy_config["type"], ssh_command=proxy_config["ssh_command"], ) def params(): """Builds combined nested dictionary of all parameters defined in configuration.toml, and if \ undefined, uses a default value""" # pylint: disable=too-many-statements # Dear PyLint, this function is intended to be long AF, because hyperglass is inteded to be \ # customizable AF. It would also be silly AF to break this into multiple functions, and you'd \ # probably still complain. <3 -ML general = {} branding = {} features = {} messages = {} general["primary_asn"] = config["general"].get("primary_asn", "65000") general["org_name"] = config["general"].get("org_name", "The Company") general["google_analytics"] = config["general"].get("google_analytics", "") general["redis_host"] = config["general"].get( "redis_host", os.environ.get("REDIS_HOST", "localhost") ) general["redis_port"] = config["general"].get( "redis_port", os.environ.get("REDIS_PORT", 6379) ) features["rate_limit"] = config["features"]["rate_limit"] features["rate_limit"]["redis_id"] = config["features"]["rate_limit"].get( "redis_id", 1 ) features["rate_limit"]["query"] = config["features"]["rate_limit"]["query"] features["rate_limit"]["query"]["rate"] = config["features"]["rate_limit"][ "query" ].get("rate", 5) features["rate_limit"]["query"]["period"] = config["features"]["rate_limit"].get( "period", "minute" ) features["rate_limit"]["query"]["title"] = config["features"]["rate_limit"][ "query" ].get("title", "Query Limit Reached") features["rate_limit"]["query"]["message"] = config["features"]["rate_limit"][ "query" ].get( "message", f"""Query limit of {features["rate_limit"]["query"]["rate"]} per \ {features["rate_limit"]["query"]["period"]} reached. Please wait one minute and try \ again.""", ) features["rate_limit"]["query"]["button"] = config["features"]["rate_limit"][ "query" ].get("button", "Try Again") features["rate_limit"]["message"] = config["features"]["rate_limit"].get( "message", f"""Query limit of {features["rate_limit"]["query"]} per minute reached. \ Please wait one minute and try again.""", ) features["rate_limit"]["site"] = config["features"]["rate_limit"]["site"] features["rate_limit"]["site"]["rate"] = config["features"]["rate_limit"][ "site" ].get("rate", 60) features["rate_limit"]["site"]["period"] = config["features"]["rate_limit"][ "site" ].get("period", "minute") features["rate_limit"]["site"]["title"] = config["features"]["rate_limit"][ "site" ].get("title", "Limit Reached") features["rate_limit"]["site"]["subtitle"] = config["features"]["rate_limit"][ "site" ].get( "subtitle", f'You have accessed this site more than {features['rate_limit']['site']['rate']} ' f'times in the last {features['rate_limit']['site']['period']}.', ) features["rate_limit"]["site"]["button"] = config["features"]["rate_limit"][ "site" ].get("button", "Try Again") features["cache"] = config["features"]["cache"] features["cache"]["redis_id"] = config["features"]["cache"].get("redis_id", 0) features["cache"]["timeout"] = config["features"]["cache"].get("timeout", 120) features["cache"]["show_text"] = config["features"]["cache"].get("show_text", True) features["cache"]["text"] = config["features"]["cache"].get( "text", f'Results will be cached for {math.ceil(features['cache']['timeout'] / 60)} minutes.', ) features["bgp_route"] = config["features"]["bgp_route"] features["bgp_route"]["enable"] = config["features"]["bgp_route"].get( "enable", True ) features["bgp_community"] = config["features"]["bgp_community"] features["bgp_community"]["enable"] = config["features"]["bgp_community"].get( "enable", True ) features["bgp_community"]["regex"] = config["features"]["bgp_community"]["regex"] features["bgp_community"]["regex"]["decimal"] = config["features"]["bgp_community"][ "regex" ].get("decimal", r"^[0-9]{1,10}$") features["bgp_community"]["regex"]["extended_as"] = config["features"][ "bgp_community" ]["regex"].get("extended_as", r"^([0-9]{0,5})\:([0-9]{1,5})$") features["bgp_community"]["regex"]["large"] = config["features"]["bgp_community"][ "regex" ].get("large", r"^([0-9]{1,10})\:([0-9]{1,10})\:[0-9]{1,10}$") features["bgp_aspath"] = config["features"]["bgp_aspath"] features["bgp_aspath"]["enable"] = config["features"]["bgp_aspath"].get( "enable", True ) features["bgp_aspath"]["regex"] = config["features"]["bgp_aspath"]["regex"] features["bgp_aspath"]["regex"]["mode"] = config["features"]["bgp_aspath"][ "regex" ].get("mode", "asplain") features["bgp_aspath"]["regex"]["asplain"] = config["features"]["bgp_aspath"][ "regex" ].get("asplain", r"^(\^|^\_)(\d+\_|\d+\$|\d+\(\_\.\+\_\))+$") features["bgp_aspath"]["regex"]["asdot"] = config["features"]["bgp_aspath"][ "regex" ].get("asdot", r"^(\^|^\_)((\d+\.\d+)\_|(\d+\.\d+)\$|(\d+\.\d+)\(\_\.\+\_\))+$") features["bgp_aspath"]["regex"]["pattern"] = config["features"]["bgp_aspath"][ "regex" ].get(features["bgp_aspath"]["regex"]["mode"], None) features["ping"] = config["features"]["ping"] features["ping"]["enable"] = config["features"]["ping"].get("enable", True) features["traceroute"] = config["features"]["traceroute"] features["traceroute"]["enable"] = config["features"]["traceroute"].get( "enable", True ) features["max_prefix"] = config["features"]["max_prefix"] features["max_prefix"]["enable"] = config["features"]["max_prefix"].get( "enable", False ) features["max_prefix"]["ipv4"] = config["features"]["max_prefix"].get("ipv4", 24) features["max_prefix"]["ipv6"] = config["features"]["max_prefix"].get("ipv6", 64) features["max_prefix"]["message"] = config["features"]["max_prefix"].get( "message", "Prefix length must be smaller than /{m}. <b>{i}</b> is too specific.", ) messages["no_query_type"] = config["messages"].get( "no_query_type", "Query Type must be specified." ) messages["no_location"] = config["messages"].get( "no_location", "A location must be selected." ) messages["no_input"] = config["messages"].get( "no_input", "A target must be specified" ) messages["not_allowed"] = config["messages"].get( "not_allowed", "<b>{i}</b> is not allowed." ) messages["requires_ipv6_cidr"] = config["messages"].get( "requires_ipv6_cidr", "<b>{d}</b> requires IPv6 BGP lookups to be in CIDR notation.", ) messages["invalid_ip"] = config["messages"].get( "invalid_ip", "<b>{i}</b> is not a valid IP address." ) messages["invalid_dual"] = config["messages"].get( "invalid_dual", "<b>{i}</b> is an invalid {qt}." ) messages["general"] = config["messages"].get("general", "An error occurred.") messages["directed_cidr"] = config["messages"].get( "directed_cidr", "<b>{q}</b> queries can not be in CIDR format." ) branding["site_name"] = config["branding"].get("site_name", "hyperglass") branding["footer"] = config["branding"]["footer"] branding["footer"]["enable"] = config["branding"]["footer"].get("enable", True) branding["credit"] = config["branding"]["credit"] branding["credit"]["enable"] = config["branding"]["credit"].get("enable", True) branding["peering_db"] = config["branding"]["peering_db"] branding["peering_db"]["enable"] = config["branding"]["peering_db"].get( "enable", True ) branding["text"] = config["branding"]["text"] branding["text"]["query_type"] = config["branding"]["text"].get( "query_type", "Query Type" ) branding["text"]["title_mode"] = config["branding"]["text"].get( "title_mode", "logo_only" ) branding["text"]["title"] = config["branding"]["text"].get("title", "hyperglass") branding["text"]["subtitle"] = config["branding"]["text"].get( "subtitle", f'AS{general['primary_asn']}' ) branding["text"]["results"] = config["branding"]["text"].get("results", "Results") branding["text"]["location"] = config["branding"]["text"].get( "location", "Select Location..." ) branding["text"]["query_placeholder"] = config["branding"]["text"].get( "query_placeholder", "IP, Prefix, Community, or AS Path" ) branding["text"]["bgp_route"] = config["branding"]["text"].get( "bgp_route", "BGP Route" ) branding["text"]["bgp_community"] = config["branding"]["text"].get( "bgp_community", "BGP Community" ) branding["text"]["bgp_aspath"] = config["branding"]["text"].get( "bgp_aspath", "BGP AS Path" ) branding["text"]["ping"] = config["branding"]["text"].get("ping", "Ping") branding["text"]["traceroute"] = config["branding"]["text"].get( "traceroute", "Traceroute" ) branding["text"]["404"]["title"] = config["branding"]["text"]["404"].get( "title", "Error" ) branding["text"]["404"]["subtitle"] = config["branding"]["text"]["404"].get( "subtitle", "Page Not Found" ) branding["text"]["500"]["title"] = config["branding"]["text"]["500"].get( "title", "Error" ) branding["text"]["500"]["subtitle"] = config["branding"]["text"]["500"].get( "subtitle", "Something Went Wrong" ) branding["text"]["500"]["button"] = config["branding"]["text"]["500"].get( "button", "Home" ) branding["text"]["504"]["message"] = config["branding"]["text"]["504"].get( "message", "Unable to reach <b>{target}</b>." ) branding["logo"] = config["branding"]["logo"] branding["logo"]["path"] = config["branding"]["logo"].get( "path", "static/images/hyperglass-dark.png" ) branding["logo"]["width"] = config["branding"]["logo"].get("width", 384) branding["logo"]["favicons"] = config["branding"]["logo"].get( "favicons", "static/images/favicon/" ) branding["color"] = config["branding"]["color"] branding["color"]["background"] = config["branding"]["color"].get( "background", "#fbfffe" ) branding["color"]["button_submit"] = config["branding"]["color"].get( "button_submit", "#40798c" ) branding["color"]["danger"] = config["branding"]["color"].get("danger", "#ff3860") branding["color"]["progress_bar"] = config["branding"]["color"].get( "progress_bar", "#40798c" ) branding["color"]["tag"]["type"] = config["branding"]["color"]["tag"].get( "type", "#ff5e5b" ) branding["color"]["tag"]["type_title"] = config["branding"]["color"]["tag"].get( "type_title", "#330036" ) branding["color"]["tag"]["location"] = config["branding"]["color"]["tag"].get( "location", "#40798c" ) branding["color"]["tag"]["location_title"] = config["branding"]["color"]["tag"].get( "location_title", "#330036" ) branding["font"] = config["branding"]["font"] branding["font"]["primary"] = config["branding"]["font"]["primary"] branding["font"]["primary"]["name"] = config["branding"]["font"]["primary"].get( "name", "Nunito" ) branding["font"]["primary"]["url"] = config["branding"]["font"]["primary"].get( "url", "https://fonts.googleapis.com/css?family=Nunito:400,600,700" ) branding["font"]["mono"] = config["branding"]["font"]["mono"] branding["font"]["mono"]["name"] = config["branding"]["font"]["mono"].get( "name", "Fira Mono" ) branding["font"]["mono"]["url"] = config["branding"]["font"]["mono"].get( "url", "https://fonts.googleapis.com/css?family=Fira+Mono" ) branding["font"]["mono"]["size"] = config["branding"]["font"]["mono"].get( "size", "0.95em" ) params_dict = dict( general=general, branding=branding, features=features, messages=messages ) return params_dict
# https://github.com/checktheroads/hyperglass """ Imports configuration varibles from configuration files and returns default values if undefined. """ # Standard Imports import os import math import logging # Module Imports import toml import logzero from logzero import logger # Project Imports import hyperglass # Project Directories working_dir = os.path.dirname(os.path.abspath(__file__)) hyperglass_root = os.path.dirname(hyperglass.__file__) # TOML Imports config = toml.load(os.path.join(working_dir, "configuration.toml")) devices = toml.load(os.path.join(working_dir, "devices.toml")) def debug_state(): """Returns string for logzero log level""" state = config.get("debug", False) return state # Logzero Configuration if debug_state(): logzero.loglevel(logging.DEBUG) else: logzero.loglevel(logging.INFO) def blacklist(): """Returns list of subnets/IPs defined in blacklist.toml""" blacklist_config = config["blacklist"] return blacklist_config def requires_ipv6_cidr(nos): """Returns boolean for input NOS association with the NOS list defined in \ requires_ipv6_cidr.toml""" nos_list = config["requires_ipv6_cidr"] return bool(nos in nos_list) def networks(): """Returns dictionary of ASNs as keys, list of associated locations as values. Imported as a \ Jinja2 variable on the main page that populates the network/ASN select class.""" asn_dict = {} routers_list = devices["router"] for router_config in routers_list.values(): asn = router_config["asn"] if asn in asn_dict: asn_dict[asn].append(router_config["location"]) else: asn_dict[asn] = [router_config["location"]] return asn_dict def hostnames(): """Returns list of all router hostnames for input validation""" hostname_list = [] routers_list = devices["router"] for router in routers_list: hostname_list.append(router) return hostname_list def locations_list(): """Returns a dictionary of ASNs as keys, list of associated locations, router hostnames, and \ router display names as keys. Used by Flask to populate the /routers/<asn> route, which is \ ingested by a JS Ajax call to populate the list of locations associated with the selected \ network/ASN on the main page.""" networks_dict = {} routers_list = devices["router"] for router in routers_list: asn = routers_list[router]["asn"] if asn in networks_dict: networks_dict[asn].append( dict( location=routers_list[router]["location"], hostname=router, display_name=routers_list[router]["display_name"], ) ) else: networks_dict[asn] = [ dict( location=routers_list[router]["location"], hostname=router, display_name=routers_list[router]["display_name"], ) ] return networks_dict def codes(): """Reusable status code numbers""" code_dict = { # 200: renders standard display text "success": 200, # 405: Renders Bulma "warning" class notification with message text "warning": 405, # 415: Renders Bulma "danger" class notification with message text "danger": 415, # 504: Renders Bulma "danger" class notifiction, used for Ping/Traceroute errors "error": 504, } return code_dict def codes_reason(): """Reusable status code descriptions""" code_desc_dict = { "200": "Valid Query", "405": "Query Not Allowed", "415": "Query Invalid", "504": "Unable to reach Ping target", } return code_desc_dict def rest_list(): """Returns list of supported hyperglass API types""" rest = ["frr", "bird"] return rest def scrape_list(): """Returns list of configured network operating systems""" config_commands = toml.load(os.path.join(working_dir, "commands.toml")) scrape = [] for nos in config_commands: scrape.append(nos) return scrape def supported_nos(): """Combines scrape_list & rest_list for full list of supported network operating systems""" scrape = scrape_list() rest = rest_list() supported = scrape + rest return supported def command(nos): """Associates input NOS with matched commands defined in commands.toml""" config_commands = toml.load(os.path.join(working_dir, "commands.toml")) commands = None if nos in scrape_list(): commands = { "dual": config_commands[nos][0]["dual"], "ipv4": config_commands[nos][0]["ipv4"], "ipv6": config_commands[nos][0]["ipv6"], } return commands def credential(cred): """Associates input credential key name with configured credential username & password in \ devices.toml.""" c_list = devices["credential"] return dict(username=c_list[cred]["username"], password=c_list[cred]["password"]) def device(dev): """Associates input device key name with configured device attributes in devices.toml""" device_config = devices["router"][dev] return dict( address=device_config.get("address"), asn=device_config.get("asn"), src_addr_ipv4=device_config.get("src_addr_ipv4"), src_addr_ipv6=device_config.get("src_addr_ipv6"), credential=device_config.get("credential"), location=device_config.get("location"), display_name=device_config.get("display_name"), port=device_config.get("port"), type=device_config.get("type"), proxy=device_config.get("proxy"), ) def proxy(prx): """Associates input proxy key name with configured proxy attributes in devices.toml""" proxy_config = devices["proxy"][prx] return dict( address=proxy_config["address"], username=proxy_config["username"], password=proxy_config["password"], type=proxy_config["type"], ssh_command=proxy_config["ssh_command"], ) def params(): """Builds combined nested dictionary of all parameters defined in configuration.toml, and if \ undefined, uses a default value""" # pylint: disable=too-many-statements # Dear PyLint, this function is intended to be long AF, because hyperglass is inteded to be \ # customizable AF. It would also be silly AF to break this into multiple functions, and you'd \ # probably still complain. <3 -ML general = {} branding = {} features = {} messages = {} general["primary_asn"] = config["general"].get("primary_asn", "65000") general["org_name"] = config["general"].get("org_name", "The Company") general["google_analytics"] = config["general"].get("google_analytics", "") general["redis_host"] = config["general"].get( "redis_host", os.environ.get("REDIS_HOST", "localhost") ) general["redis_port"] = config["general"].get( "redis_port", os.environ.get("REDIS_PORT", 6379) ) features["rate_limit"] = config["features"]["rate_limit"] features["rate_limit"]["redis_id"] = config["features"]["rate_limit"].get( "redis_id", 1 ) features["rate_limit"]["query"] = config["features"]["rate_limit"]["query"] features["rate_limit"]["query"]["rate"] = config["features"]["rate_limit"][ "query" ].get("rate", 5) features["rate_limit"]["query"]["period"] = config["features"]["rate_limit"].get( "period", "minute" ) features["rate_limit"]["query"]["title"] = config["features"]["rate_limit"][ "query" ].get("title", "Query Limit Reached") features["rate_limit"]["query"]["message"] = config["features"]["rate_limit"][ "query" ].get( "message", f"""Query limit of {features["rate_limit"]["query"]["rate"]} per \ {features["rate_limit"]["query"]["period"]} reached. Please wait one minute and try \ again.""", ) features["rate_limit"]["query"]["button"] = config["features"]["rate_limit"][ "query" ].get("button", "Try Again") features["rate_limit"]["message"] = config["features"]["rate_limit"].get( "message", f"""Query limit of {features["rate_limit"]["query"]} per minute reached. \ Please wait one minute and try again.""", ) features["rate_limit"]["site"] = config["features"]["rate_limit"]["site"] features["rate_limit"]["site"]["rate"] = config["features"]["rate_limit"][ "site" ].get("rate", 60) features["rate_limit"]["site"]["period"] = config["features"]["rate_limit"][ "site" ].get("period", "minute") features["rate_limit"]["site"]["title"] = config["features"]["rate_limit"][ "site" ].get("title", "Limit Reached") features["rate_limit"]["site"]["subtitle"] = config["features"]["rate_limit"][ "site" ].get( "subtitle", f'You have accessed this site more than {features["rate_limit"]["site"]["rate"]} ' f'times in the last {features["rate_limit"]["site"]["period"]}.', ) features["rate_limit"]["site"]["button"] = config["features"]["rate_limit"][ "site" ].get("button", "Try Again") features["cache"] = config["features"]["cache"] features["cache"]["redis_id"] = config["features"]["cache"].get("redis_id", 0) features["cache"]["timeout"] = config["features"]["cache"].get("timeout", 120) features["cache"]["show_text"] = config["features"]["cache"].get("show_text", True) features["cache"]["text"] = config["features"]["cache"].get( "text", f'Results will be cached for {math.ceil(features["cache"]["timeout"] / 60)} minutes.', ) features["bgp_route"] = config["features"]["bgp_route"] features["bgp_route"]["enable"] = config["features"]["bgp_route"].get( "enable", True ) features["bgp_community"] = config["features"]["bgp_community"] features["bgp_community"]["enable"] = config["features"]["bgp_community"].get( "enable", True ) features["bgp_community"]["regex"] = config["features"]["bgp_community"]["regex"] features["bgp_community"]["regex"]["decimal"] = config["features"]["bgp_community"][ "regex" ].get("decimal", r"^[0-9]{1,10}$") features["bgp_community"]["regex"]["extended_as"] = config["features"][ "bgp_community" ]["regex"].get("extended_as", r"^([0-9]{0,5})\:([0-9]{1,5})$") features["bgp_community"]["regex"]["large"] = config["features"]["bgp_community"][ "regex" ].get("large", r"^([0-9]{1,10})\:([0-9]{1,10})\:[0-9]{1,10}$") features["bgp_aspath"] = config["features"]["bgp_aspath"] features["bgp_aspath"]["enable"] = config["features"]["bgp_aspath"].get( "enable", True ) features["bgp_aspath"]["regex"] = config["features"]["bgp_aspath"]["regex"] features["bgp_aspath"]["regex"]["mode"] = config["features"]["bgp_aspath"][ "regex" ].get("mode", "asplain") features["bgp_aspath"]["regex"]["asplain"] = config["features"]["bgp_aspath"][ "regex" ].get("asplain", r"^(\^|^\_)(\d+\_|\d+\$|\d+\(\_\.\+\_\))+$") features["bgp_aspath"]["regex"]["asdot"] = config["features"]["bgp_aspath"][ "regex" ].get("asdot", r"^(\^|^\_)((\d+\.\d+)\_|(\d+\.\d+)\$|(\d+\.\d+)\(\_\.\+\_\))+$") features["bgp_aspath"]["regex"]["pattern"] = config["features"]["bgp_aspath"][ "regex" ].get(features["bgp_aspath"]["regex"]["mode"], None) features["ping"] = config["features"]["ping"] features["ping"]["enable"] = config["features"]["ping"].get("enable", True) features["traceroute"] = config["features"]["traceroute"] features["traceroute"]["enable"] = config["features"]["traceroute"].get( "enable", True ) features["max_prefix"] = config["features"]["max_prefix"] features["max_prefix"]["enable"] = config["features"]["max_prefix"].get( "enable", False ) features["max_prefix"]["ipv4"] = config["features"]["max_prefix"].get("ipv4", 24) features["max_prefix"]["ipv6"] = config["features"]["max_prefix"].get("ipv6", 64) features["max_prefix"]["message"] = config["features"]["max_prefix"].get( "message", "Prefix length must be smaller than /{m}. <b>{i}</b> is too specific.", ) messages["no_query_type"] = config["messages"].get( "no_query_type", "Query Type must be specified." ) messages["no_location"] = config["messages"].get( "no_location", "A location must be selected." ) messages["no_input"] = config["messages"].get( "no_input", "A target must be specified" ) messages["not_allowed"] = config["messages"].get( "not_allowed", "<b>{i}</b> is not allowed." ) messages["requires_ipv6_cidr"] = config["messages"].get( "requires_ipv6_cidr", "<b>{d}</b> requires IPv6 BGP lookups to be in CIDR notation.", ) messages["invalid_ip"] = config["messages"].get( "invalid_ip", "<b>{i}</b> is not a valid IP address." ) messages["invalid_dual"] = config["messages"].get( "invalid_dual", "<b>{i}</b> is an invalid {qt}." ) messages["general"] = config["messages"].get("general", "An error occurred.") messages["directed_cidr"] = config["messages"].get( "directed_cidr", "<b>{q}</b> queries can not be in CIDR format." ) branding["site_name"] = config["branding"].get("site_name", "hyperglass") branding["footer"] = config["branding"]["footer"] branding["footer"]["enable"] = config["branding"]["footer"].get("enable", True) branding["credit"] = config["branding"]["credit"] branding["credit"]["enable"] = config["branding"]["credit"].get("enable", True) branding["peering_db"] = config["branding"]["peering_db"] branding["peering_db"]["enable"] = config["branding"]["peering_db"].get( "enable", True ) branding["text"] = config["branding"]["text"] branding["text"]["query_type"] = config["branding"]["text"].get( "query_type", "Query Type" ) branding["text"]["title_mode"] = config["branding"]["text"].get( "title_mode", "logo_only" ) branding["text"]["title"] = config["branding"]["text"].get("title", "hyperglass") branding["text"]["subtitle"] = config["branding"]["text"].get( "subtitle", f'AS{general["primary_asn"]}' ) branding["text"]["results"] = config["branding"]["text"].get("results", "Results") branding["text"]["location"] = config["branding"]["text"].get( "location", "Select Location..." ) branding["text"]["query_placeholder"] = config["branding"]["text"].get( "query_placeholder", "IP, Prefix, Community, or AS Path" ) branding["text"]["bgp_route"] = config["branding"]["text"].get( "bgp_route", "BGP Route" ) branding["text"]["bgp_community"] = config["branding"]["text"].get( "bgp_community", "BGP Community" ) branding["text"]["bgp_aspath"] = config["branding"]["text"].get( "bgp_aspath", "BGP AS Path" ) branding["text"]["ping"] = config["branding"]["text"].get("ping", "Ping") branding["text"]["traceroute"] = config["branding"]["text"].get( "traceroute", "Traceroute" ) branding["text"]["404"]["title"] = config["branding"]["text"]["404"].get( "title", "Error" ) branding["text"]["404"]["subtitle"] = config["branding"]["text"]["404"].get( "subtitle", "Page Not Found" ) branding["text"]["500"]["title"] = config["branding"]["text"]["500"].get( "title", "Error" ) branding["text"]["500"]["subtitle"] = config["branding"]["text"]["500"].get( "subtitle", "Something Went Wrong" ) branding["text"]["500"]["button"] = config["branding"]["text"]["500"].get( "button", "Home" ) branding["text"]["504"]["message"] = config["branding"]["text"]["504"].get( "message", "Unable to reach <b>{target}</b>." ) branding["logo"] = config["branding"]["logo"] branding["logo"]["path"] = config["branding"]["logo"].get( "path", "static/images/hyperglass-dark.png" ) branding["logo"]["width"] = config["branding"]["logo"].get("width", 384) branding["logo"]["favicons"] = config["branding"]["logo"].get( "favicons", "static/images/favicon/" ) branding["color"] = config["branding"]["color"] branding["color"]["background"] = config["branding"]["color"].get( "background", "#fbfffe" ) branding["color"]["button_submit"] = config["branding"]["color"].get( "button_submit", "#40798c" ) branding["color"]["danger"] = config["branding"]["color"].get("danger", "#ff3860") branding["color"]["progress_bar"] = config["branding"]["color"].get( "progress_bar", "#40798c" ) branding["color"]["tag"]["type"] = config["branding"]["color"]["tag"].get( "type", "#ff5e5b" ) branding["color"]["tag"]["type_title"] = config["branding"]["color"]["tag"].get( "type_title", "#330036" ) branding["color"]["tag"]["location"] = config["branding"]["color"]["tag"].get( "location", "#40798c" ) branding["color"]["tag"]["location_title"] = config["branding"]["color"]["tag"].get( "location_title", "#330036" ) branding["font"] = config["branding"]["font"] branding["font"]["primary"] = config["branding"]["font"]["primary"] branding["font"]["primary"]["name"] = config["branding"]["font"]["primary"].get( "name", "Nunito" ) branding["font"]["primary"]["url"] = config["branding"]["font"]["primary"].get( "url", "https://fonts.googleapis.com/css?family=Nunito:400,600,700" ) branding["font"]["mono"] = config["branding"]["font"]["mono"] branding["font"]["mono"]["name"] = config["branding"]["font"]["mono"].get( "name", "Fira Mono" ) branding["font"]["mono"]["url"] = config["branding"]["font"]["mono"].get( "url", "https://fonts.googleapis.com/css?family=Fira+Mono" ) branding["font"]["mono"]["size"] = config["branding"]["font"]["mono"].get( "size", "0.95em" ) params_dict = dict( general=general, branding=branding, features=features, messages=messages ) return params_dict
import random import string import traceback from tests.cephfs.cephfs_utilsV1 import FsUtils from utility.log import Log log = Log(__name__) def run(ceph_cluster, **kw): """ Pre-requisites : 1. create fs volume create cephfs and cephfs-ec Subvolume Group Operations : 1. ceph fs subvolumegroup create <vol_name> <group_name> 2. ceph fs subvolume create <vol_name> <subvol_name> [--size <size_in_bytes>] [--group_name <subvol_group_name>] 3. Mount subvolume on both fuse and kernel clients and run IO's 4. ceph fs subvolume resize <vol_name> <subvolume_name> <new_size> [--group_name <subvol_group>] 5. Mount subvolume on both fuse and kernel clients and run IO's 6. Validate the resize. Clean-up: 1. Remove files from mountpoint, Unmount subvolumes. 2. Remove the pools added as part of pool_layout 3. ceph fs subvolume rm <vol_name> <subvol_name> [--group_name <subvol_group_name>] 4. ceph fs subvolumegroup rm <vol_name> <group_name> """ try: fs_util = FsUtils(ceph_cluster) config = kw.get("config") build = config.get("build", config.get("rhbuild")) clients = ceph_cluster.get_ceph_objects("client") log.info("checking Pre-requisites") if len(clients) < 2: log.info( f"This test requires minimum 2 client nodes.This has only {len(clients)} clients" ) return 1 fs_util.prepare_clients(clients, build) fs_util.auth_list(clients) default_fs = "cephfs" if build.startswith("4"): # create EC pool list_cmds = [ "ceph fs flag set enable_multiple true", "ceph osd pool create cephfs-data-ec 64 erasure", "ceph osd pool create cephfs-metadata 64", "ceph osd pool set cephfs-data-ec allow_ec_overwrites true", "ceph fs new cephfs-ec cephfs-metadata cephfs-data-ec --force", ] if fs_util.get_fs_info(clients[0], "cephfs_new"): default_fs = "cephfs_new" list_cmds.append("ceph fs volume create cephfs") for cmd in list_cmds: clients[0].exec_command(sudo=True, cmd=cmd) log.info("Create SubVolumeGroups on each filesystem") subvolumegroup_list = [ {"vol_name": default_fs, "group_name": "subvolgroup_1"}, {"vol_name": "cephfs-ec", "group_name": "subvolgroup_ec1"}, ] for subvolumegroup in subvolumegroup_list: fs_util.create_subvolumegroup(clients[0], **subvolumegroup) log.info("Create 2 Sub volumes on each of the subvolume group with Size 2GB") subvolume_list = [ { "vol_name": default_fs, "subvol_name": "subvol_1", "group_name": "subvolgroup_1", "size": "2147483648", }, { "vol_name": default_fs, "subvol_name": "subvol_2", "group_name": "subvolgroup_1", "size": "2147483648", }, { "vol_name": "cephfs-ec", "subvol_name": "subvol_3", "group_name": "subvolgroup_ec1", "size": "2147483648", }, { "vol_name": "cephfs-ec", "subvol_name": "subvol_4", "group_name": "subvolgroup_ec1", "size": "2147483648", }, ] for subvolume in subvolume_list: fs_util.create_subvolume(clients[0], **subvolume) log.info("Validate the Subvolume Size") for subvolume in subvolume_list: subvolume_size_subvol = fs_util.get_subvolume_info( client=clients[0], **subvolume ) if int(subvolume.get("size", "infinite")) != int( subvolume_size_subvol["bytes_quota"] ): log.error( f"Size mismatchiing for {subvolume.get("subvol_name")} " f"Expected size is : {subvolume.get("size", "infinite")}" f"Actual Size: {subvolume_size_subvol["bytes_quota"]}" ) return 1 mounting_dir = "".join( random.choice(string.ascii_lowercase + string.digits) for _ in list(range(10)) ) log.info( "Mount 1 subvolumegroup/subvolume on kernel and 1 subvloume on Fuse → Client1" ) kernel_mounting_dir_1 = f"/mnt/cephfs_kernel{mounting_dir}_1/" mon_node_ips = fs_util.get_mon_node_ips() log.info("Get the path of sub volume") subvol_path, rc = clients[0].exec_command( sudo=True, cmd=f"ceph fs subvolume getpath {default_fs} subvol_1 subvolgroup_1", ) fs_util.kernel_mount( [clients[0]], kernel_mounting_dir_1, ",".join(mon_node_ips), sub_dir=f"{subvol_path.strip()}", ) subvol_path, rc = clients[0].exec_command( sudo=True, cmd=f"ceph fs subvolume getpath {default_fs} subvol_2 subvolgroup_1", ) fuse_mounting_dir_1 = f"/mnt/cephfs_fuse{mounting_dir}_1/" fs_util.fuse_mount( [clients[0]], fuse_mounting_dir_1, extra_params=f" -r {subvol_path.strip()}", ) log.info( "On EC,Mount 1 subvolumegroup/subvolume on kernal and 1 subvloume on Fuse → Client2" ) if build.startswith("5"): kernel_mounting_dir_2 = f"/mnt/cephfs_kernel{mounting_dir}_EC_1/" mon_node_ips = fs_util.get_mon_node_ips() log.info("Get the path of sub volume") subvol_path, rc = clients[1].exec_command( sudo=True, cmd="ceph fs subvolume getpath cephfs-ec subvol_3 subvolgroup_ec1", ) fs_util.kernel_mount( [clients[1]], kernel_mounting_dir_2, ",".join(mon_node_ips), sub_dir=f"{subvol_path.strip()}", extra_params=",fs=cephfs-ec", ) subvol_path, rc = clients[0].exec_command( sudo=True, cmd="ceph fs subvolume getpath cephfs-ec subvol_4 subvolgroup_ec1", ) fuse_mounting_dir_2 = f"/mnt/cephfs_fuse{mounting_dir}_EC_1/" fs_util.fuse_mount( [clients[1]], fuse_mounting_dir_2, extra_params=f" -r {subvol_path.strip()} --client_fs cephfs-ec", ) run_ios( clients[0], kernel_mounting_dir_1, file_name="dd_before", bs="100M", count=20, ) run_ios( clients[0], fuse_mounting_dir_1, file_name="dd_before", bs="100M", count=20 ) run_ios( clients[1], kernel_mounting_dir_2, file_name="dd_before", bs="100M", count=20, ) run_ios( clients[1], fuse_mounting_dir_2, file_name="dd_before", bs="100M", count=20 ) log.info("Resize the subvolumes to 5GB and add data more than 2GB") resize_subvolumes = [ f"ceph fs subvolume resize {default_fs} subvol_1 5368709120 --group_name subvolgroup_1", f"ceph fs subvolume resize {default_fs} subvol_2 5368709120 --group_name subvolgroup_1", "ceph fs subvolume resize cephfs-ec subvol_3 5368709120 --group_name subvolgroup_ec1", "ceph fs subvolume resize cephfs-ec subvol_4 5368709120 --group_name subvolgroup_ec1", ] for cmd in resize_subvolumes: clients[0].exec_command(sudo=True, cmd=cmd) log.info("Validate the Subvolume after Resize") for subvolume in subvolume_list: subvolume_size_subvol = fs_util.get_subvolume_info( client=clients[0], **subvolume ) if 5368709120 != int(subvolume_size_subvol["bytes_quota"]): log.error( f"Size mismatchiing for {subvolume.get("subvol_name")} Expected size is : 5368709120" f"Actual Size: {subvolume_size_subvol["bytes_quota"]}" ) return 1 run_ios( clients[0], kernel_mounting_dir_1, file_name="dd_after", bs="100M", count=30 ) run_ios( clients[0], fuse_mounting_dir_1, file_name="dd_after", bs="100M", count=30 ) run_ios( clients[1], kernel_mounting_dir_2, file_name="dd_after", bs="100M", count=30 ) run_ios( clients[1], fuse_mounting_dir_2, file_name="dd_after", bs="100M", count=30 ) log.info("Clean up the system") fs_util.client_clean_up( "umount", kernel_clients=[clients[0]], mounting_dir=kernel_mounting_dir_1 ) fs_util.client_clean_up( "umount", kernel_clients=[clients[1]], mounting_dir=kernel_mounting_dir_2 ) fs_util.client_clean_up( "umount", fuse_clients=[clients[0]], mounting_dir=fuse_mounting_dir_1 ) fs_util.client_clean_up( "umount", fuse_clients=[clients[1]], mounting_dir=fuse_mounting_dir_2 ) clients[1].exec_command( sudo=True, cmd="ceph config set mon mon_allow_pool_delete true" ) for subvolume in subvolume_list: fs_util.remove_subvolume(clients[0], **subvolume) for subvolumegroup in subvolumegroup_list: fs_util.remove_subvolumegroup(clients[0], **subvolumegroup) return 0 except Exception as e: log.error(e) log.error(traceback.format_exc()) return 1 def run_ios(client, mounting_dir, file_name, bs, count): client.exec_command( sudo=True, cmd=f"dd if=/dev/zero of={mounting_dir}{client.node.hostname}{file_name} bs={bs} " f"count={count}", )
import random import string import traceback from tests.cephfs.cephfs_utilsV1 import FsUtils from utility.log import Log log = Log(__name__) def run(ceph_cluster, **kw): """ Pre-requisites : 1. create fs volume create cephfs and cephfs-ec Subvolume Group Operations : 1. ceph fs subvolumegroup create <vol_name> <group_name> 2. ceph fs subvolume create <vol_name> <subvol_name> [--size <size_in_bytes>] [--group_name <subvol_group_name>] 3. Mount subvolume on both fuse and kernel clients and run IO's 4. ceph fs subvolume resize <vol_name> <subvolume_name> <new_size> [--group_name <subvol_group>] 5. Mount subvolume on both fuse and kernel clients and run IO's 6. Validate the resize. Clean-up: 1. Remove files from mountpoint, Unmount subvolumes. 2. Remove the pools added as part of pool_layout 3. ceph fs subvolume rm <vol_name> <subvol_name> [--group_name <subvol_group_name>] 4. ceph fs subvolumegroup rm <vol_name> <group_name> """ try: fs_util = FsUtils(ceph_cluster) config = kw.get("config") build = config.get("build", config.get("rhbuild")) clients = ceph_cluster.get_ceph_objects("client") log.info("checking Pre-requisites") if len(clients) < 2: log.info( f"This test requires minimum 2 client nodes.This has only {len(clients)} clients" ) return 1 fs_util.prepare_clients(clients, build) fs_util.auth_list(clients) default_fs = "cephfs" if build.startswith("4"): # create EC pool list_cmds = [ "ceph fs flag set enable_multiple true", "ceph osd pool create cephfs-data-ec 64 erasure", "ceph osd pool create cephfs-metadata 64", "ceph osd pool set cephfs-data-ec allow_ec_overwrites true", "ceph fs new cephfs-ec cephfs-metadata cephfs-data-ec --force", ] if fs_util.get_fs_info(clients[0], "cephfs_new"): default_fs = "cephfs_new" list_cmds.append("ceph fs volume create cephfs") for cmd in list_cmds: clients[0].exec_command(sudo=True, cmd=cmd) log.info("Create SubVolumeGroups on each filesystem") subvolumegroup_list = [ {"vol_name": default_fs, "group_name": "subvolgroup_1"}, {"vol_name": "cephfs-ec", "group_name": "subvolgroup_ec1"}, ] for subvolumegroup in subvolumegroup_list: fs_util.create_subvolumegroup(clients[0], **subvolumegroup) log.info("Create 2 Sub volumes on each of the subvolume group with Size 2GB") subvolume_list = [ { "vol_name": default_fs, "subvol_name": "subvol_1", "group_name": "subvolgroup_1", "size": "2147483648", }, { "vol_name": default_fs, "subvol_name": "subvol_2", "group_name": "subvolgroup_1", "size": "2147483648", }, { "vol_name": "cephfs-ec", "subvol_name": "subvol_3", "group_name": "subvolgroup_ec1", "size": "2147483648", }, { "vol_name": "cephfs-ec", "subvol_name": "subvol_4", "group_name": "subvolgroup_ec1", "size": "2147483648", }, ] for subvolume in subvolume_list: fs_util.create_subvolume(clients[0], **subvolume) log.info("Validate the Subvolume Size") for subvolume in subvolume_list: subvolume_size_subvol = fs_util.get_subvolume_info( client=clients[0], **subvolume ) if int(subvolume.get("size", "infinite")) != int( subvolume_size_subvol["bytes_quota"] ): log.error( f"Size mismatchiing for {subvolume.get('subvol_name')} " f"Expected size is : {subvolume.get('size', 'infinite')}" f"Actual Size: {subvolume_size_subvol['bytes_quota']}" ) return 1 mounting_dir = "".join( random.choice(string.ascii_lowercase + string.digits) for _ in list(range(10)) ) log.info( "Mount 1 subvolumegroup/subvolume on kernel and 1 subvloume on Fuse → Client1" ) kernel_mounting_dir_1 = f"/mnt/cephfs_kernel{mounting_dir}_1/" mon_node_ips = fs_util.get_mon_node_ips() log.info("Get the path of sub volume") subvol_path, rc = clients[0].exec_command( sudo=True, cmd=f"ceph fs subvolume getpath {default_fs} subvol_1 subvolgroup_1", ) fs_util.kernel_mount( [clients[0]], kernel_mounting_dir_1, ",".join(mon_node_ips), sub_dir=f"{subvol_path.strip()}", ) subvol_path, rc = clients[0].exec_command( sudo=True, cmd=f"ceph fs subvolume getpath {default_fs} subvol_2 subvolgroup_1", ) fuse_mounting_dir_1 = f"/mnt/cephfs_fuse{mounting_dir}_1/" fs_util.fuse_mount( [clients[0]], fuse_mounting_dir_1, extra_params=f" -r {subvol_path.strip()}", ) log.info( "On EC,Mount 1 subvolumegroup/subvolume on kernal and 1 subvloume on Fuse → Client2" ) if build.startswith("5"): kernel_mounting_dir_2 = f"/mnt/cephfs_kernel{mounting_dir}_EC_1/" mon_node_ips = fs_util.get_mon_node_ips() log.info("Get the path of sub volume") subvol_path, rc = clients[1].exec_command( sudo=True, cmd="ceph fs subvolume getpath cephfs-ec subvol_3 subvolgroup_ec1", ) fs_util.kernel_mount( [clients[1]], kernel_mounting_dir_2, ",".join(mon_node_ips), sub_dir=f"{subvol_path.strip()}", extra_params=",fs=cephfs-ec", ) subvol_path, rc = clients[0].exec_command( sudo=True, cmd="ceph fs subvolume getpath cephfs-ec subvol_4 subvolgroup_ec1", ) fuse_mounting_dir_2 = f"/mnt/cephfs_fuse{mounting_dir}_EC_1/" fs_util.fuse_mount( [clients[1]], fuse_mounting_dir_2, extra_params=f" -r {subvol_path.strip()} --client_fs cephfs-ec", ) run_ios( clients[0], kernel_mounting_dir_1, file_name="dd_before", bs="100M", count=20, ) run_ios( clients[0], fuse_mounting_dir_1, file_name="dd_before", bs="100M", count=20 ) run_ios( clients[1], kernel_mounting_dir_2, file_name="dd_before", bs="100M", count=20, ) run_ios( clients[1], fuse_mounting_dir_2, file_name="dd_before", bs="100M", count=20 ) log.info("Resize the subvolumes to 5GB and add data more than 2GB") resize_subvolumes = [ f"ceph fs subvolume resize {default_fs} subvol_1 5368709120 --group_name subvolgroup_1", f"ceph fs subvolume resize {default_fs} subvol_2 5368709120 --group_name subvolgroup_1", "ceph fs subvolume resize cephfs-ec subvol_3 5368709120 --group_name subvolgroup_ec1", "ceph fs subvolume resize cephfs-ec subvol_4 5368709120 --group_name subvolgroup_ec1", ] for cmd in resize_subvolumes: clients[0].exec_command(sudo=True, cmd=cmd) log.info("Validate the Subvolume after Resize") for subvolume in subvolume_list: subvolume_size_subvol = fs_util.get_subvolume_info( client=clients[0], **subvolume ) if 5368709120 != int(subvolume_size_subvol["bytes_quota"]): log.error( f"Size mismatchiing for {subvolume.get('subvol_name')} Expected size is : 5368709120" f"Actual Size: {subvolume_size_subvol['bytes_quota']}" ) return 1 run_ios( clients[0], kernel_mounting_dir_1, file_name="dd_after", bs="100M", count=30 ) run_ios( clients[0], fuse_mounting_dir_1, file_name="dd_after", bs="100M", count=30 ) run_ios( clients[1], kernel_mounting_dir_2, file_name="dd_after", bs="100M", count=30 ) run_ios( clients[1], fuse_mounting_dir_2, file_name="dd_after", bs="100M", count=30 ) log.info("Clean up the system") fs_util.client_clean_up( "umount", kernel_clients=[clients[0]], mounting_dir=kernel_mounting_dir_1 ) fs_util.client_clean_up( "umount", kernel_clients=[clients[1]], mounting_dir=kernel_mounting_dir_2 ) fs_util.client_clean_up( "umount", fuse_clients=[clients[0]], mounting_dir=fuse_mounting_dir_1 ) fs_util.client_clean_up( "umount", fuse_clients=[clients[1]], mounting_dir=fuse_mounting_dir_2 ) clients[1].exec_command( sudo=True, cmd="ceph config set mon mon_allow_pool_delete true" ) for subvolume in subvolume_list: fs_util.remove_subvolume(clients[0], **subvolume) for subvolumegroup in subvolumegroup_list: fs_util.remove_subvolumegroup(clients[0], **subvolumegroup) return 0 except Exception as e: log.error(e) log.error(traceback.format_exc()) return 1 def run_ios(client, mounting_dir, file_name, bs, count): client.exec_command( sudo=True, cmd=f"dd if=/dev/zero of={mounting_dir}{client.node.hostname}{file_name} bs={bs} " f"count={count}", )
# -*- coding: future_fstrings -*- import json import datetime import adal from .reports import Reports from .datasets import Datasets from .imports import Imports from .groups import Groups from .activity_logs import ActivityLogs class PowerBIClient: default_resource_url = 'https://analysis.windows.net/powerbi/api' default_api_url = 'https://api.powerbi.com' default_authority_url = 'https://login.windows.net/common' api_version_snippet = 'v1.0' api_myorg_snippet = 'myorg' @staticmethod def get_client_with_username_password(client_id, username, password, authority_url=None, resource_url=None, api_url=None): """ Constructs a client with the option of using common defaults. :param client_id: The Power BI Client ID :param username: Username :param password: Password :param authority_url: The authority_url; defaults to 'https://login.windows.net/common' :param resource_url: The resource_url; defaults to 'https://analysis.windows.net/powerbi/api' :param api_url: The api_url: defaults to 'https://api.powerbi.com' :return: """ if authority_url is None: authority_url = PowerBIClient.default_authority_url if resource_url is None: resource_url = PowerBIClient.default_resource_url if api_url is None: api_url = PowerBIClient.default_api_url context = adal.AuthenticationContext(authority=authority_url, validate_authority=True, api_version=None) # get your authentication token token = context.acquire_token_with_username_password(resource=resource_url, client_id=client_id, username=username, password=password) return PowerBIClient(api_url, token) def __init__(self, api_url, token): self.api_url = api_url self.token = token self.datasets = Datasets(self) self.reports = Reports(self) self.imports = Imports(self) self.groups = Groups(self) self.activity_logs = ActivityLogs(self) @property def auth_header(self): if self._auth_header is None: self._auth_header = { 'Authorization': f'Bearer {self.token['accessToken']}' } return self._auth_header _auth_header = None class EffectiveIdentity: username_key = 'username' roles_key = 'roles' datasets_key = 'datasets' def __init__(self, username, roles, datasets): self.username = username self.roles = roles self.datasets = datasets class EffectiveIdentityEncoder(json.JSONEncoder): def default(self, o): return { EffectiveIdentity.username_key: o.username, EffectiveIdentity.roles_key: o.roles, EffectiveIdentity.datasets_key: o.datasets, } class TokenRequest: access_level_key = 'accessLevel' dataset_id_key = 'datasetId' allow_saveas_key = 'allowSaveAs' identities_key = 'identities' def __init__(self, access_level, dataset_id=None, allow_saveas=None, identities=None): self.access_level = access_level self.dataset_id = dataset_id self.allow_saveas = allow_saveas self.identities = identities class TokenRequestEncoder(json.JSONEncoder): def default(self, o): effective_identity_encoder = EffectiveIdentityEncoder() json_dict = { TokenRequest.access_level_key: o.access_level } if o.dataset_id is not None: json_dict[TokenRequest.dataset_id_key] = o.dataset_id if o.allow_saveas is not None: json_dict[TokenRequest.allow_saveas_key] = o.allow_saveas if o.identities is not None: json_dict[TokenRequest.identities_key] = [effective_identity_encoder.default(x) for x in o.identities] return json_dict class EmbedToken: token_key = 'token' token_id_key = 'tokenId' expiration_key = 'expiration' def __init__(self, token, token_id, expiration): self.token = token self.token_id = token_id self.expiration = expiration @classmethod def from_dict(cls, dictionary): if cls.token_key not in dictionary: raise RuntimeError(f'Token dict has no {cls.token_key} key') token = dictionary[cls.token_key] token_id = dictionary[cls.token_id_key] expiration = dictionary[cls.expiration_key] return EmbedToken(token, token_id, expiration) @property def expiration_as_datetime(self): return datetime.datetime.strptime(self.expiration, '%Y-%m-%dT%H:%M:%SZ')
# -*- coding: future_fstrings -*- import json import datetime import adal from .reports import Reports from .datasets import Datasets from .imports import Imports from .groups import Groups from .activity_logs import ActivityLogs class PowerBIClient: default_resource_url = 'https://analysis.windows.net/powerbi/api' default_api_url = 'https://api.powerbi.com' default_authority_url = 'https://login.windows.net/common' api_version_snippet = 'v1.0' api_myorg_snippet = 'myorg' @staticmethod def get_client_with_username_password(client_id, username, password, authority_url=None, resource_url=None, api_url=None): """ Constructs a client with the option of using common defaults. :param client_id: The Power BI Client ID :param username: Username :param password: Password :param authority_url: The authority_url; defaults to 'https://login.windows.net/common' :param resource_url: The resource_url; defaults to 'https://analysis.windows.net/powerbi/api' :param api_url: The api_url: defaults to 'https://api.powerbi.com' :return: """ if authority_url is None: authority_url = PowerBIClient.default_authority_url if resource_url is None: resource_url = PowerBIClient.default_resource_url if api_url is None: api_url = PowerBIClient.default_api_url context = adal.AuthenticationContext(authority=authority_url, validate_authority=True, api_version=None) # get your authentication token token = context.acquire_token_with_username_password(resource=resource_url, client_id=client_id, username=username, password=password) return PowerBIClient(api_url, token) def __init__(self, api_url, token): self.api_url = api_url self.token = token self.datasets = Datasets(self) self.reports = Reports(self) self.imports = Imports(self) self.groups = Groups(self) self.activity_logs = ActivityLogs(self) @property def auth_header(self): if self._auth_header is None: self._auth_header = { 'Authorization': f'Bearer {self.token["accessToken"]}' } return self._auth_header _auth_header = None class EffectiveIdentity: username_key = 'username' roles_key = 'roles' datasets_key = 'datasets' def __init__(self, username, roles, datasets): self.username = username self.roles = roles self.datasets = datasets class EffectiveIdentityEncoder(json.JSONEncoder): def default(self, o): return { EffectiveIdentity.username_key: o.username, EffectiveIdentity.roles_key: o.roles, EffectiveIdentity.datasets_key: o.datasets, } class TokenRequest: access_level_key = 'accessLevel' dataset_id_key = 'datasetId' allow_saveas_key = 'allowSaveAs' identities_key = 'identities' def __init__(self, access_level, dataset_id=None, allow_saveas=None, identities=None): self.access_level = access_level self.dataset_id = dataset_id self.allow_saveas = allow_saveas self.identities = identities class TokenRequestEncoder(json.JSONEncoder): def default(self, o): effective_identity_encoder = EffectiveIdentityEncoder() json_dict = { TokenRequest.access_level_key: o.access_level } if o.dataset_id is not None: json_dict[TokenRequest.dataset_id_key] = o.dataset_id if o.allow_saveas is not None: json_dict[TokenRequest.allow_saveas_key] = o.allow_saveas if o.identities is not None: json_dict[TokenRequest.identities_key] = [effective_identity_encoder.default(x) for x in o.identities] return json_dict class EmbedToken: token_key = 'token' token_id_key = 'tokenId' expiration_key = 'expiration' def __init__(self, token, token_id, expiration): self.token = token self.token_id = token_id self.expiration = expiration @classmethod def from_dict(cls, dictionary): if cls.token_key not in dictionary: raise RuntimeError(f'Token dict has no {cls.token_key} key') token = dictionary[cls.token_key] token_id = dictionary[cls.token_id_key] expiration = dictionary[cls.expiration_key] return EmbedToken(token, token_id, expiration) @property def expiration_as_datetime(self): return datetime.datetime.strptime(self.expiration, '%Y-%m-%dT%H:%M:%SZ')
"""Covid View""" __docformat__ = "numpy" import os import matplotlib.dates as mdates import matplotlib.pyplot as plt import pandas as pd from rich.console import Console import gamestonk_terminal.feature_flags as gtff from gamestonk_terminal.alternative.covid import covid_model from gamestonk_terminal.config_plot import PLOT_DPI from gamestonk_terminal.helper_funcs import ( plot_autoscale, export_data, rich_table_from_df, ) t_console = Console() def display_covid_ov(country, raw: bool = False, limit: int = 10, export: str = ""): """Show historical cases and deaths by country Parameters ---------- country: str Country to get data for raw: bool Flag to display raw data limit: int Number of raw data to show export: str Format to export data """ t_console.print("") cases = covid_model.get_global_cases(country) / 1_000 deaths = covid_model.get_global_deaths(country) ov = pd.concat([cases, deaths], axis=1) ov.columns = ["Cases", "Deaths"] fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI) ax.plot(cases.index, cases, alpha=0.2, c="b") ax.plot(cases.index, cases.rolling(7).mean(), lw=4, c="b") ax.set_ylabel("Cases (1k)", color="blue") ax.tick_params(axis="y", labelcolor="blue") ax2 = ax.twinx() ax2.plot(deaths.index, deaths, "r", alpha=0.2) ax2.plot(deaths.index, deaths.rolling(7).mean(), "r", lw=4) ax2.grid() ax2.set_title(f"Overview for {country.upper()}") ax2.set_xlabel("Date") ax2.set_ylabel("Deaths", color="red") ax2.tick_params(axis="y", labelcolor="red") dateFmt = mdates.DateFormatter("%Y-%m-%d") ax.xaxis.set_major_formatter(dateFmt) ax.tick_params(axis="x", labelrotation=45) ax.set_xlim(ov.index[0], ov.index[-1]) fig.tight_layout(pad=2) if gtff.USE_ION: plt.ion() plt.show() if raw: ov.index = [x.strftime("%Y-%m-%d") for x in ov.index] if gtff.USE_TABULATE_DF: t_console.print( rich_table_from_df( ov.tail(limit), headers=[x.title() for x in ov.columns], show_index=True, index_name="Date", title=f"[bold]{country} COVID Numbers[/bold]", ) ) else: t_console.print(ov.tail(limit).to_string()) t_console.print("") if export: export_data(export, os.path.dirname(os.path.abspath(__file__)), "ov", ov) def display_covid_stat( country, stat: str = "cases", raw: bool = False, limit: int = 10, export: str = "" ): """Show historical cases and deaths by country Parameters ---------- country: str Country to get data for stat: str Statistic to get. Either "cases", "deaths" or "rates" raw: bool Flag to display raw data limit: int Number of raw data to show export: str Format to export data """ t_console.print("") if stat == "cases": data = covid_model.get_global_cases(country) / 1_000 elif stat == "deaths": data = covid_model.get_global_deaths(country) elif stat == "rates": cases = covid_model.get_global_cases(country) deaths = covid_model.get_global_deaths(country) data = (deaths / cases).fillna(0) * 100 else: t_console.print("Invalid stat selected.\n") return fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI) ax.plot(data.index, data, alpha=0.2, c="b") ax.plot(data.index, data.rolling(7).mean(), lw=4, c="b") if stat == "cases": ax.set_ylabel(stat.title() + " (1k)", color="blue") else: ax.set_ylabel(stat.title(), color="blue") ax.tick_params(axis="y", labelcolor="blue") ax.grid("on") dateFmt = mdates.DateFormatter("%Y-%m-%d") ax.xaxis.set_major_formatter(dateFmt) ax.tick_params(axis="x", labelrotation=45) ax.spines["right"].set_visible(False) ax.spines["top"].set_visible(False) ax.set_title(f"{country} COVID {stat}") ax.set_xlim(data.index[0], data.index[-1]) fig.tight_layout(pad=2) if gtff.USE_ION: plt.ion() plt.show() if raw: data.index = [x.strftime("%Y-%m-%d") for x in data.index] if gtff.USE_TABULATE_DF: t_console.print( rich_table_from_df( data.tail(limit), headers=[stat.title()], show_index=True, index_name="Date", title=f"[bold]{country} COVID {stat}[/bold]", ) ) else: t_console.print(data.tail(limit).to_string()) t_console.print("") export_data(export, os.path.dirname(os.path.abspath(__file__)), stat, data) def display_country_slopes( days_back: int = 30, limit: int = 10, ascend: bool = False, threshold: int = 10000, export: str = "", ): """ Parameters ---------- days_back: int Number of historical days to get slope for limit: int Number to show in table ascend: bool Boolean to sort in ascending order threshold: int Threshold for total cases over period export : str Format to export data """ hist_slope = covid_model.get_case_slopes(days_back, threshold).sort_values( by="Slope", ascending=ascend ) if gtff.USE_TABULATE_DF: t_console.print( rich_table_from_df( hist_slope.head(limit), show_index=True, index_name="Country", title=f"[bold]{("Highest","Lowest")[ascend]} Sloping Cases[/bold] (Cases/Day)", ) ) else: t_console.print(hist_slope.head(limit).to_string()) t_console.print("") export_data( export, os.path.dirname(os.path.abspath(__file__)), f"slopes_{days_back}day", hist_slope, )
"""Covid View""" __docformat__ = "numpy" import os import matplotlib.dates as mdates import matplotlib.pyplot as plt import pandas as pd from rich.console import Console import gamestonk_terminal.feature_flags as gtff from gamestonk_terminal.alternative.covid import covid_model from gamestonk_terminal.config_plot import PLOT_DPI from gamestonk_terminal.helper_funcs import ( plot_autoscale, export_data, rich_table_from_df, ) t_console = Console() def display_covid_ov(country, raw: bool = False, limit: int = 10, export: str = ""): """Show historical cases and deaths by country Parameters ---------- country: str Country to get data for raw: bool Flag to display raw data limit: int Number of raw data to show export: str Format to export data """ t_console.print("") cases = covid_model.get_global_cases(country) / 1_000 deaths = covid_model.get_global_deaths(country) ov = pd.concat([cases, deaths], axis=1) ov.columns = ["Cases", "Deaths"] fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI) ax.plot(cases.index, cases, alpha=0.2, c="b") ax.plot(cases.index, cases.rolling(7).mean(), lw=4, c="b") ax.set_ylabel("Cases (1k)", color="blue") ax.tick_params(axis="y", labelcolor="blue") ax2 = ax.twinx() ax2.plot(deaths.index, deaths, "r", alpha=0.2) ax2.plot(deaths.index, deaths.rolling(7).mean(), "r", lw=4) ax2.grid() ax2.set_title(f"Overview for {country.upper()}") ax2.set_xlabel("Date") ax2.set_ylabel("Deaths", color="red") ax2.tick_params(axis="y", labelcolor="red") dateFmt = mdates.DateFormatter("%Y-%m-%d") ax.xaxis.set_major_formatter(dateFmt) ax.tick_params(axis="x", labelrotation=45) ax.set_xlim(ov.index[0], ov.index[-1]) fig.tight_layout(pad=2) if gtff.USE_ION: plt.ion() plt.show() if raw: ov.index = [x.strftime("%Y-%m-%d") for x in ov.index] if gtff.USE_TABULATE_DF: t_console.print( rich_table_from_df( ov.tail(limit), headers=[x.title() for x in ov.columns], show_index=True, index_name="Date", title=f"[bold]{country} COVID Numbers[/bold]", ) ) else: t_console.print(ov.tail(limit).to_string()) t_console.print("") if export: export_data(export, os.path.dirname(os.path.abspath(__file__)), "ov", ov) def display_covid_stat( country, stat: str = "cases", raw: bool = False, limit: int = 10, export: str = "" ): """Show historical cases and deaths by country Parameters ---------- country: str Country to get data for stat: str Statistic to get. Either "cases", "deaths" or "rates" raw: bool Flag to display raw data limit: int Number of raw data to show export: str Format to export data """ t_console.print("") if stat == "cases": data = covid_model.get_global_cases(country) / 1_000 elif stat == "deaths": data = covid_model.get_global_deaths(country) elif stat == "rates": cases = covid_model.get_global_cases(country) deaths = covid_model.get_global_deaths(country) data = (deaths / cases).fillna(0) * 100 else: t_console.print("Invalid stat selected.\n") return fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI) ax.plot(data.index, data, alpha=0.2, c="b") ax.plot(data.index, data.rolling(7).mean(), lw=4, c="b") if stat == "cases": ax.set_ylabel(stat.title() + " (1k)", color="blue") else: ax.set_ylabel(stat.title(), color="blue") ax.tick_params(axis="y", labelcolor="blue") ax.grid("on") dateFmt = mdates.DateFormatter("%Y-%m-%d") ax.xaxis.set_major_formatter(dateFmt) ax.tick_params(axis="x", labelrotation=45) ax.spines["right"].set_visible(False) ax.spines["top"].set_visible(False) ax.set_title(f"{country} COVID {stat}") ax.set_xlim(data.index[0], data.index[-1]) fig.tight_layout(pad=2) if gtff.USE_ION: plt.ion() plt.show() if raw: data.index = [x.strftime("%Y-%m-%d") for x in data.index] if gtff.USE_TABULATE_DF: t_console.print( rich_table_from_df( data.tail(limit), headers=[stat.title()], show_index=True, index_name="Date", title=f"[bold]{country} COVID {stat}[/bold]", ) ) else: t_console.print(data.tail(limit).to_string()) t_console.print("") export_data(export, os.path.dirname(os.path.abspath(__file__)), stat, data) def display_country_slopes( days_back: int = 30, limit: int = 10, ascend: bool = False, threshold: int = 10000, export: str = "", ): """ Parameters ---------- days_back: int Number of historical days to get slope for limit: int Number to show in table ascend: bool Boolean to sort in ascending order threshold: int Threshold for total cases over period export : str Format to export data """ hist_slope = covid_model.get_case_slopes(days_back, threshold).sort_values( by="Slope", ascending=ascend ) if gtff.USE_TABULATE_DF: t_console.print( rich_table_from_df( hist_slope.head(limit), show_index=True, index_name="Country", title=f"[bold]{('Highest','Lowest')[ascend]} Sloping Cases[/bold] (Cases/Day)", ) ) else: t_console.print(hist_slope.head(limit).to_string()) t_console.print("") export_data( export, os.path.dirname(os.path.abspath(__file__)), f"slopes_{days_back}day", hist_slope, )